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
cask 'boom' do version '1.6.9,1575451705' sha256 '444b5513c92eb0975494509908786a31f087a0af0e58fa5f312a156318be22f8' # devmate.com/com.globaldelight.Boom2/ was verified as official when first introduced to the cask url "https://dl.devmate.com/com.globaldelight.Boom2/#{version.before_comma}/#{version.after_comma}/Boom2-#{version.before_comma}.dmg" appcast 'https://updates.devmate.com/com.globaldelight.Boom2.xml' name 'Boom' homepage 'https://www.globaldelight.com/boom' depends_on macos: '>= :yosemite' app 'Boom 2.app' uninstall kext: 'com.globaldelight.driver.Boom2Device', launchctl: [ 'com.globaldelight.Boom2.*', 'com.globaldelight.Boom2Daemon', ], signal: ['TERM', 'com.globaldelight.Boom2'] zap trash: [ '~/Library/Application Support/com.globaldelight.Boom2', '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.globaldelight.boom2.sfl*', '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.globaldelight.boom2daemon.sfl*', '~/Library/Preferences/com.globaldelight.Boom2.plist', '~/Library/Preferences/com.globaldelight.Boom2Daemon.plist', ] end
sscotth/homebrew-cask
Casks/boom.rb
Ruby
bsd-2-clause
1,400
// Copyright (C) 2015 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es6id: 12.10.3 description: Invocation of `Symbol.toPrimitive` method during coercion info: | [...] 7. Return the result of performing Abstract Equality Comparison rval == lval. ES6 Section 7.2.12 Abstract Equality Comparison [...] 10. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then return the result of the comparison x == ToPrimitive(y). ES6 Section 7.1.1 ToPrimitive ( input [, PreferredType] ) 1. If PreferredType was not passed, let hint be "default". [...] 4. Let exoticToPrim be GetMethod(input, @@toPrimitive). 5. ReturnIfAbrupt(exoticToPrim). 6. If exoticToPrim is not undefined, then a. Let result be Call(exoticToPrim, input, «hint»). [...] features: [Symbol.toPrimitive] ---*/ var y = {}; var callCount = 0; var thisVal, args; y[Symbol.toPrimitive] = function() { callCount += 1; thisVal = this; args = arguments; }; 0 == y; assert.sameValue(callCount, 1, 'method invoked exactly once'); assert.sameValue(thisVal, y, '`this` value is the object being compared'); assert.sameValue(args.length, 1, 'method invoked with exactly one argument'); assert.sameValue( args[0], 'default', 'method invoked with the string "default" as the first argument' );
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/equals/coerce-symbol-to-prim-invocation.js
JavaScript
bsd-2-clause
1,426
cask 'jetbrains-toolbox' do version '1.0.1569' sha256 '5e47e404f7b9aa6e5d500eceb59801a9c1dc4da104e29fe1e392956188369b71' url "https://download.jetbrains.com/toolbox/jetbrains-toolbox-#{version}.dmg" name 'JetBrains Toolbox' homepage 'https://www.jetbrains.com/' license :gratis app 'JetBrains Toolbox.app' end
pacav69/homebrew-cask
Casks/jetbrains-toolbox.rb
Ruby
bsd-2-clause
326
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.wrapper; import java.io.*; import java.net.URI; import java.util.*; import java.util.concurrent.Callable; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class Install { public static final String DEFAULT_DISTRIBUTION_PATH = "wrapper/dists"; private final IDownload download; private final PathAssembler pathAssembler; private final ExclusiveFileAccessManager exclusiveFileAccessManager = new ExclusiveFileAccessManager(120000, 200); public Install(IDownload download, PathAssembler pathAssembler) { this.download = download; this.pathAssembler = pathAssembler; } public File createDist(WrapperConfiguration configuration) throws Exception { final URI distributionUrl = configuration.getDistribution(); final PathAssembler.LocalDistribution localDistribution = pathAssembler.getDistribution(configuration); final File distDir = localDistribution.getDistributionDir(); final File localZipFile = localDistribution.getZipFile(); return exclusiveFileAccessManager.access(localZipFile, new Callable<File>() { public File call() throws Exception { final File markerFile = new File(localZipFile.getParentFile(), localZipFile.getName() + ".ok"); if (distDir.isDirectory() && markerFile.isFile()) { return getDistributionRoot(distDir, distDir.getAbsolutePath()); } boolean needsDownload = !localZipFile.isFile(); if (needsDownload) { File tmpZipFile = new File(localZipFile.getParentFile(), localZipFile.getName() + ".part"); tmpZipFile.delete(); System.out.println("Downloading " + distributionUrl); download.download(distributionUrl, tmpZipFile); tmpZipFile.renameTo(localZipFile); } List<File> topLevelDirs = listDirs(distDir); for (File dir : topLevelDirs) { System.out.println("Deleting directory " + dir.getAbsolutePath()); deleteDir(dir); } System.out.println("Unzipping " + localZipFile.getAbsolutePath() + " to " + distDir.getAbsolutePath()); unzip(localZipFile, distDir); File root = getDistributionRoot(distDir, distributionUrl.toString()); setExecutablePermissions(root); markerFile.createNewFile(); return root; } }); } private File getDistributionRoot(File distDir, String distributionDescription) { List<File> dirs = listDirs(distDir); if (dirs.isEmpty()) { throw new RuntimeException(String.format("Gradle distribution '%s' does not contain any directories. Expected to find exactly 1 directory.", distributionDescription)); } if (dirs.size() != 1) { throw new RuntimeException(String.format("Gradle distribution '%s' contains too many directories. Expected to find exactly 1 directory.", distributionDescription)); } return dirs.get(0); } private List<File> listDirs(File distDir) { List<File> dirs = new ArrayList<File>(); if (distDir.exists()) { for (File file : distDir.listFiles()) { if (file.isDirectory()) { dirs.add(file); } } } return dirs; } private void setExecutablePermissions(File gradleHome) { if (isWindows()) { return; } File gradleCommand = new File(gradleHome, "bin/gradle"); String errorMessage = null; try { ProcessBuilder pb = new ProcessBuilder("chmod", "755", gradleCommand.getCanonicalPath()); Process p = pb.start(); if (p.waitFor() == 0) { System.out.println("Set executable permissions for: " + gradleCommand.getAbsolutePath()); } else { BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); Formatter stdout = new Formatter(); String line; while ((line = is.readLine()) != null) { stdout.format("%s%n", line); } errorMessage = stdout.toString(); } } catch (IOException e) { errorMessage = e.getMessage(); } catch (InterruptedException e) { errorMessage = e.getMessage(); } if (errorMessage != null) { System.out.println("Could not set executable permissions for: " + gradleCommand.getAbsolutePath()); System.out.println("Please do this manually if you want to use the Gradle UI."); } } private boolean isWindows() { String osName = System.getProperty("os.name").toLowerCase(Locale.US); if (osName.indexOf("windows") > -1) { return true; } return false; } private boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } // The directory is now empty so delete it return dir.delete(); } private void unzip(File zip, File dest) throws IOException { Enumeration entries; ZipFile zipFile = new ZipFile(zip); try { entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { (new File(dest, entry.getName())).mkdirs(); continue; } OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(dest, entry.getName()))); try { copyInputStream(zipFile.getInputStream(entry), outputStream); } finally { outputStream.close(); } } } finally { zipFile.close(); } } private void copyInputStream(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); } in.close(); out.close(); } }
Pushjet/Pushjet-Android
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/wrapper/org/gradle/wrapper/Install.java
Java
bsd-2-clause
7,302
cask 'rubymine' do version '2018.1.4,181.5281.41' sha256 'e89880cfed154e01545063f830e444f0a9ae3509b177f254a92032544cffe24a' url "https://download.jetbrains.com/ruby/RubyMine-#{version.before_comma}.dmg" appcast 'https://data.services.jetbrains.com/products/releases?code=RM&latest=true&type=release' name 'RubyMine' homepage 'https://www.jetbrains.com/ruby/' auto_updates true app 'RubyMine.app' uninstall_postflight do ENV['PATH'].split(File::PATH_SEPARATOR).map { |path| File.join(path, 'mine') }.each { |path| File.delete(path) if File.exist?(path) && File.readlines(path).grep(%r{# see com.intellij.idea.SocketLock for the server side of this interface}).any? } end zap trash: [ "~/Library/Application Support/RubyMine#{version.major_minor}", "~/Library/Caches/RubyMine#{version.major_minor}", "~/Library/Logs/RubyMine#{version.major_minor}", "~/Library/Preferences/RubyMine#{version.major_minor}", ] end
goxberry/homebrew-cask
Casks/rubymine.rb
Ruby
bsd-2-clause
1,013
var loopback = require('loopback'), boot = require('loopback-boot'); var app = loopback(); boot(app, __dirname); module.exports = app;
maschinenbau/freecodecamp
client/loopbackClient.js
JavaScript
bsd-3-clause
142
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/allocator/allocator_extension.h" #include "base/logging.h" namespace base { namespace allocator { bool GetProperty(const char* name, size_t* value) { thunks::GetPropertyFunction get_property_function = base::allocator::thunks::GetGetPropertyFunction(); return get_property_function != NULL && get_property_function(name, value); } void GetStats(char* buffer, int buffer_length) { DCHECK_GT(buffer_length, 0); thunks::GetStatsFunction get_stats_function = base::allocator::thunks::GetGetStatsFunction(); if (get_stats_function) get_stats_function(buffer, buffer_length); else buffer[0] = '\0'; } void ReleaseFreeMemory() { thunks::ReleaseFreeMemoryFunction release_free_memory_function = base::allocator::thunks::GetReleaseFreeMemoryFunction(); if (release_free_memory_function) release_free_memory_function(); } void SetGetPropertyFunction( thunks::GetPropertyFunction get_property_function) { DCHECK_EQ(base::allocator::thunks::GetGetPropertyFunction(), reinterpret_cast<thunks::GetPropertyFunction>(NULL)); base::allocator::thunks::SetGetPropertyFunction(get_property_function); } void SetGetStatsFunction(thunks::GetStatsFunction get_stats_function) { DCHECK_EQ(base::allocator::thunks::GetGetStatsFunction(), reinterpret_cast<thunks::GetStatsFunction>(NULL)); base::allocator::thunks::SetGetStatsFunction(get_stats_function); } void SetReleaseFreeMemoryFunction( thunks::ReleaseFreeMemoryFunction release_free_memory_function) { DCHECK_EQ(base::allocator::thunks::GetReleaseFreeMemoryFunction(), reinterpret_cast<thunks::ReleaseFreeMemoryFunction>(NULL)); base::allocator::thunks::SetReleaseFreeMemoryFunction( release_free_memory_function); } } // namespace allocator } // namespace base
leighpauls/k2cro4
base/allocator/allocator_extension.cc
C++
bsd-3-clause
1,997
""" Generating and counting primes. """ from __future__ import print_function, division import random from bisect import bisect # Using arrays for sieving instead of lists greatly reduces # memory consumption from array import array as _array from sympy import Function, S from sympy.core.compatibility import as_int, range from .primetest import isprime def _azeros(n): return _array('l', [0]*n) def _aset(*v): return _array('l', v) def _arange(a, b): return _array('l', range(a, b)) class Sieve: """An infinite list of prime numbers, implemented as a dynamically growing sieve of Eratosthenes. When a lookup is requested involving an odd number that has not been sieved, the sieve is automatically extended up to that number. Examples ======== >>> from sympy import sieve >>> sieve._reset() # this line for doctest only >>> 25 in sieve False >>> sieve._list array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23]) """ # data shared (and updated) by all Sieve instances def __init__(self): self._n = 6 self._list = _aset(2, 3, 5, 7, 11, 13) # primes self._tlist = _aset(0, 1, 1, 2, 2, 4) # totient self._mlist = _aset(0, 1, -1, -1, 0, -1) # mobius assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist)) def __repr__(self): return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n" "%s sieve (%i): %i, %i, %i, ... %i, %i\n" "%s sieve (%i): %i, %i, %i, ... %i, %i>") % ( 'prime', len(self._list), self._list[0], self._list[1], self._list[2], self._list[-2], self._list[-1], 'totient', len(self._tlist), self._tlist[0], self._tlist[1], self._tlist[2], self._tlist[-2], self._tlist[-1], 'mobius', len(self._mlist), self._mlist[0], self._mlist[1], self._mlist[2], self._mlist[-2], self._mlist[-1]) def _reset(self, prime=None, totient=None, mobius=None): """Reset all caches (default). To reset one or more set the desired keyword to True.""" if all(i is None for i in (prime, totient, mobius)): prime = totient = mobius = True if prime: self._list = self._list[:self._n] if totient: self._tlist = self._tlist[:self._n] if mobius: self._mlist = self._mlist[:self._n] def extend(self, n): """Grow the sieve to cover all primes <= n (a real number). Examples ======== >>> from sympy import sieve >>> sieve._reset() # this line for doctest only >>> sieve.extend(30) >>> sieve[10] == 29 True """ n = int(n) if n <= self._list[-1]: return # We need to sieve against all bases up to sqrt(n). # This is a recursive call that will do nothing if there are enough # known bases already. maxbase = int(n**0.5) + 1 self.extend(maxbase) # Create a new sieve starting from sqrt(n) begin = self._list[-1] + 1 newsieve = _arange(begin, n + 1) # Now eliminate all multiples of primes in [2, sqrt(n)] for p in self.primerange(2, maxbase): # Start counting at a multiple of p, offsetting # the index to account for the new sieve's base index startindex = (-begin) % p for i in range(startindex, len(newsieve), p): newsieve[i] = 0 # Merge the sieves self._list += _array('l', [x for x in newsieve if x]) def extend_to_no(self, i): """Extend to include the ith prime number. Parameters ========== i : integer Examples ======== >>> from sympy import sieve >>> sieve._reset() # this line for doctest only >>> sieve.extend_to_no(9) >>> sieve._list array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23]) Notes ===== The list is extended by 50% if it is too short, so it is likely that it will be longer than requested. """ i = as_int(i) while len(self._list) < i: self.extend(int(self._list[-1] * 1.5)) def primerange(self, a, b): """Generate all prime numbers in the range [a, b). Examples ======== >>> from sympy import sieve >>> print([i for i in sieve.primerange(7, 18)]) [7, 11, 13, 17] """ from sympy.functions.elementary.integers import ceiling # wrapping ceiling in as_int will raise an error if there was a problem # determining whether the expression was exactly an integer or not a = max(2, as_int(ceiling(a))) b = as_int(ceiling(b)) if a >= b: return self.extend(b) i = self.search(a)[1] maxi = len(self._list) + 1 while i < maxi: p = self._list[i - 1] if p < b: yield p i += 1 else: return def totientrange(self, a, b): """Generate all totient numbers for the range [a, b). Examples ======== >>> from sympy import sieve >>> print([i for i in sieve.totientrange(7, 18)]) [6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16] """ from sympy.functions.elementary.integers import ceiling # wrapping ceiling in as_int will raise an error if there was a problem # determining whether the expression was exactly an integer or not a = max(1, as_int(ceiling(a))) b = as_int(ceiling(b)) n = len(self._tlist) if a >= b: return elif b <= n: for i in range(a, b): yield self._tlist[i] else: self._tlist += _arange(n, b) for i in range(1, n): ti = self._tlist[i] startindex = (n + i - 1) // i * i for j in range(startindex, b, i): self._tlist[j] -= ti if i >= a: yield ti for i in range(n, b): ti = self._tlist[i] for j in range(2 * i, b, i): self._tlist[j] -= ti if i >= a: yield ti def mobiusrange(self, a, b): """Generate all mobius numbers for the range [a, b). Parameters ========== a : integer First number in range b : integer First number outside of range Examples ======== >>> from sympy import sieve >>> print([i for i in sieve.mobiusrange(7, 18)]) [-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1] """ from sympy.functions.elementary.integers import ceiling # wrapping ceiling in as_int will raise an error if there was a problem # determining whether the expression was exactly an integer or not a = max(1, as_int(ceiling(a))) b = as_int(ceiling(b)) n = len(self._mlist) if a >= b: return elif b <= n: for i in range(a, b): yield self._mlist[i] else: self._mlist += _azeros(b - n) for i in range(1, n): mi = self._mlist[i] startindex = (n + i - 1) // i * i for j in range(startindex, b, i): self._mlist[j] -= mi if i >= a: yield mi for i in range(n, b): mi = self._mlist[i] for j in range(2 * i, b, i): self._mlist[j] -= mi if i >= a: yield mi def search(self, n): """Return the indices i, j of the primes that bound n. If n is prime then i == j. Although n can be an expression, if ceiling cannot convert it to an integer then an n error will be raised. Examples ======== >>> from sympy import sieve >>> sieve.search(25) (9, 10) >>> sieve.search(23) (9, 9) """ from sympy.functions.elementary.integers import ceiling # wrapping ceiling in as_int will raise an error if there was a problem # determining whether the expression was exactly an integer or not test = as_int(ceiling(n)) n = as_int(n) if n < 2: raise ValueError("n should be >= 2 but got: %s" % n) if n > self._list[-1]: self.extend(n) b = bisect(self._list, n) if self._list[b - 1] == test: return b, b else: return b, b + 1 def __contains__(self, n): try: n = as_int(n) assert n >= 2 except (ValueError, AssertionError): return False if n % 2 == 0: return n == 2 a, b = self.search(n) return a == b def __getitem__(self, n): """Return the nth prime number""" if isinstance(n, slice): self.extend_to_no(n.stop) return self._list[n.start - 1:n.stop - 1:n.step] else: n = as_int(n) self.extend_to_no(n) return self._list[n - 1] # Generate a global object for repeated use in trial division etc sieve = Sieve() def prime(nth): """ Return the nth prime, with the primes indexed as prime(1) = 2, prime(2) = 3, etc.... The nth prime is approximately n*log(n). Logarithmic integral of x is a pretty nice approximation for number of primes <= x, i.e. li(x) ~ pi(x) In fact, for the numbers we are concerned about( x<1e11 ), li(x) - pi(x) < 50000 Also, li(x) > pi(x) can be safely assumed for the numbers which can be evaluated by this function. Here, we find the least integer m such that li(m) > n using binary search. Now pi(m-1) < li(m-1) <= n, We find pi(m - 1) using primepi function. Starting from m, we have to find n - pi(m-1) more primes. For the inputs this implementation can handle, we will have to test primality for at max about 10**5 numbers, to get our answer. Examples ======== >>> from sympy import prime >>> prime(10) 29 >>> prime(1) 2 >>> prime(100000) 1299709 See Also ======== sympy.ntheory.primetest.isprime : Test if n is prime primerange : Generate all primes in a given range primepi : Return the number of primes less than or equal to n References ========== .. [1] https://en.wikipedia.org/wiki/Prime_number_theorem#Table_of_.CF.80.28x.29.2C_x_.2F_log_x.2C_and_li.28x.29 .. [2] https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number .. [3] https://en.wikipedia.org/wiki/Skewes%27_number """ n = as_int(nth) if n < 1: raise ValueError("nth must be a positive integer; prime(1) == 2") if n <= len(sieve._list): return sieve[n] from sympy.functions.special.error_functions import li from sympy.functions.elementary.exponential import log a = 2 # Lower bound for binary search b = int(n*(log(n) + log(log(n)))) # Upper bound for the search. while a < b: mid = (a + b) >> 1 if li(mid) > n: b = mid else: a = mid + 1 n_primes = primepi(a - 1) while n_primes < n: if isprime(a): n_primes += 1 a += 1 return a - 1 class primepi(Function): """ Represents the prime counting function pi(n) = the number of prime numbers less than or equal to n. Algorithm Description: In sieve method, we remove all multiples of prime p except p itself. Let phi(i,j) be the number of integers 2 <= k <= i which remain after sieving from primes less than or equal to j. Clearly, pi(n) = phi(n, sqrt(n)) If j is not a prime, phi(i,j) = phi(i, j - 1) if j is a prime, We remove all numbers(except j) whose smallest prime factor is j. Let x= j*a be such a number, where 2 <= a<= i / j Now, after sieving from primes <= j - 1, a must remain (because x, and hence a has no prime factor <= j - 1) Clearly, there are phi(i / j, j - 1) such a which remain on sieving from primes <= j - 1 Now, if a is a prime less than equal to j - 1, x= j*a has smallest prime factor = a, and has already been removed(by sieving from a). So, we don't need to remove it again. (Note: there will be pi(j - 1) such x) Thus, number of x, that will be removed are: phi(i / j, j - 1) - phi(j - 1, j - 1) (Note that pi(j - 1) = phi(j - 1, j - 1)) => phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1) So,following recursion is used and implemented as dp: phi(a, b) = phi(a, b - 1), if b is not a prime phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime Clearly a is always of the form floor(n / k), which can take at most 2*sqrt(n) values. Two arrays arr1,arr2 are maintained arr1[i] = phi(i, j), arr2[i] = phi(n // i, j) Finally the answer is arr2[1] Examples ======== >>> from sympy import primepi >>> primepi(25) 9 See Also ======== sympy.ntheory.primetest.isprime : Test if n is prime primerange : Generate all primes in a given range prime : Return the nth prime """ @classmethod def eval(cls, n): if n is S.Infinity: return S.Infinity if n is S.NegativeInfinity: return S.Zero try: n = int(n) except TypeError: if n.is_real == False or n is S.NaN: raise ValueError("n must be real") return if n < 2: return S.Zero if n <= sieve._list[-1]: return S(sieve.search(n)[0]) lim = int(n ** 0.5) lim -= 1 lim = max(lim, 0) while lim * lim <= n: lim += 1 lim -= 1 arr1 = [0] * (lim + 1) arr2 = [0] * (lim + 1) for i in range(1, lim + 1): arr1[i] = i - 1 arr2[i] = n // i - 1 for i in range(2, lim + 1): # Presently, arr1[k]=phi(k,i - 1), # arr2[k] = phi(n // k,i - 1) if arr1[i] == arr1[i - 1]: continue p = arr1[i - 1] for j in range(1, min(n // (i * i), lim) + 1): st = i * j if st <= lim: arr2[j] -= arr2[st] - p else: arr2[j] -= arr1[n // st] - p lim2 = min(lim, i * i - 1) for j in range(lim, lim2, -1): arr1[j] -= arr1[j // i] - p return S(arr2[1]) def nextprime(n, ith=1): """ Return the ith prime greater than n. i must be an integer. Notes ===== Potential primes are located at 6*j +/- 1. This property is used during searching. >>> from sympy import nextprime >>> [(i, nextprime(i)) for i in range(10, 15)] [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)] >>> nextprime(2, ith=2) # the 2nd prime after 2 5 See Also ======== prevprime : Return the largest prime smaller than n primerange : Generate all primes in a given range """ n = int(n) i = as_int(ith) if i > 1: pr = n j = 1 while 1: pr = nextprime(pr) j += 1 if j > i: break return pr if n < 2: return 2 if n < 7: return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n] if n <= sieve._list[-2]: l, u = sieve.search(n) if l == u: return sieve[u + 1] else: return sieve[u] nn = 6*(n//6) if nn == n: n += 1 if isprime(n): return n n += 4 elif n - nn == 5: n += 2 if isprime(n): return n n += 4 else: n = nn + 5 while 1: if isprime(n): return n n += 2 if isprime(n): return n n += 4 def prevprime(n): """ Return the largest prime smaller than n. Notes ===== Potential primes are located at 6*j +/- 1. This property is used during searching. >>> from sympy import prevprime >>> [(i, prevprime(i)) for i in range(10, 15)] [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)] See Also ======== nextprime : Return the ith prime greater than n primerange : Generates all primes in a given range """ from sympy.functions.elementary.integers import ceiling # wrapping ceiling in as_int will raise an error if there was a problem # determining whether the expression was exactly an integer or not n = as_int(ceiling(n)) if n < 3: raise ValueError("no preceding primes") if n < 8: return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n] if n <= sieve._list[-1]: l, u = sieve.search(n) if l == u: return sieve[l-1] else: return sieve[l] nn = 6*(n//6) if n - nn <= 1: n = nn - 1 if isprime(n): return n n -= 4 else: n = nn + 1 while 1: if isprime(n): return n n -= 2 if isprime(n): return n n -= 4 def primerange(a, b): """ Generate a list of all prime numbers in the range [a, b). If the range exists in the default sieve, the values will be returned from there; otherwise values will be returned but will not modify the sieve. Examples ======== >>> from sympy import primerange, sieve >>> print([i for i in primerange(1, 30)]) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] The Sieve method, primerange, is generally faster but it will occupy more memory as the sieve stores values. The default instance of Sieve, named sieve, can be used: >>> list(sieve.primerange(1, 30)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] Notes ===== Some famous conjectures about the occurrence of primes in a given range are [1]: - Twin primes: though often not, the following will give 2 primes an infinite number of times: primerange(6*n - 1, 6*n + 2) - Legendre's: the following always yields at least one prime primerange(n**2, (n+1)**2+1) - Bertrand's (proven): there is always a prime in the range primerange(n, 2*n) - Brocard's: there are at least four primes in the range primerange(prime(n)**2, prime(n+1)**2) The average gap between primes is log(n) [2]; the gap between primes can be arbitrarily large since sequences of composite numbers are arbitrarily large, e.g. the numbers in the sequence n! + 2, n! + 3 ... n! + n are all composite. See Also ======== nextprime : Return the ith prime greater than n prevprime : Return the largest prime smaller than n randprime : Returns a random prime in a given range primorial : Returns the product of primes based on condition Sieve.primerange : return range from already computed primes or extend the sieve to contain the requested range. References ========== .. [1] https://en.wikipedia.org/wiki/Prime_number .. [2] http://primes.utm.edu/notes/gaps.html """ from sympy.functions.elementary.integers import ceiling if a >= b: return # if we already have the range, return it if b <= sieve._list[-1]: for i in sieve.primerange(a, b): yield i return # otherwise compute, without storing, the desired range. # wrapping ceiling in as_int will raise an error if there was a problem # determining whether the expression was exactly an integer or not a = as_int(ceiling(a)) - 1 b = as_int(ceiling(b)) while 1: a = nextprime(a) if a < b: yield a else: return def randprime(a, b): """ Return a random prime number in the range [a, b). Bertrand's postulate assures that randprime(a, 2*a) will always succeed for a > 1. Examples ======== >>> from sympy import randprime, isprime >>> randprime(1, 30) #doctest: +SKIP 13 >>> isprime(randprime(1, 30)) True See Also ======== primerange : Generate all primes in a given range References ========== .. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate """ if a >= b: return a, b = map(int, (a, b)) n = random.randint(a - 1, b) p = nextprime(n) if p >= b: p = prevprime(b) if p < a: raise ValueError("no primes exist in the specified range") return p def primorial(n, nth=True): """ Returns the product of the first n primes (default) or the primes less than or equal to n (when ``nth=False``). Examples ======== >>> from sympy.ntheory.generate import primorial, randprime, primerange >>> from sympy import factorint, Mul, primefactors, sqrt >>> primorial(4) # the first 4 primes are 2, 3, 5, 7 210 >>> primorial(4, nth=False) # primes <= 4 are 2 and 3 6 >>> primorial(1) 2 >>> primorial(1, nth=False) 1 >>> primorial(sqrt(101), nth=False) 210 One can argue that the primes are infinite since if you take a set of primes and multiply them together (e.g. the primorial) and then add or subtract 1, the result cannot be divided by any of the original factors, hence either 1 or more new primes must divide this product of primes. In this case, the number itself is a new prime: >>> factorint(primorial(4) + 1) {211: 1} In this case two new primes are the factors: >>> factorint(primorial(4) - 1) {11: 1, 19: 1} Here, some primes smaller and larger than the primes multiplied together are obtained: >>> p = list(primerange(10, 20)) >>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p))) [2, 5, 31, 149] See Also ======== primerange : Generate all primes in a given range """ if nth: n = as_int(n) else: n = int(n) if n < 1: raise ValueError("primorial argument must be >= 1") p = 1 if nth: for i in range(1, n + 1): p *= prime(i) else: for i in primerange(2, n + 1): p *= i return p def cycle_length(f, x0, nmax=None, values=False): """For a given iterated sequence, return a generator that gives the length of the iterated cycle (lambda) and the length of terms before the cycle begins (mu); if ``values`` is True then the terms of the sequence will be returned instead. The sequence is started with value ``x0``. Note: more than the first lambda + mu terms may be returned and this is the cost of cycle detection with Brent's method; there are, however, generally less terms calculated than would have been calculated if the proper ending point were determined, e.g. by using Floyd's method. >>> from sympy.ntheory.generate import cycle_length This will yield successive values of i <-- func(i): >>> def iter(func, i): ... while 1: ... ii = func(i) ... yield ii ... i = ii ... A function is defined: >>> func = lambda i: (i**2 + 1) % 51 and given a seed of 4 and the mu and lambda terms calculated: >>> next(cycle_length(func, 4)) (6, 2) We can see what is meant by looking at the output: >>> n = cycle_length(func, 4, values=True) >>> list(ni for ni in n) [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14] There are 6 repeating values after the first 2. If a sequence is suspected of being longer than you might wish, ``nmax`` can be used to exit early (and mu will be returned as None): >>> next(cycle_length(func, 4, nmax = 4)) (4, None) >>> [ni for ni in cycle_length(func, 4, nmax = 4, values=True)] [17, 35, 2, 5] Code modified from: https://en.wikipedia.org/wiki/Cycle_detection. """ nmax = int(nmax or 0) # main phase: search successive powers of two power = lam = 1 tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0. i = 0 while tortoise != hare and (not nmax or i < nmax): i += 1 if power == lam: # time to start a new power of two? tortoise = hare power *= 2 lam = 0 if values: yield hare hare = f(hare) lam += 1 if nmax and i == nmax: if values: return else: yield nmax, None return if not values: # Find the position of the first repetition of length lambda mu = 0 tortoise = hare = x0 for i in range(lam): hare = f(hare) while tortoise != hare: tortoise = f(tortoise) hare = f(hare) mu += 1 if mu: mu -= 1 yield lam, mu def composite(nth): """ Return the nth composite number, with the composite numbers indexed as composite(1) = 4, composite(2) = 6, etc.... Examples ======== >>> from sympy import composite >>> composite(36) 52 >>> composite(1) 4 >>> composite(17737) 20000 See Also ======== sympy.ntheory.primetest.isprime : Test if n is prime primerange : Generate all primes in a given range primepi : Return the number of primes less than or equal to n prime : Return the nth prime compositepi : Return the number of positive composite numbers less than or equal to n """ n = as_int(nth) if n < 1: raise ValueError("nth must be a positive integer; composite(1) == 4") composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18] if n <= 10: return composite_arr[n - 1] a, b = 4, sieve._list[-1] if n <= b - primepi(b) - 1: while a < b - 1: mid = (a + b) >> 1 if mid - primepi(mid) - 1 > n: b = mid else: a = mid if isprime(a): a -= 1 return a from sympy.functions.special.error_functions import li from sympy.functions.elementary.exponential import log a = 4 # Lower bound for binary search b = int(n*(log(n) + log(log(n)))) # Upper bound for the search. while a < b: mid = (a + b) >> 1 if mid - li(mid) - 1 > n: b = mid else: a = mid + 1 n_composites = a - primepi(a) - 1 while n_composites > n: if not isprime(a): n_composites -= 1 a -= 1 if isprime(a): a -= 1 return a def compositepi(n): """ Return the number of positive composite numbers less than or equal to n. The first positive composite is 4, i.e. compositepi(4) = 1. Examples ======== >>> from sympy import compositepi >>> compositepi(25) 15 >>> compositepi(1000) 831 See Also ======== sympy.ntheory.primetest.isprime : Test if n is prime primerange : Generate all primes in a given range prime : Return the nth prime primepi : Return the number of primes less than or equal to n composite : Return the nth composite number """ n = int(n) if n < 4: return 0 return n - primepi(n) - 1
kaushik94/sympy
sympy/ntheory/generate.py
Python
bsd-3-clause
28,626
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "android_webview/browser/net/aw_url_request_job_factory.h" #include "net/base/net_errors.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_job_factory_impl.h" #include "net/url_request/url_request_job_manager.h" using net::NetworkDelegate; using net::URLRequest; using net::URLRequestJob; namespace android_webview { AwURLRequestJobFactory::AwURLRequestJobFactory() : next_factory_(new net::URLRequestJobFactoryImpl()) { } AwURLRequestJobFactory::~AwURLRequestJobFactory() { } bool AwURLRequestJobFactory::IsHandledProtocol( const std::string& scheme) const { // This introduces a dependency on the URLRequestJobManager // implementation. The assumption is that if true is returned from this // method it is still valid to return NULL from the // MaybeCreateJobWithProtocolHandler method and in that case the // URLRequestJobManager will try and create the URLRequestJob by using the // set of built in handlers. return true; } bool AwURLRequestJobFactory::IsHandledURL(const GURL& url) const { return true; } URLRequestJob* AwURLRequestJobFactory::MaybeCreateJobWithProtocolHandler( const std::string& scheme, URLRequest* request, NetworkDelegate* network_delegate) const { URLRequestJob* job = next_factory_->MaybeCreateJobWithProtocolHandler( scheme, request, network_delegate); if (job) return job; // If the URLRequestJobManager supports the scheme NULL should be returned // from this method. In that case the built in handlers in // URLRequestJobManager will then be used to create the job. if (net::URLRequestJobManager::GetInstance()->SupportsScheme(scheme)) return NULL; return new net::URLRequestErrorJob( request, network_delegate, net::ERR_UNKNOWN_URL_SCHEME); } bool AwURLRequestJobFactory::SetProtocolHandler( const std::string& scheme, ProtocolHandler* protocol_handler) { return next_factory_->SetProtocolHandler(scheme, protocol_handler); } void AwURLRequestJobFactory::AddInterceptor(Interceptor* interceptor) { next_factory_->AddInterceptor(interceptor); } URLRequestJob* AwURLRequestJobFactory::MaybeCreateJobWithInterceptor( URLRequest* request, NetworkDelegate* network_delegate) const { return next_factory_->MaybeCreateJobWithInterceptor( request, network_delegate); } URLRequestJob* AwURLRequestJobFactory::MaybeInterceptRedirect( const GURL& location, URLRequest* request, NetworkDelegate* network_delegate) const { return next_factory_->MaybeInterceptRedirect( location, request, network_delegate); } URLRequestJob* AwURLRequestJobFactory::MaybeInterceptResponse( URLRequest* request, NetworkDelegate* network_delegate) const { return next_factory_->MaybeInterceptResponse(request, network_delegate); } } // namespace android_webview
nacl-webkit/chrome_deps
android_webview/browser/net/aw_url_request_job_factory.cc
C++
bsd-3-clause
3,024
package com.tinkerpop.pipes.transform; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.pipes.util.PipeHelper; import java.util.Arrays; /** * BothEdgesPipe emits both the outgoing and incoming edges of a vertex. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class BothEdgesPipe extends VerticesEdgesPipe { public BothEdgesPipe(final String... labels) { super(Direction.BOTH, labels); } public BothEdgesPipe(final int branchFactor, final String... labels) { super(Direction.BOTH, branchFactor, labels); } public String toString() { return (this.branchFactor == Integer.MAX_VALUE) ? PipeHelper.makePipeString(this, Arrays.asList(this.labels)) : PipeHelper.makePipeString(this, this.branchFactor, Arrays.asList(this.labels)); } }
whshev/pipes
src/main/java/com/tinkerpop/pipes/transform/BothEdgesPipe.java
Java
bsd-3-clause
855
module SalesInvoiceSoapResponses def sales_invoice_gettax_response(doc_code, line_item, shipment, time = Time.now) { transaction_id: "4314427373575624", result_code: "Success", doc_id: "56879220", doc_type: "SalesInvoice", doc_code: doc_code, doc_date: time.to_date, doc_status: "Saved", reconciled: false, timestamp: time, total_amount: "110", total_discount: "0", total_exemption: "0", total_taxable: "110", total_tax: "9.77", total_tax_calculated: "9.77", hash_code: "0", tax_lines: { tax_line: [ { no: SpreeAvatax::SalesShared.avatax_id(line_item), tax_code: "P0000000", taxability: true, boundary_level: "Zip5", exemption: "0", discount: "0", taxable: "10", rate: "0.088750", tax: "0.89", tax_calculated: "0.89", tax_included: false, tax_details: { tax_detail: [ { country: "US", region: "NY", juris_type: "State", juris_code: "36", tax_type: "Sales", base: "10", taxable: "10", rate: "0.040000", tax: "0.4", tax_calculated: "0.4", non_taxable: "0", exemption: "0", juris_name: "NEW YORK", tax_name: "NY STATE TAX", tax_authority_type: "45", tax_group: nil, rate_type: "G", state_assigned_no: nil }, { country: "US", region: "NY", juris_type: "City", juris_code: "51000", tax_type: "Sales", base: "10", taxable: "10", rate: "0.045000", tax: "0.45", tax_calculated: "0.45", non_taxable: "0", exemption: "0", juris_name: "NEW YORK CITY", tax_name: "NY CITY TAX", tax_authority_type: "45", tax_group: nil, rate_type: "G", state_assigned_no: "NE 8081" }, { country: "US", region: "NY", juris_type: "Special", juris_code: "359071", tax_type: "Sales", base: "10", taxable: "10", rate: "0.003750", tax: "0.04", tax_calculated: "0.04", non_taxable: "0", exemption: "0", juris_name: "METROPOLITAN COMMUTER TRANSPORTATION DISTRICT", tax_name: "NY SPECIAL TAX", tax_authority_type: "45", tax_group: nil, rate_type: "G", state_assigned_no: "NE 8061" } ] }, exempt_cert_id: "0", tax_date: time.to_date, reporting_date: time.to_date, accounting_method: "Accrual" }, { no: SpreeAvatax::SalesShared.avatax_id(shipment), tax_code: "FR020100", taxability: true, boundary_level: "Zip5", exemption: "0", discount: "0", taxable: "100", rate: "0.088750", tax: "8.88", tax_calculated: "8.88", tax_included: false, tax_details: { tax_detail: [ { country: "US", region: "NY", juris_type: "State", juris_code: "36", tax_type: "Sales", base: "100", taxable: "100", rate: "0.040000", tax: "4", tax_calculated: "4", non_taxable: "0", exemption: "0", juris_name: "NEW YORK", tax_name: "NY STATE TAX", tax_authority_type: "45", tax_group: nil, rate_type: "G", state_assigned_no: nil }, { country: "US", region: "NY", juris_type: "City", juris_code: "51000", tax_type: "Sales", base: "100", taxable: "100", rate: "0.045000", tax: "4.5", tax_calculated: "4.5", non_taxable: "0", exemption: "0", juris_name: "NEW YORK CITY", tax_name: "NY CITY TAX", tax_authority_type: "45", tax_group: nil, rate_type: "G", state_assigned_no: "NE 8081" }, { country: "US", region: "NY", juris_type: "Special", juris_code: "359071", tax_type: "Sales", base: "100", taxable: "100", rate: "0.003750", tax: "0.38", tax_calculated: "0.38", non_taxable: "0", exemption: "0", juris_name: "METROPOLITAN COMMUTER TRANSPORTATION DISTRICT", tax_name: "NY SPECIAL TAX", tax_authority_type: "45", tax_group: nil, rate_type: "G", state_assigned_no: "NE 8061" } ] }, exempt_cert_id: "0", tax_date: time.to_date, reporting_date: time.to_date, accounting_method: "Accrual" } ] }, tax_addresses: { tax_address: { address: "1234 Way", address_code: "1", boundary_level: "2", city: "New York", country: "US", postal_code: "10010", region: "NY", tax_region_id: "2088629", juris_code: "3600051000", latitude: nil, longitude: nil, geocode_type: "ZIP5Centroid", validate_status: "HouseNotOnStreet", distance_to_boundary: "0" } }, locked: false, adjustment_reason: "0", adjustment_description: nil, version: "1", tax_date: time.to_date, tax_summary: nil, volatile_tax_rates: false, messages: [ { summary: nil, details: nil, helplink: nil, refersto: nil, severity: nil, source: nil } ] } end def sales_invoice_posttax_response { transaction_id: "4314427475194657", result_code: "Success", doc_id: "56879220", messages:[ { summary: nil, details: nil, helplink: nil, refersto: nil, severity: nil, source: nil, }, ], } end def sales_invoice_canceltax_response { transaction_id: "4321919394664864", result_code: "Success", doc_id: "57305344", messages: [ { summary: nil, details: nil, helplink: nil, refersto: nil, severity: nil, source: nil, }, ], } end end
jordan-brough/solidus_avatax
spec/support/sales_invoice_soap_responses.rb
Ruby
bsd-3-clause
7,800
/* @flow */ /* Flow declarations for express requests and responses */ /* eslint-disable no-unused-vars */ declare class Request { method: String; body: Object; query: Object; } declare class Response { status: (code: Number) => Response; set: (field: String, value: String) => Response; send: (body: String) => void; }
jamiehodge/express-graphql
resources/interfaces/express.js
JavaScript
bsd-3-clause
333
import base64 import logging import string import warnings from datetime import datetime, timedelta from django.conf import settings from django.contrib.sessions.exceptions import SuspiciousSession from django.core import signing from django.core.exceptions import SuspiciousOperation from django.utils import timezone from django.utils.crypto import ( constant_time_compare, get_random_string, salted_hmac, ) from django.utils.deprecation import RemovedInDjango40Warning from django.utils.module_loading import import_string from django.utils.translation import LANGUAGE_SESSION_KEY # session_key should not be case sensitive because some backends can store it # on case insensitive file systems. VALID_KEY_CHARS = string.ascii_lowercase + string.digits class CreateError(Exception): """ Used internally as a consistent exception type to catch from save (see the docstring for SessionBase.save() for details). """ pass class UpdateError(Exception): """ Occurs if Django tries to update a session that was deleted. """ pass class SessionBase: """ Base class for all Session classes. """ TEST_COOKIE_NAME = 'testcookie' TEST_COOKIE_VALUE = 'worked' __not_given = object() def __init__(self, session_key=None): self._session_key = session_key self.accessed = False self.modified = False self.serializer = import_string(settings.SESSION_SERIALIZER) def __contains__(self, key): return key in self._session def __getitem__(self, key): if key == LANGUAGE_SESSION_KEY: warnings.warn( 'The user language will no longer be stored in ' 'request.session in Django 4.0. Read it from ' 'request.COOKIES[settings.LANGUAGE_COOKIE_NAME] instead.', RemovedInDjango40Warning, stacklevel=2, ) return self._session[key] def __setitem__(self, key, value): self._session[key] = value self.modified = True def __delitem__(self, key): del self._session[key] self.modified = True @property def key_salt(self): return 'django.contrib.sessions.' + self.__class__.__qualname__ def get(self, key, default=None): return self._session.get(key, default) def pop(self, key, default=__not_given): self.modified = self.modified or key in self._session args = () if default is self.__not_given else (default,) return self._session.pop(key, *args) def setdefault(self, key, value): if key in self._session: return self._session[key] else: self.modified = True self._session[key] = value return value def set_test_cookie(self): self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE def test_cookie_worked(self): return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE def delete_test_cookie(self): del self[self.TEST_COOKIE_NAME] def _hash(self, value): # RemovedInDjango40Warning: pre-Django 3.1 format will be invalid. key_salt = "django.contrib.sessions" + self.__class__.__name__ return salted_hmac(key_salt, value).hexdigest() def encode(self, session_dict): "Return the given session dictionary serialized and encoded as a string." # RemovedInDjango40Warning: DEFAULT_HASHING_ALGORITHM will be removed. if settings.DEFAULT_HASHING_ALGORITHM == 'sha1': return self._legacy_encode(session_dict) return signing.dumps( session_dict, salt=self.key_salt, serializer=self.serializer, compress=True, ) def decode(self, session_data): try: return signing.loads(session_data, salt=self.key_salt, serializer=self.serializer) # RemovedInDjango40Warning: when the deprecation ends, handle here # exceptions similar to what _legacy_decode() does now. except signing.BadSignature: try: # Return an empty session if data is not in the pre-Django 3.1 # format. return self._legacy_decode(session_data) except Exception: logger = logging.getLogger('django.security.SuspiciousSession') logger.warning('Session data corrupted') return {} except Exception: return self._legacy_decode(session_data) def _legacy_encode(self, session_dict): # RemovedInDjango40Warning. serialized = self.serializer().dumps(session_dict) hash = self._hash(serialized) return base64.b64encode(hash.encode() + b':' + serialized).decode('ascii') def _legacy_decode(self, session_data): # RemovedInDjango40Warning: pre-Django 3.1 format will be invalid. encoded_data = base64.b64decode(session_data.encode('ascii')) try: # could produce ValueError if there is no ':' hash, serialized = encoded_data.split(b':', 1) expected_hash = self._hash(serialized) if not constant_time_compare(hash.decode(), expected_hash): raise SuspiciousSession("Session data corrupted") else: return self.serializer().loads(serialized) except Exception as e: # ValueError, SuspiciousOperation, unpickling exceptions. If any of # these happen, just return an empty dictionary (an empty session). if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(str(e)) return {} def update(self, dict_): self._session.update(dict_) self.modified = True def has_key(self, key): return key in self._session def keys(self): return self._session.keys() def values(self): return self._session.values() def items(self): return self._session.items() def clear(self): # To avoid unnecessary persistent storage accesses, we set up the # internals directly (loading data wastes time, since we are going to # set it to an empty dict anyway). self._session_cache = {} self.accessed = True self.modified = True def is_empty(self): "Return True when there is no session_key and the session is empty." try: return not self._session_key and not self._session_cache except AttributeError: return True def _get_new_session_key(self): "Return session key that isn't being used." while True: session_key = get_random_string(32, VALID_KEY_CHARS) if not self.exists(session_key): return session_key def _get_or_create_session_key(self): if self._session_key is None: self._session_key = self._get_new_session_key() return self._session_key def _validate_session_key(self, key): """ Key must be truthy and at least 8 characters long. 8 characters is an arbitrary lower bound for some minimal key security. """ return key and len(key) >= 8 def _get_session_key(self): return self.__session_key def _set_session_key(self, value): """ Validate session key on assignment. Invalid values will set to None. """ if self._validate_session_key(value): self.__session_key = value else: self.__session_key = None session_key = property(_get_session_key) _session_key = property(_get_session_key, _set_session_key) def _get_session(self, no_load=False): """ Lazily load session from storage (unless "no_load" is True, when only an empty dict is stored) and store it in the current instance. """ self.accessed = True try: return self._session_cache except AttributeError: if self.session_key is None or no_load: self._session_cache = {} else: self._session_cache = self.load() return self._session_cache _session = property(_get_session) def get_session_cookie_age(self): return settings.SESSION_COOKIE_AGE def get_expiry_age(self, **kwargs): """Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session. """ try: modification = kwargs['modification'] except KeyError: modification = timezone.now() # Make the difference between "expiry=None passed in kwargs" and # "expiry not passed in kwargs", in order to guarantee not to trigger # self.load() when expiry is provided. try: expiry = kwargs['expiry'] except KeyError: expiry = self.get('_session_expiry') if not expiry: # Checks both None and 0 cases return self.get_session_cookie_age() if not isinstance(expiry, datetime): return expiry delta = expiry - modification return delta.days * 86400 + delta.seconds def get_expiry_date(self, **kwargs): """Get session the expiry date (as a datetime object). Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session. """ try: modification = kwargs['modification'] except KeyError: modification = timezone.now() # Same comment as in get_expiry_age try: expiry = kwargs['expiry'] except KeyError: expiry = self.get('_session_expiry') if isinstance(expiry, datetime): return expiry expiry = expiry or self.get_session_cookie_age() return modification + timedelta(seconds=expiry) def set_expiry(self, value): """ Set a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the session will expire on browser close. If ``value`` is a ``datetime`` or ``timedelta`` object, the session will expire at that specific future time. If ``value`` is ``None``, the session uses the global session expiry policy. """ if value is None: # Remove any custom expiration for this session. try: del self['_session_expiry'] except KeyError: pass return if isinstance(value, timedelta): value = timezone.now() + value self['_session_expiry'] = value def get_expire_at_browser_close(self): """ Return ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one. """ if self.get('_session_expiry') is None: return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE return self.get('_session_expiry') == 0 def flush(self): """ Remove the current session data from the database and regenerate the key. """ self.clear() self.delete() self._session_key = None def cycle_key(self): """ Create a new session key, while retaining the current session data. """ data = self._session key = self.session_key self.create() self._session_cache = data if key: self.delete(key) # Methods that child classes must implement. def exists(self, session_key): """ Return True if the given session_key already exists. """ raise NotImplementedError('subclasses of SessionBase must provide an exists() method') def create(self): """ Create a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns. """ raise NotImplementedError('subclasses of SessionBase must provide a create() method') def save(self, must_create=False): """ Save the session data. If 'must_create' is True, create a new session object (or raise CreateError). Otherwise, only update an existing object and don't create one (raise UpdateError if needed). """ raise NotImplementedError('subclasses of SessionBase must provide a save() method') def delete(self, session_key=None): """ Delete the session data under this key. If the key is None, use the current session key value. """ raise NotImplementedError('subclasses of SessionBase must provide a delete() method') def load(self): """ Load the session data and return a dictionary. """ raise NotImplementedError('subclasses of SessionBase must provide a load() method') @classmethod def clear_expired(cls): """ Remove expired sessions from the session store. If this operation isn't possible on a given backend, it should raise NotImplementedError. If it isn't necessary, because the backend has a built-in expiration mechanism, it should be a no-op. """ raise NotImplementedError('This backend does not support clear_expired().')
wkschwartz/django
django/contrib/sessions/backends/base.py
Python
bsd-3-clause
13,900
# -*- coding: utf-8 -*- import os CODE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) def get_permdir(): return os.path.join(CODE_DIR, 'permdir') def get_repo_root(): return get_permdir() def get_tmpdir(): return os.path.join(CODE_DIR, 'tmpdir') def init_permdir(): path = get_permdir() if not os.path.exists(path): os.makedirs(path) init_permdir()
douban/code
vilya/libs/permdir.py
Python
bsd-3-clause
407
from social_core.backends.upwork import UpworkOAuth
cjltsod/python-social-auth
social/backends/upwork.py
Python
bsd-3-clause
52
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/web_resource/eula_accepted_notifier.h" #include "base/macros.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h" #include "components/web_resource/web_resource_pref_names.h" #include "testing/gtest/include/gtest/gtest.h" namespace web_resource { class EulaAcceptedNotifierTest : public testing::Test, public EulaAcceptedNotifier::Observer { public: EulaAcceptedNotifierTest() : eula_accepted_called_(false) { } // testing::Test overrides. void SetUp() override { local_state_.registry()->RegisterBooleanPref(prefs::kEulaAccepted, false); notifier_.reset(new EulaAcceptedNotifier(&local_state_)); notifier_->Init(this); } // EulaAcceptedNotifier::Observer overrides. void OnEulaAccepted() override { EXPECT_FALSE(eula_accepted_called_); eula_accepted_called_ = true; } void SetEulaAcceptedPref() { local_state_.SetBoolean(prefs::kEulaAccepted, true); } EulaAcceptedNotifier* notifier() { return notifier_.get(); } bool eula_accepted_called() { return eula_accepted_called_; } private: TestingPrefServiceSimple local_state_; scoped_ptr<EulaAcceptedNotifier> notifier_; bool eula_accepted_called_; DISALLOW_COPY_AND_ASSIGN(EulaAcceptedNotifierTest); }; TEST_F(EulaAcceptedNotifierTest, EulaAlreadyAccepted) { SetEulaAcceptedPref(); EXPECT_TRUE(notifier()->IsEulaAccepted()); EXPECT_FALSE(eula_accepted_called()); // Call it a second time, to ensure the answer doesn't change. EXPECT_TRUE(notifier()->IsEulaAccepted()); EXPECT_FALSE(eula_accepted_called()); } TEST_F(EulaAcceptedNotifierTest, EulaNotAccepted) { EXPECT_FALSE(notifier()->IsEulaAccepted()); EXPECT_FALSE(eula_accepted_called()); // Call it a second time, to ensure the answer doesn't change. EXPECT_FALSE(notifier()->IsEulaAccepted()); EXPECT_FALSE(eula_accepted_called()); } TEST_F(EulaAcceptedNotifierTest, EulaNotInitiallyAccepted) { EXPECT_FALSE(notifier()->IsEulaAccepted()); SetEulaAcceptedPref(); EXPECT_TRUE(notifier()->IsEulaAccepted()); EXPECT_TRUE(eula_accepted_called()); // Call it a second time, to ensure the answer doesn't change. EXPECT_TRUE(notifier()->IsEulaAccepted()); } } // namespace web_resource
ds-hwang/chromium-crosswalk
components/web_resource/eula_accepted_notifier_unittest.cc
C++
bsd-3-clause
2,473
""" This module collects helper functions and classes that "span" multiple levels of MVC. In other words, these functions/classes introduce controlled coupling for convenience's sake. """ import warnings from django.template import loader, RequestContext from django.template.context import _current_app_undefined from django.template.engine import ( _context_instance_undefined, _dictionary_undefined, _dirs_undefined) from django.http import HttpResponse, Http404 from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.db.models.base import ModelBase from django.db.models.manager import Manager from django.db.models.query import QuerySet from django.core import urlresolvers from django.utils import six from django.utils.deprecation import RemovedInDjango20Warning from django.utils.encoding import force_text from django.utils.functional import Promise def render_to_response(template_name, context=None, context_instance=_context_instance_undefined, content_type=None, status=None, dirs=_dirs_undefined, dictionary=_dictionary_undefined): """ Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ if (context_instance is _context_instance_undefined and dirs is _dirs_undefined and dictionary is _dictionary_undefined): # No deprecated arguments were passed - use the new code path content = loader.render_to_string(template_name, context) else: # Some deprecated arguments were passed - use the legacy code path content = loader.render_to_string( template_name, context, context_instance, dirs, dictionary) return HttpResponse(content, content_type, status) def render(request, template_name, context=None, context_instance=_context_instance_undefined, content_type=None, status=None, current_app=_current_app_undefined, dirs=_dirs_undefined, dictionary=_dictionary_undefined): """ Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. Uses a RequestContext by default. """ if (context_instance is _context_instance_undefined and current_app is _current_app_undefined and dirs is _dirs_undefined and dictionary is _dictionary_undefined): # No deprecated arguments were passed - use the new code path # In Django 2.0, request should become a positional argument. content = loader.render_to_string(template_name, context, request=request) else: # Some deprecated arguments were passed - use the legacy code path if context_instance is not _context_instance_undefined: if current_app is not _current_app_undefined: raise ValueError('If you provide a context_instance you must ' 'set its current_app before calling render()') else: context_instance = RequestContext(request) if current_app is not _current_app_undefined: warnings.warn( "The current_app argument of render is deprecated. " "Set the current_app attribute of request instead.", RemovedInDjango20Warning, stacklevel=2) request.current_app = current_app # Directly set the private attribute to avoid triggering the # warning in RequestContext.__init__. context_instance._current_app = current_app content = loader.render_to_string( template_name, context, context_instance, dirs, dictionary) return HttpResponse(content, content_type, status) def redirect(to, *args, **kwargs): """ Returns an HttpResponseRedirect to the appropriate URL for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urlresolvers.reverse()` will be used to reverse-resolve the name. * A URL, which will be used as-is for the redirect location. By default issues a temporary redirect; pass permanent=True to issue a permanent redirect """ if kwargs.pop('permanent', False): redirect_class = HttpResponsePermanentRedirect else: redirect_class = HttpResponseRedirect return redirect_class(resolve_url(to, *args, **kwargs)) def _get_queryset(klass): """ Returns a QuerySet from a Model, Manager, or QuerySet. Created to make get_object_or_404 and get_list_or_404 more DRY. Raises a ValueError if klass is not a Model, Manager, or QuerySet. """ if isinstance(klass, QuerySet): return klass elif isinstance(klass, Manager): manager = klass elif isinstance(klass, ModelBase): manager = klass._default_manager else: if isinstance(klass, type): klass__name = klass.__name__ else: klass__name = klass.__class__.__name__ raise ValueError("Object is of type '%s', but must be a Django Model, " "Manager, or QuerySet" % klass__name) return manager.all() def get_object_or_404(klass, *args, **kwargs): """ Uses get() to return an object, or raises a Http404 exception if the object does not exist. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query. Note: Like with get(), an MultipleObjectsReturned will be raised if more than one object is found. """ queryset = _get_queryset(klass) try: return queryset.get(*args, **kwargs) except queryset.model.DoesNotExist: raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) def get_list_or_404(klass, *args, **kwargs): """ Uses filter() to return a list of objects, or raise a Http404 exception if the list is empty. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the filter() query. """ queryset = _get_queryset(klass) obj_list = list(queryset.filter(*args, **kwargs)) if not obj_list: raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) return obj_list def resolve_url(to, *args, **kwargs): """ Return a URL appropriate for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urlresolvers.reverse()` will be used to reverse-resolve the name. * A URL, which will be returned as-is. """ # If it's a model, use get_absolute_url() if hasattr(to, 'get_absolute_url'): return to.get_absolute_url() if isinstance(to, Promise): # Expand the lazy instance, as it can cause issues when it is passed # further to some Python functions like urlparse. to = force_text(to) if isinstance(to, six.string_types): # Handle relative URLs if any(to.startswith(path) for path in ('./', '../')): return to # Next try a reverse URL resolution. try: return urlresolvers.reverse(to, args=args, kwargs=kwargs) except urlresolvers.NoReverseMatch: # If this is a callable, re-raise. if callable(to): raise # If this doesn't "feel" like a URL, re-raise. if '/' not in to and '.' not in to: raise # Finally, fall back and assume it's a URL return to
doismellburning/django
django/shortcuts.py
Python
bsd-3-clause
7,865
from settings import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'denorm', 'HOST': 'localhost', 'USER': 'denorm', 'PASSWORD': 'denorm1', } }
mjtamlyn/django-denorm
test_project/settings_mysql.py
Python
bsd-3-clause
221
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/geolocation/geolocation_permission_context.h" #include <set> #include <string> #include <utility> #include "base/bind.h" #include "base/command_line.h" #include "base/containers/hash_tables.h" #include "base/id_map.h" #include "base/memory/scoped_vector.h" #include "base/synchronization/waitable_event.h" #include "base/test/simple_test_clock.h" #include "base/time/clock.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/content_settings/tab_specific_content_settings.h" #include "chrome/browser/geolocation/geolocation_permission_context_factory.h" #include "chrome/browser/infobars/infobar_service.h" #include "chrome/browser/ui/website_settings/mock_permission_bubble_view.h" #include "chrome/browser/ui/website_settings/permission_bubble_manager.h" #include "chrome/browser/ui/website_settings/permission_bubble_request.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/permission_request_id.h" #include "components/infobars/core/confirm_infobar_delegate.h" #include "components/infobars/core/infobar.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "content/public/test/mock_render_process_host.h" #include "content/public/test/test_renderer_host.h" #include "content/public/test/test_utils.h" #include "content/public/test/web_contents_tester.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_ANDROID) #include "base/prefs/pref_service.h" #include "chrome/browser/android/mock_location_settings.h" #include "chrome/browser/geolocation/geolocation_permission_context_android.h" #endif #if defined(ENABLE_EXTENSIONS) #include "extensions/browser/view_type_utils.h" #endif using content::MockRenderProcessHost; // ClosedInfoBarTracker ------------------------------------------------------- // We need to track which infobars were closed. class ClosedInfoBarTracker : public content::NotificationObserver { public: ClosedInfoBarTracker(); ~ClosedInfoBarTracker() override; // content::NotificationObserver: void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) override; size_t size() const { return removed_infobars_.size(); } bool Contains(infobars::InfoBar* infobar) const; void Clear(); private: FRIEND_TEST_ALL_PREFIXES(GeolocationPermissionContextTests, TabDestroyed); content::NotificationRegistrar registrar_; std::set<infobars::InfoBar*> removed_infobars_; }; ClosedInfoBarTracker::ClosedInfoBarTracker() { registrar_.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED, content::NotificationService::AllSources()); } ClosedInfoBarTracker::~ClosedInfoBarTracker() { } void ClosedInfoBarTracker::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK(type == chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED); removed_infobars_.insert( content::Details<infobars::InfoBar::RemovedDetails>(details)->first); } bool ClosedInfoBarTracker::Contains(infobars::InfoBar* infobar) const { return removed_infobars_.count(infobar) != 0; } void ClosedInfoBarTracker::Clear() { removed_infobars_.clear(); } // GeolocationPermissionContextTests ------------------------------------------ class GeolocationPermissionContextTests : public ChromeRenderViewHostTestHarness { protected: // ChromeRenderViewHostTestHarness: void SetUp() override; void TearDown() override; PermissionRequestID RequestID(int bridge_id); PermissionRequestID RequestIDForTab(int tab, int bridge_id); InfoBarService* infobar_service() { return InfoBarService::FromWebContents(web_contents()); } InfoBarService* infobar_service_for_tab(int tab) { return InfoBarService::FromWebContents(extra_tabs_[tab]); } void RequestGeolocationPermission(content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_frame, bool user_gesture); void PermissionResponse(const PermissionRequestID& id, ContentSetting content_setting); void CheckPermissionMessageSent(int bridge_id, bool allowed); void CheckPermissionMessageSentForTab(int tab, int bridge_id, bool allowed); void CheckPermissionMessageSentInternal(MockRenderProcessHost* process, int bridge_id, bool allowed); void AddNewTab(const GURL& url); void CheckTabContentsState(const GURL& requesting_frame, ContentSetting expected_content_setting); size_t GetBubblesQueueSize(PermissionBubbleManager* manager); void AcceptBubble(PermissionBubbleManager* manager); void DenyBubble(PermissionBubbleManager* manager); void CloseBubble(PermissionBubbleManager* manager); void BubbleManagerDocumentLoadCompleted(); void BubbleManagerDocumentLoadCompleted(content::WebContents* web_contents); ContentSetting GetGeolocationContentSetting(GURL frame_0, GURL frame_1); // owned by the browser context GeolocationPermissionContext* geolocation_permission_context_; ClosedInfoBarTracker closed_infobar_tracker_; MockPermissionBubbleView bubble_view_; ScopedVector<content::WebContents> extra_tabs_; // A map between renderer child id and a pair represending the bridge id and // whether the requested permission was allowed. base::hash_map<int, std::pair<int, bool> > responses_; }; PermissionRequestID GeolocationPermissionContextTests::RequestID( int bridge_id) { return PermissionRequestID( web_contents()->GetRenderProcessHost()->GetID(), web_contents()->GetRenderViewHost()->GetRoutingID(), bridge_id, GURL()); } PermissionRequestID GeolocationPermissionContextTests::RequestIDForTab( int tab, int bridge_id) { return PermissionRequestID( extra_tabs_[tab]->GetRenderProcessHost()->GetID(), extra_tabs_[tab]->GetRenderViewHost()->GetRoutingID(), bridge_id, GURL()); } void GeolocationPermissionContextTests::RequestGeolocationPermission( content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_frame, bool user_gesture) { geolocation_permission_context_->RequestPermission( web_contents, id, requesting_frame, user_gesture, base::Bind(&GeolocationPermissionContextTests::PermissionResponse, base::Unretained(this), id)); content::RunAllBlockingPoolTasksUntilIdle(); } void GeolocationPermissionContextTests::PermissionResponse( const PermissionRequestID& id, ContentSetting content_setting) { responses_[id.render_process_id()] = std::make_pair(id.bridge_id(), content_setting == CONTENT_SETTING_ALLOW); } void GeolocationPermissionContextTests::CheckPermissionMessageSent( int bridge_id, bool allowed) { CheckPermissionMessageSentInternal(process(), bridge_id, allowed); } void GeolocationPermissionContextTests::CheckPermissionMessageSentForTab( int tab, int bridge_id, bool allowed) { CheckPermissionMessageSentInternal(static_cast<MockRenderProcessHost*>( extra_tabs_[tab]->GetRenderProcessHost()), bridge_id, allowed); } void GeolocationPermissionContextTests::CheckPermissionMessageSentInternal( MockRenderProcessHost* process, int bridge_id, bool allowed) { ASSERT_EQ(responses_.count(process->GetID()), 1U); EXPECT_EQ(bridge_id, responses_[process->GetID()].first); EXPECT_EQ(allowed, responses_[process->GetID()].second); responses_.erase(process->GetID()); } void GeolocationPermissionContextTests::AddNewTab(const GURL& url) { content::WebContents* new_tab = CreateTestWebContents(); new_tab->GetController().LoadURL( url, content::Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); content::RenderFrameHostTester::For(new_tab->GetMainFrame()) ->SendNavigate(extra_tabs_.size() + 1, url); // Set up required helpers, and make this be as "tabby" as the code requires. #if defined(ENABLE_EXTENSIONS) extensions::SetViewType(new_tab, extensions::VIEW_TYPE_TAB_CONTENTS); #endif InfoBarService::CreateForWebContents(new_tab); PermissionBubbleManager::CreateForWebContents(new_tab); PermissionBubbleManager::FromWebContents(new_tab)->SetView(&bubble_view_); extra_tabs_.push_back(new_tab); } void GeolocationPermissionContextTests::CheckTabContentsState( const GURL& requesting_frame, ContentSetting expected_content_setting) { TabSpecificContentSettings* content_settings = TabSpecificContentSettings::FromWebContents(web_contents()); const ContentSettingsUsagesState::StateMap& state_map = content_settings->geolocation_usages_state().state_map(); EXPECT_EQ(1U, state_map.count(requesting_frame.GetOrigin())); EXPECT_EQ(0U, state_map.count(requesting_frame)); ContentSettingsUsagesState::StateMap::const_iterator settings = state_map.find(requesting_frame.GetOrigin()); ASSERT_FALSE(settings == state_map.end()) << "geolocation state not found " << requesting_frame; EXPECT_EQ(expected_content_setting, settings->second); } void GeolocationPermissionContextTests::SetUp() { ChromeRenderViewHostTestHarness::SetUp(); // Set up required helpers, and make this be as "tabby" as the code requires. #if defined(ENABLE_EXTENSIONS) extensions::SetViewType(web_contents(), extensions::VIEW_TYPE_TAB_CONTENTS); #endif InfoBarService::CreateForWebContents(web_contents()); TabSpecificContentSettings::CreateForWebContents(web_contents()); geolocation_permission_context_ = GeolocationPermissionContextFactory::GetForProfile(profile()); #if defined(OS_ANDROID) static_cast<GeolocationPermissionContextAndroid*>( geolocation_permission_context_) ->SetLocationSettingsForTesting( scoped_ptr<LocationSettings>(new MockLocationSettings())); MockLocationSettings::SetLocationStatus(true, true); #endif PermissionBubbleManager::CreateForWebContents(web_contents()); PermissionBubbleManager::FromWebContents(web_contents())->SetView( &bubble_view_); } void GeolocationPermissionContextTests::TearDown() { extra_tabs_.clear(); ChromeRenderViewHostTestHarness::TearDown(); } size_t GeolocationPermissionContextTests::GetBubblesQueueSize( PermissionBubbleManager* manager) { return manager->requests_.size(); } void GeolocationPermissionContextTests::AcceptBubble( PermissionBubbleManager* manager) { manager->Accept(); } void GeolocationPermissionContextTests::DenyBubble( PermissionBubbleManager* manager) { manager->Deny(); } void GeolocationPermissionContextTests::CloseBubble( PermissionBubbleManager* manager) { manager->Closing(); } void GeolocationPermissionContextTests::BubbleManagerDocumentLoadCompleted() { GeolocationPermissionContextTests::BubbleManagerDocumentLoadCompleted( web_contents()); } void GeolocationPermissionContextTests::BubbleManagerDocumentLoadCompleted( content::WebContents* web_contents) { PermissionBubbleManager::FromWebContents(web_contents)-> DocumentOnLoadCompletedInMainFrame(); } ContentSetting GeolocationPermissionContextTests::GetGeolocationContentSetting( GURL frame_0, GURL frame_1) { return profile()->GetHostContentSettingsMap()->GetContentSetting( frame_0, frame_1, CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string()); } // Needed to parameterize the tests for both infobars & permission bubbles. class GeolocationPermissionContextParamTests : public GeolocationPermissionContextTests, public ::testing::WithParamInterface<bool> { protected: GeolocationPermissionContextParamTests() {} ~GeolocationPermissionContextParamTests() override {} bool BubbleEnabled() const { #if defined (OS_ANDROID) return false; #else return GetParam(); #endif } void SetUp() override { GeolocationPermissionContextTests::SetUp(); #if !defined(OS_ANDROID) if (BubbleEnabled()) { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnablePermissionsBubbles); EXPECT_TRUE(PermissionBubbleManager::Enabled()); } else { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kDisablePermissionsBubbles); EXPECT_FALSE(PermissionBubbleManager::Enabled()); } #endif } size_t GetNumberOfPrompts() { if (BubbleEnabled()) { PermissionBubbleManager* manager = PermissionBubbleManager::FromWebContents(web_contents()); return GetBubblesQueueSize(manager); } else { return infobar_service()->infobar_count(); } } void AcceptPrompt() { if (BubbleEnabled()) { PermissionBubbleManager* manager = PermissionBubbleManager::FromWebContents(web_contents()); AcceptBubble(manager); } else { infobars::InfoBar* infobar = infobar_service()->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate = infobar->delegate()->AsConfirmInfoBarDelegate(); infobar_delegate->Accept(); } } base::string16 GetPromptText() { if (BubbleEnabled()) { PermissionBubbleManager* manager = PermissionBubbleManager::FromWebContents(web_contents()); return manager->requests_.front()->GetMessageText(); } infobars::InfoBar* infobar = infobar_service()->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate = infobar->delegate()->AsConfirmInfoBarDelegate(); return infobar_delegate->GetMessageText(); } private: DISALLOW_COPY_AND_ASSIGN(GeolocationPermissionContextParamTests); }; // Tests ---------------------------------------------------------------------- TEST_P(GeolocationPermissionContextParamTests, SinglePermissionInfobar) { if (BubbleEnabled()) return; GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); EXPECT_EQ(0U, infobar_service()->infobar_count()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); ASSERT_EQ(1U, infobar_service()->infobar_count()); infobars::InfoBar* infobar = infobar_service()->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate = infobar->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate); infobar_delegate->Cancel(); infobar_service()->RemoveInfoBar(infobar); EXPECT_EQ(1U, closed_infobar_tracker_.size()); EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar)); } TEST_P(GeolocationPermissionContextParamTests, SinglePermissionBubble) { if (!BubbleEnabled()) return; GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); BubbleManagerDocumentLoadCompleted(); EXPECT_EQ(0U, GetNumberOfPrompts()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); ASSERT_EQ(1U, GetNumberOfPrompts()); } #if defined(OS_ANDROID) // Infobar-only tests; Android doesn't support permission bubbles. TEST_F(GeolocationPermissionContextTests, GeolocationEnabledDisabled) { GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); MockLocationSettings::SetLocationStatus(true, true); EXPECT_EQ(0U, infobar_service()->infobar_count()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(1U, infobar_service()->infobar_count()); ConfirmInfoBarDelegate* infobar_delegate_0 = infobar_service()->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate_0); base::string16 text_0 = infobar_delegate_0->GetButtonLabel( ConfirmInfoBarDelegate::BUTTON_OK); Reload(); MockLocationSettings::SetLocationStatus(true, false); EXPECT_EQ(0U, infobar_service()->infobar_count()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(0U, infobar_service()->infobar_count()); } TEST_F(GeolocationPermissionContextTests, MasterEnabledGoogleAppsEnabled) { GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); MockLocationSettings::SetLocationStatus(true, true); EXPECT_EQ(0U, infobar_service()->infobar_count()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(1U, infobar_service()->infobar_count()); ConfirmInfoBarDelegate* infobar_delegate = infobar_service()->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate); infobar_delegate->Accept(); CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); } TEST_F(GeolocationPermissionContextTests, MasterEnabledGoogleAppsDisabled) { GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); MockLocationSettings::SetLocationStatus(true, false); EXPECT_EQ(0U, infobar_service()->infobar_count()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(0U, infobar_service()->infobar_count()); } #endif TEST_P(GeolocationPermissionContextParamTests, QueuedPermission) { GURL requesting_frame_0("http://www.example.com/geolocation"); GURL requesting_frame_1("http://www.example-2.com/geolocation"); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_0, requesting_frame_1)); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_1, requesting_frame_1)); NavigateAndCommit(requesting_frame_0); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Check that no permission requests have happened yet. EXPECT_EQ(0U, GetNumberOfPrompts()); // Request permission for two frames. RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame_0, true); RequestGeolocationPermission( web_contents(), RequestID(1), requesting_frame_1, true); // Ensure only one infobar is created. ASSERT_EQ(1U, GetNumberOfPrompts()); base::string16 text_0 = GetPromptText(); // Accept the first frame. AcceptPrompt(); CheckTabContentsState(requesting_frame_0, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); if (!BubbleEnabled()) { infobars::InfoBar* infobar_0 = infobar_service()->infobar_at(0); infobar_service()->RemoveInfoBar(infobar_0); EXPECT_EQ(1U, closed_infobar_tracker_.size()); EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar_0)); closed_infobar_tracker_.Clear(); } // Now we should have a new infobar for the second frame. ASSERT_EQ(1U, GetNumberOfPrompts()); base::string16 text_1 = GetPromptText(); // Check that the messages differ. EXPECT_NE(text_0, text_1); // Cancel (block) this frame. if (BubbleEnabled()) { PermissionBubbleManager* manager = PermissionBubbleManager::FromWebContents(web_contents()); DenyBubble(manager); } else { infobars::InfoBar* infobar_1 = infobar_service()->infobar_at(0); infobar_1->delegate()->AsConfirmInfoBarDelegate()->Cancel(); } CheckTabContentsState(requesting_frame_1, CONTENT_SETTING_BLOCK); CheckPermissionMessageSent(1, false); // Ensure the persisted permissions are ok. EXPECT_EQ( CONTENT_SETTING_ALLOW, GetGeolocationContentSetting(requesting_frame_0, requesting_frame_0)); EXPECT_EQ( CONTENT_SETTING_BLOCK, GetGeolocationContentSetting(requesting_frame_1, requesting_frame_0)); } TEST_P(GeolocationPermissionContextParamTests, HashIsIgnored) { GURL url_a("http://www.example.com/geolocation#a"); GURL url_b("http://www.example.com/geolocation#b"); // Navigate to the first url. NavigateAndCommit(url_a); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Check permission is requested. ASSERT_EQ(0U, GetNumberOfPrompts()); RequestGeolocationPermission( web_contents(), RequestID(0), url_a, BubbleEnabled()); ASSERT_EQ(1U, GetNumberOfPrompts()); // Change the hash, we'll still be on the same page. NavigateAndCommit(url_b); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Accept. AcceptPrompt(); CheckTabContentsState(url_a, CONTENT_SETTING_ALLOW); CheckTabContentsState(url_b, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); // Cleanup. if (!BubbleEnabled()) { infobars::InfoBar* infobar = infobar_service()->infobar_at(0); infobar_service()->RemoveInfoBar(infobar); EXPECT_EQ(1U, closed_infobar_tracker_.size()); EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar)); } } TEST_P(GeolocationPermissionContextParamTests, PermissionForFileScheme) { // TODO(felt): The bubble is rejecting file:// permission requests. // Fix and enable this test. crbug.com/444047 if (BubbleEnabled()) return; GURL requesting_frame("file://example/geolocation.html"); NavigateAndCommit(requesting_frame); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Check permission is requested. ASSERT_EQ(0U, GetNumberOfPrompts()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(1U, GetNumberOfPrompts()); // Accept the frame. AcceptPrompt(); CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); // Make sure the setting is not stored. EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame, requesting_frame)); } TEST_P(GeolocationPermissionContextParamTests, CancelGeolocationPermissionRequest) { GURL frame_0("http://www.example.com/geolocation"); GURL frame_1("http://www.example-2.com/geolocation"); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(frame_0, frame_0)); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(frame_1, frame_0)); NavigateAndCommit(frame_0); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); ASSERT_EQ(0U, GetNumberOfPrompts()); // Request permission for two frames. RequestGeolocationPermission( web_contents(), RequestID(0), frame_0, true); RequestGeolocationPermission( web_contents(), RequestID(1), frame_1, true); // Get the first permission request text. ASSERT_EQ(1U, GetNumberOfPrompts()); base::string16 text_0 = GetPromptText(); ASSERT_FALSE(text_0.empty()); // Simulate the frame going away; the request should be removed. if (BubbleEnabled()) { PermissionBubbleManager* manager = PermissionBubbleManager::FromWebContents(web_contents()); CloseBubble(manager); } else { geolocation_permission_context_->CancelPermissionRequest(web_contents(), RequestID(0)); } // Check that the next pending request is created correctly. base::string16 text_1 = GetPromptText(); EXPECT_NE(text_0, text_1); // Allow this frame and check that it worked. AcceptPrompt(); CheckTabContentsState(frame_1, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(1, true); // Ensure the persisted permissions are ok. EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(frame_0, frame_0)); EXPECT_EQ( CONTENT_SETTING_ALLOW, GetGeolocationContentSetting(frame_1, frame_0)); } TEST_P(GeolocationPermissionContextParamTests, InvalidURL) { // Navigate to the first url. GURL invalid_embedder("about:blank"); GURL requesting_frame; NavigateAndCommit(invalid_embedder); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Nothing should be displayed. EXPECT_EQ(0U, GetNumberOfPrompts()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(0U, GetNumberOfPrompts()); CheckPermissionMessageSent(0, false); } TEST_P(GeolocationPermissionContextParamTests, SameOriginMultipleTabs) { GURL url_a("http://www.example.com/geolocation"); GURL url_b("http://www.example-2.com/geolocation"); NavigateAndCommit(url_a); // Tab A0 AddNewTab(url_b); // Tab B (extra_tabs_[0]) AddNewTab(url_a); // Tab A1 (extra_tabs_[1]) if (BubbleEnabled()) { BubbleManagerDocumentLoadCompleted(); BubbleManagerDocumentLoadCompleted(extra_tabs_[0]); BubbleManagerDocumentLoadCompleted(extra_tabs_[1]); } PermissionBubbleManager* manager_a0 = PermissionBubbleManager::FromWebContents(web_contents()); PermissionBubbleManager* manager_b = PermissionBubbleManager::FromWebContents(extra_tabs_[0]); PermissionBubbleManager* manager_a1 = PermissionBubbleManager::FromWebContents(extra_tabs_[1]); // Request permission in all three tabs. RequestGeolocationPermission( web_contents(), RequestID(0), url_a, true); RequestGeolocationPermission( extra_tabs_[0], RequestIDForTab(0, 0), url_b, true); RequestGeolocationPermission( extra_tabs_[1], RequestIDForTab(1, 0), url_a, true); ASSERT_EQ(1U, GetNumberOfPrompts()); // For A0. if (BubbleEnabled()) { ASSERT_EQ(1U, GetBubblesQueueSize(manager_b)); ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1)); } else { ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count()); ASSERT_EQ(1U, infobar_service_for_tab(1)->infobar_count()); } // Accept the permission in tab A0. if (BubbleEnabled()) { AcceptBubble(manager_a0); } else { infobars::InfoBar* infobar_a0 = infobar_service()->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate_a0 = infobar_a0->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate_a0); infobar_delegate_a0->Accept(); infobar_service()->RemoveInfoBar(infobar_a0); EXPECT_EQ(2U, closed_infobar_tracker_.size()); EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar_a0)); } CheckPermissionMessageSent(0, true); // Because they're the same origin, this will cause tab A1's infobar to // disappear. It does not cause the bubble to disappear: crbug.com/443013. // TODO(felt): Update this test when the bubble's behavior is changed. if (BubbleEnabled()) ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1)); else CheckPermissionMessageSentForTab(1, 0, true); // Either way, tab B should still have a pending permission request. if (BubbleEnabled()) ASSERT_EQ(1U, GetBubblesQueueSize(manager_b)); else ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count()); } TEST_P(GeolocationPermissionContextParamTests, QueuedOriginMultipleTabs) { GURL url_a("http://www.example.com/geolocation"); GURL url_b("http://www.example-2.com/geolocation"); NavigateAndCommit(url_a); // Tab A0. AddNewTab(url_a); // Tab A1. if (BubbleEnabled()) { BubbleManagerDocumentLoadCompleted(); BubbleManagerDocumentLoadCompleted(extra_tabs_[0]); } PermissionBubbleManager* manager_a0 = PermissionBubbleManager::FromWebContents(web_contents()); PermissionBubbleManager* manager_a1 = PermissionBubbleManager::FromWebContents(extra_tabs_[0]); // Request permission in both tabs; the extra tab will have two permission // requests from two origins. RequestGeolocationPermission( web_contents(), RequestID(0), url_a, true); RequestGeolocationPermission( extra_tabs_[0], RequestIDForTab(0, 0), url_a, true); RequestGeolocationPermission( extra_tabs_[0], RequestIDForTab(0, 1), url_b, true); if (BubbleEnabled()) { ASSERT_EQ(1U, GetBubblesQueueSize(manager_a0)); ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1)); } else { ASSERT_EQ(1U, infobar_service()->infobar_count()); ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count()); } // Accept the first request in tab A1. if (BubbleEnabled()) { AcceptBubble(manager_a1); } else { infobars::InfoBar* infobar_a1 = infobar_service_for_tab(0)->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate_a1 = infobar_a1->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate_a1); infobar_delegate_a1->Accept(); infobar_service_for_tab(0)->RemoveInfoBar(infobar_a1); EXPECT_EQ(2U, closed_infobar_tracker_.size()); EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar_a1)); } CheckPermissionMessageSentForTab(0, 0, true); // Because they're the same origin, this will cause tab A0's infobar to // disappear. It does not cause the bubble to disappear: crbug.com/443013. // TODO(felt): Update this test when the bubble's behavior is changed. if (BubbleEnabled()) { EXPECT_EQ(1U, GetBubblesQueueSize(manager_a0)); } else { EXPECT_EQ(0U, infobar_service()->infobar_count()); CheckPermissionMessageSent(0, true); } // The second request should now be visible in tab A1. if (BubbleEnabled()) ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1)); else ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count()); // Accept the second request and check that it's gone. if (BubbleEnabled()) { AcceptBubble(manager_a1); EXPECT_EQ(0U, GetBubblesQueueSize(manager_a1)); } else { infobars::InfoBar* infobar_1 = infobar_service_for_tab(0)->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate_1 = infobar_1->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate_1); infobar_delegate_1->Accept(); } } TEST_P(GeolocationPermissionContextParamTests, TabDestroyed) { GURL requesting_frame_0("http://www.example.com/geolocation"); GURL requesting_frame_1("http://www.example-2.com/geolocation"); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_0, requesting_frame_0)); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_1, requesting_frame_0)); NavigateAndCommit(requesting_frame_0); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Request permission for two frames. RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame_0, false); RequestGeolocationPermission( web_contents(), RequestID(1), requesting_frame_1, false); // Ensure only one prompt is created. ASSERT_EQ(1U, GetNumberOfPrompts()); // Delete the tab contents. if (!BubbleEnabled()) { infobars::InfoBar* infobar = infobar_service()->infobar_at(0); DeleteContents(); ASSERT_EQ(1U, closed_infobar_tracker_.size()); ASSERT_TRUE(closed_infobar_tracker_.Contains(infobar)); } // The content settings should not have changed. EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_0, requesting_frame_0)); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_1, requesting_frame_0)); } TEST_P(GeolocationPermissionContextParamTests, LastUsageAudited) { GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); base::SimpleTestClock* test_clock = new base::SimpleTestClock; test_clock->SetNow(base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(10)); HostContentSettingsMap* map = profile()->GetHostContentSettingsMap(); map->SetPrefClockForTesting(scoped_ptr<base::Clock>(test_clock)); // The permission shouldn't have been used yet. EXPECT_EQ(map->GetLastUsage(requesting_frame.GetOrigin(), requesting_frame.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 0); ASSERT_EQ(0U, GetNumberOfPrompts()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, false); ASSERT_EQ(1U, GetNumberOfPrompts()); AcceptPrompt(); CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); // Permission has been used at the starting time. EXPECT_EQ(map->GetLastUsage(requesting_frame.GetOrigin(), requesting_frame.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 10); test_clock->Advance(base::TimeDelta::FromSeconds(3)); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, false); // Permission has been used three seconds later. EXPECT_EQ(map->GetLastUsage(requesting_frame.GetOrigin(), requesting_frame.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 13); } TEST_P(GeolocationPermissionContextParamTests, LastUsageAuditedMultipleFrames) { base::SimpleTestClock* test_clock = new base::SimpleTestClock; test_clock->SetNow(base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(10)); HostContentSettingsMap* map = profile()->GetHostContentSettingsMap(); map->SetPrefClockForTesting(scoped_ptr<base::Clock>(test_clock)); GURL requesting_frame_0("http://www.example.com/geolocation"); GURL requesting_frame_1("http://www.example-2.com/geolocation"); // The permission shouldn't have been used yet. EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 0); EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 0); NavigateAndCommit(requesting_frame_0); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); EXPECT_EQ(0U, GetNumberOfPrompts()); // Request permission for two frames. RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame_0, false); RequestGeolocationPermission( web_contents(), RequestID(1), requesting_frame_1, false); // Ensure only one infobar is created. ASSERT_EQ(1U, GetNumberOfPrompts()); // Accept the first frame. AcceptPrompt(); if (!BubbleEnabled()) infobar_service()->RemoveInfoBar(infobar_service()->infobar_at(0)); CheckTabContentsState(requesting_frame_0, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); // Verify that accepting the first didn't accept because it's embedded // in the other. EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 10); EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 0); ASSERT_EQ(1U, GetNumberOfPrompts()); test_clock->Advance(base::TimeDelta::FromSeconds(1)); // Allow the second frame. AcceptPrompt(); CheckTabContentsState(requesting_frame_1, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(1, true); if (!BubbleEnabled()) infobar_service()->RemoveInfoBar(infobar_service()->infobar_at(0)); // Verify that the times are different. EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 10); EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 11); test_clock->Advance(base::TimeDelta::FromSeconds(2)); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame_0, false); // Verify that requesting permission in one frame doesn't update other where // it is the embedder. EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 13); EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 11); } INSTANTIATE_TEST_CASE_P(GeolocationPermissionContextTestsWithAndWithoutBubbles, GeolocationPermissionContextParamTests, ::testing::Values(false, true));
sgraham/nope
chrome/browser/geolocation/geolocation_permission_context_unittest.cc
C++
bsd-3-clause
37,152
// transform/fmllr-raw.cc // Copyright 2013 Johns Hopkins University (author: Daniel Povey) // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include <utility> #include <vector> using std::vector; #include "transform/fmllr-raw.h" #include "transform/fmllr-diag-gmm.h" namespace kaldi { FmllrRawAccs::FmllrRawAccs(int32 raw_dim, int32 model_dim, const Matrix<BaseFloat> &full_transform) : raw_dim_(raw_dim), model_dim_(model_dim) { if (full_transform.NumCols() != full_transform.NumRows() && full_transform.NumCols() != full_transform.NumRows() + 1) { KALDI_ERR << "Expecting full LDA+MLLT transform to be square or d by d+1 " << "(make sure you are including rejected rows)."; } if (raw_dim <= 0 || full_transform.NumRows() % raw_dim != 0) KALDI_ERR << "Raw feature dimension is invalid " << raw_dim << "(must be positive and divide feature dimension)"; int32 full_dim = full_transform.NumRows(); full_transform_ = full_transform.Range(0, full_dim, 0, full_dim); transform_offset_.Resize(full_dim); if (full_transform_.NumCols() == full_dim + 1) transform_offset_.CopyColFromMat(full_transform_, full_dim); int32 full_dim2 = ((full_dim + 1) * (full_dim + 2)) / 2; count_ = 0.0; temp_.Resize(full_dim + 1); Q_.Resize(model_dim + 1, full_dim + 1); S_.Resize(model_dim + 1, full_dim2); single_frame_stats_.s.Resize(full_dim + 1); single_frame_stats_.transformed_data.Resize(full_dim); single_frame_stats_.count = 0.0; single_frame_stats_.a.Resize(model_dim); single_frame_stats_.b.Resize(model_dim); } bool FmllrRawAccs::DataHasChanged(const VectorBase<BaseFloat> &data) const { KALDI_ASSERT(data.Dim() == FullDim()); return !data.ApproxEqual(single_frame_stats_.s.Range(0, FullDim()), 0.0); } void FmllrRawAccs::CommitSingleFrameStats() { // Commit the stats for this from (in SingleFrameStats). int32 model_dim = ModelDim(), full_dim = FullDim(); SingleFrameStats &stats = single_frame_stats_; if (stats.count == 0.0) return; count_ += stats.count; // a_ext and b_ext are a and b extended with the count, // which we'll later use to reconstruct the full stats for // the rejected dimensions. Vector<double> a_ext(model_dim + 1), b_ext(model_dim + 1); a_ext.Range(0, model_dim).CopyFromVec(stats.a); b_ext.Range(0, model_dim).CopyFromVec(stats.b); a_ext(model_dim) = stats.count; b_ext(model_dim) = stats.count; Q_.AddVecVec(1.0, a_ext, Vector<double>(stats.s)); temp_.SetZero(); temp_.AddVec2(1.0, stats.s); int32 full_dim2 = ((full_dim + 1) * (full_dim + 2)) / 2; SubVector<double> temp_vec(temp_.Data(), full_dim2); S_.AddVecVec(1.0, b_ext, temp_vec); } void FmllrRawAccs::InitSingleFrameStats(const VectorBase<BaseFloat> &data) { SingleFrameStats &stats = single_frame_stats_; int32 full_dim = FullDim(); KALDI_ASSERT(data.Dim() == full_dim); stats.s.Range(0, full_dim).CopyFromVec(data); stats.s(full_dim) = 1.0; stats.transformed_data.AddMatVec(1.0, full_transform_, kNoTrans, data, 0.0); stats.transformed_data.AddVec(1.0, transform_offset_); stats.count = 0.0; stats.a.SetZero(); stats.b.SetZero(); } BaseFloat FmllrRawAccs::AccumulateForGmm(const DiagGmm &gmm, const VectorBase<BaseFloat> &data, BaseFloat weight) { int32 model_dim = ModelDim(), full_dim = FullDim(); KALDI_ASSERT(data.Dim() == full_dim && "Expect raw, spliced data, which should have same dimension as " "full transform."); if (DataHasChanged(data)) { // this is part of our mechanism to accumulate certain sub-parts of // the computation for each frame, to avoid excessive compute. CommitSingleFrameStats(); InitSingleFrameStats(data); } SingleFrameStats &stats = single_frame_stats_; SubVector<BaseFloat> projected_data(stats.transformed_data, 0, model_dim); int32 num_gauss = gmm.NumGauss(); Vector<BaseFloat> posterior(num_gauss); BaseFloat log_like = gmm.ComponentPosteriors(projected_data, &posterior); posterior.Scale(weight); // Note: AccumulateFromPosteriors takes the original, spliced data, // and returns the log-like of the rejected dimensions. AccumulateFromPosteriors(gmm, data, posterior); // Add the likelihood of the rejected dimensions to the objective function // (assume zero-mean, unit-variance Gaussian; the LDA should have any offset // required to ensure this). if (full_dim > model_dim) { SubVector<BaseFloat> rejected_data(stats.transformed_data, model_dim, full_dim - model_dim); log_like += -0.5 * (VecVec(rejected_data, rejected_data) + (full_dim - model_dim) * M_LOG_2PI); } return log_like; } /* // Extended comment here. // // Let x_t(i) be the fully processed feature, dimension i (with fMLLR transform // and LDA transform), but *without* any offset term from the LDA, which // it's more convenient to view as an offset in the model. // // // For a given dimension i (either accepted or rejected), the auxf can // be expressed as a quadratic function of x_t(i). We ultimately will want to // express x_t(i) as a linear function of the parameters of the linearized // fMLLR transform matrix. Some notation: // Let l be the linearized transform matrix, i.e. the concatenation of the // m rows, each of length m+1, of the fMLLR transform. // Let n be the number of frames we splice together each time. // Let s_t be the spliced-together features on time t, with a one appended; // it will have n blocks each of size m, followed by a 1. (dim is n*m + 1). // // x(i) [note, this is the feature without any LDA offset], is bilinear in the // transform matrix and the features, so: // // x(i) = l^T M_i s_t, where s_t is the spliced features on time t, // with a 1 appended // [we need to compute M_i but we know the function is bilinear so it exists]. // // The auxf can be written as: // F = sum_i sum_t a_{ti} x(i) - 0.5 b_{ti} x(i)^2 // = sum_i sum_t a_{ti} x(i) - 0.5 b_{ti} x(i)^2 // = sum_i sum_t a_{ti} (l^T M_i s_t) - 0.5 b_{ti} (l^T M_i s_t )^2 // = sum_i l^T M_i q_i + l^T M_i S_i M_i^T l // where // q_i = sum_t a_{ti} s_t, and // S_i = sum_t b_{ti} s_t s_t^T // [Note that we only need store S_i for the model-dim plus one, because // all the rejected dimensions have the same value] // // We define a matrix Q whose rows are q_d, with // Q = \sum_t d_t s_t^T // [The Q we actually store as stats will use a modified form of d that // has a 1 for all dimensions past the model dim, to avoid redundancy; // we'll reconstruct the true Q from this later on.] // // // What is M_i? Working it out is a little tedious. // Note: each M_i (from i = 0 ... full_dim) is of // dimension (raw_dim*(raw_dim+1)) by full_dim + 1 // // We want to express x(i) [we forget the subscript "t" sometimes], // as a bilinear function of l and s_t. // We have x(i) = l^T M_i s. // // The (j,k)'th component of M_i is the term in x(i) that corresponds to the j'th // component of l and the k'th of s. // Before defining M_i, let us define N_i, where l^t N_i s will equal the spliced and // transformed pre-LDA features of dimension i. the N's have the same dimensions as the // M's. // // We'll first define the j,k'th component of N_i, as this is easier; we'll then define the M_i // as combinations of N_i. // // For a given i, j and k, the value of n_{i,j,k} will be as follows: // We first decompose index j into j1, j2 (both functions of // the original index j), where // j1 corresponds to the row-index of the fMLLR transform, j2 to the col-index. // We next decompose i into i1, i2, where i1 corresponds to the splicing number // (0...n-1), and i2 corresponds to the cepstral index. // // If (j1 != i2) then n_{ijk} == 0. // // Elsif k corresponds to the last element [i.e. k == m * n], then this m_{ijk} corresponds // to the effect of the j'th component of l for zero input, so: // If j2 == m (i.e. this the offset term in the fMLLR matrix), then // n_{ijk} = 1.0, // Else // n_{ijk} = 0.0 // Fi // // Else: // Decompose k into k1, k2, where k1 = 0.. n-1 is the splicing index, and k2 = 0...m-1 is // the cepstral index. // If k1 != i1 then // n_{ijk} = 0.0 // elsif k2 != j2 then // n_{ijk} = 0.0 // else // n_{ijk} = 1.0 // fi // Endif // Now, M_i will be defined as sum_i T_{ij} N_j, where T_{ij} are the elements of the // LDA+MLLT transform (but excluding any linear offset, which gets accounted for by // c_i, above). // // Now suppose we want to express the auxiliary function in a simpler form // as l^T v - 0.5 l^T W l, where v and W are the "simple" linear and quadratic stats, // we can do so with: // v = \sum_i M_i q_i // and // W = \sum_i M_i S_i M_i^T // */ void FmllrRawAccs::AccumulateFromPosteriors( const DiagGmm &diag_gmm, const VectorBase<BaseFloat> &data, const VectorBase<BaseFloat> &posterior) { // The user may call this function directly, even though we also // call it from AccumulateForGmm(), so check again: if (DataHasChanged(data)) { CommitSingleFrameStats(); InitSingleFrameStats(data); } int32 model_dim = ModelDim(); SingleFrameStats &stats = single_frame_stats_; // The quantities a and b describe the diagonal auxiliary function // for each of the retained dimensions in the transformed space-- // in the format F = \sum_d alpha(d) x(d) -0.5 beta(d) x(d)^2, // where x(d) is the d'th dimensional fully processed feature. // For d, see the comment-- it's alpha processed to take into // account any offset in the LDA. Note that it's a reference. // Vector<double> a(model_dim), b(model_dim); int32 num_comp = diag_gmm.NumGauss(); double count = 0.0; // data-count contribution from this frame. // Note: we could do this using matrix-matrix operations instead of // row by row. In the end it won't really matter as this is not // the slowest part of the computation. for (size_t m = 0; m < num_comp; m++) { BaseFloat this_post = posterior(m); if (this_post != 0.0) { count += this_post; a.AddVec(this_post, diag_gmm.means_invvars().Row(m)); b.AddVec(this_post, diag_gmm.inv_vars().Row(m)); } } // Correct "a" for any offset term in the LDA transform-- we view it as // the opposite offset in the model [note: we'll handle the rejected // dimensions // in update time.] Here, multiplying the element of "b" (which is the // weighted inv-vars) by transform_offset_, and subtracting the result from // a, is like subtracting the transform-offset from the original means // (because a contains the means times inv-vars_. Vector<double> offset(transform_offset_.Range(0, model_dim)); a.AddVecVec(-1.0, b, offset, 1.0); stats.a.AddVec(1.0, a); stats.b.AddVec(1.0, b); stats.count += count; } void FmllrRawAccs::Update(const FmllrRawOptions &opts, MatrixBase<BaseFloat> *raw_fmllr_mat, BaseFloat *objf_impr, BaseFloat *count) { // First commit any pending stats from the last frame. if (single_frame_stats_.count != 0.0) CommitSingleFrameStats(); if (this->count_ < opts.min_count) { KALDI_WARN << "Not updating (raw) fMLLR since count " << this->count_ << " is less than min count " << opts.min_count; *objf_impr = 0.0; *count = this->count_; return; } KALDI_ASSERT(raw_fmllr_mat->NumRows() == RawDim() && raw_fmllr_mat->NumCols() == RawDim() + 1 && !raw_fmllr_mat->IsZero()); Matrix<double> fmllr_mat( *raw_fmllr_mat); // temporary, double-precision version // of matrix. Matrix<double> linear_stats; // like K in diagonal update. std::vector<SpMatrix<double> > diag_stats; // like G in diagonal update. // Note: we will invert these. std::vector<std::vector<Matrix<double> > > off_diag_stats; // these will // contribute to the linear term. Vector<double> simple_linear_stats; SpMatrix<double> simple_quadratic_stats; ConvertToSimpleStats(&simple_linear_stats, &simple_quadratic_stats); ConvertToPerRowStats(simple_linear_stats, simple_quadratic_stats, &linear_stats, &diag_stats, &off_diag_stats); try { for (size_t i = 0; i < diag_stats.size(); i++) { diag_stats[i].Invert(); } } catch (...) { KALDI_WARN << "Error inverting stats matrices for fMLLR " << "[min-count too small? Bad data?], not updating."; return; } int32 raw_dim = RawDim(), splice_width = SpliceWidth(); double effective_beta = count_ * splice_width; // We "count" the determinant // splice_width times in the objective function. double auxf_orig = GetAuxf(simple_linear_stats, simple_quadratic_stats, fmllr_mat); for (int32 iter = 0; iter < opts.num_iters; iter++) { for (int32 row = 0; row < raw_dim; row++) { SubVector<double> this_row(fmllr_mat, row); Vector<double> this_linear(raw_dim + 1); // Here, k_i is the linear term // in the auxf expressed as a function of this row. this_linear.CopyFromVec(linear_stats.Row(row)); for (int32 row2 = 0; row2 < raw_dim; row2++) { if (row2 != row) { if (row2 < row) { this_linear.AddMatVec(-1.0, off_diag_stats[row][row2], kNoTrans, fmllr_mat.Row(row2), 1.0); } else { // We won't have the element [row][row2] stored, but use symmetry. this_linear.AddMatVec(-1.0, off_diag_stats[row2][row], kTrans, fmllr_mat.Row(row2), 1.0); } } } FmllrInnerUpdate(diag_stats[row], this_linear, effective_beta, row, &fmllr_mat); } if (GetVerboseLevel() >= 2) { double cur_auxf = GetAuxf(simple_linear_stats, simple_quadratic_stats, fmllr_mat), auxf_change = cur_auxf - auxf_orig; KALDI_VLOG(2) << "Updating raw fMLLR: objf improvement per frame was " << (auxf_change / this->count_) << " over " << this->count_ << " frames, by the " << iter << "'th iteration"; } } double auxf_final = GetAuxf(simple_linear_stats, simple_quadratic_stats, fmllr_mat), auxf_change = auxf_final - auxf_orig; *count = this->count_; KALDI_VLOG(1) << "Updating raw fMLLR: objf improvement per frame was " << (auxf_change / this->count_) << " over " << this->count_ << " frames."; if (auxf_final > auxf_orig) { *objf_impr = auxf_change; *count = this->count_; raw_fmllr_mat->CopyFromMat(fmllr_mat); } else { *objf_impr = 0.0; // don't update "raw_fmllr_mat" } } void FmllrRawAccs::SetZero() { count_ = 0.0; single_frame_stats_.count = 0.0; single_frame_stats_.s.SetZero(); Q_.SetZero(); S_.SetZero(); } // Compute the M_i quantities, needed in the update. This function could be // greatly speeded up but I don't think it's the limiting factor. void FmllrRawAccs::ComputeM(std::vector<Matrix<double> > *M) const { int32 full_dim = FullDim(), raw_dim = RawDim(), raw_dim2 = raw_dim * (raw_dim + 1); M->resize(full_dim); for (int32 i = 0; i < full_dim; i++) (*M)[i].Resize(raw_dim2, full_dim + 1); // the N's are simpler matrices from which we'll interpolate the M's. // In this loop we imagine w are computing the vector of N's, but // when we get each element, if it's nonzero we propagate it straight // to the M's. for (int32 i = 0; i < full_dim; i++) { // i is index after fMLLR transform; i1 is splicing index, // i2 is cepstral index. int32 i1 = i / raw_dim, i2 = i % raw_dim; for (int32 j = 0; j < raw_dim2; j++) { // j1 is row-index of fMLLR transform, j2 is column-index int32 j1 = j / (raw_dim + 1), j2 = j % (raw_dim + 1); for (int32 k = 0; k < full_dim + 1; k++) { BaseFloat n_ijk; if (j1 != i2) { n_ijk = 0.0; } else if (k == full_dim) { if (j2 == raw_dim) // offset term in fMLLR matrix. n_ijk = 1.0; else n_ijk = 0.0; } else { // k1 is splicing index, k2 is cepstral idnex. int32 k1 = k / raw_dim, k2 = k % raw_dim; if (k1 != i1 || k2 != j2) n_ijk = 0.0; else n_ijk = 1.0; } if (n_ijk != 0.0) for (int32 l = 0; l < full_dim; l++) (*M)[l](j, k) += n_ijk * full_transform_(l, i); } } } } void FmllrRawAccs::ConvertToSimpleStats( Vector<double> *simple_linear_stats, SpMatrix<double> *simple_quadratic_stats) const { std::vector<Matrix<double> > M; ComputeM(&M); int32 full_dim = FullDim(), raw_dim = RawDim(), model_dim = ModelDim(), raw_dim2 = raw_dim * (raw_dim + 1), full_dim2 = ((full_dim + 1) * (full_dim + 2)) / 2; simple_linear_stats->Resize(raw_dim2); simple_quadratic_stats->Resize(raw_dim2); for (int32 i = 0; i < full_dim; i++) { Vector<double> q_i(full_dim + 1); SpMatrix<double> S_i(full_dim + 1); SubVector<double> S_i_vec(S_i.Data(), full_dim2); if (i < model_dim) { q_i.CopyFromVec(Q_.Row(i)); S_i_vec.CopyFromVec(S_.Row(i)); } else { q_i.CopyFromVec( Q_.Row(model_dim)); // The last row contains stats proportional // to "count", which we need to modify to be correct. q_i.Scale( -transform_offset_(i)); // These stats are zero (corresponding to // a zero-mean model) if there is no offset in the LDA transform. Note: // the two statements above are the equivalent, for the rejected dims, // of the statement "a.AddVecVec(-1.0, b, offset);" for the kept ones. // S_i_vec.CopyFromVec(S_.Row(model_dim)); // these are correct, and // all the same (corresponds to unit variance). } // The equation v = \sum_i M_i q_i: simple_linear_stats->AddMatVec(1.0, M[i], kNoTrans, q_i, 1.0); // The equation W = \sum_i M_i S_i M_i^T // Here, M[i] is quite sparse, so AddSmat2Sp will be faster. simple_quadratic_stats->AddSmat2Sp(1.0, M[i], kNoTrans, S_i, 1.0); } } // See header for comment. void FmllrRawAccs::ConvertToPerRowStats( const Vector<double> &simple_linear_stats, const SpMatrix<double> &simple_quadratic_stats_sp, Matrix<double> *linear_stats, std::vector<SpMatrix<double> > *diag_stats, std::vector<std::vector<Matrix<double> > > *off_diag_stats) const { // get it as a Matrix, which makes it easier to extract sub-parts. Matrix<double> simple_quadratic_stats(simple_quadratic_stats_sp); linear_stats->Resize(RawDim(), RawDim() + 1); linear_stats->CopyRowsFromVec(simple_linear_stats); diag_stats->resize(RawDim()); off_diag_stats->resize(RawDim()); // Set *diag_stats int32 rd1 = RawDim() + 1; for (int32 i = 0; i < RawDim(); i++) { SubMatrix<double> this_diag(simple_quadratic_stats, i * rd1, rd1, i * rd1, rd1); (*diag_stats)[i].Resize(RawDim() + 1); (*diag_stats)[i].CopyFromMat(this_diag, kTakeMean); } for (int32 i = 0; i < RawDim(); i++) { (*off_diag_stats)[i].resize(i); for (int32 j = 0; j < i; j++) { SubMatrix<double> this_off_diag(simple_quadratic_stats, i * rd1, rd1, j * rd1, rd1); (*off_diag_stats)[i][j] = this_off_diag; } } } double FmllrRawAccs::GetAuxf(const Vector<double> &simple_linear_stats, const SpMatrix<double> &simple_quadratic_stats, const Matrix<double> &fmllr_mat) const { // linearize transform... int32 raw_dim = RawDim(), spice_width = SpliceWidth(); Vector<double> fmllr_vec(raw_dim * (raw_dim + 1)); fmllr_vec.CopyRowsFromMat(fmllr_mat); SubMatrix<double> square_part(fmllr_mat, 0, raw_dim, 0, raw_dim); double logdet = square_part.LogDet(); return VecVec(fmllr_vec, simple_linear_stats) - 0.5 * VecSpVec(fmllr_vec, simple_quadratic_stats, fmllr_vec) + logdet * spice_width * count_; } } // namespace kaldi
hoangt/djinn
tonic-suite/asr/src/transform/fmllr-raw.cc
C++
bsd-3-clause
21,344
if (this.importScripts) { importScripts('../../../fast/js/resources/js-test-pre.js'); importScripts('shared.js'); } description("Test transaction aborts send the proper onabort messages.."); indexedDBTest(prepareDatabase, startTest); function prepareDatabase() { db = event.target.result; store = evalAndLog("store = db.createObjectStore('storeName', null)"); request = evalAndLog("store.add({x: 'value', y: 'zzz'}, 'key')"); request.onerror = unexpectedErrorCallback; } function startTest() { trans = evalAndLog("trans = db.transaction(['storeName'], 'readwrite')"); evalAndLog("trans.onabort = transactionAborted"); evalAndLog("trans.oncomplete = unexpectedCompleteCallback"); store = evalAndLog("store = trans.objectStore('storeName')"); request = evalAndLog("store.add({x: 'value2', y: 'zzz2'}, 'key2')"); request.onerror = firstAdd; request.onsuccess = unexpectedSuccessCallback; request = evalAndLog("store.add({x: 'value3', y: 'zzz3'}, 'key3')"); request.onerror = secondAdd; request.onsuccess = unexpectedSuccessCallback; trans.abort(); firstError = false; secondError = false; abortFired = false; } function firstAdd() { shouldBe("event.target.error.name", "'AbortError'"); shouldBeNull("trans.error"); shouldBeFalse("firstError"); shouldBeFalse("secondError"); shouldBeFalse("abortFired"); firstError = true; evalAndExpectException("store.add({x: 'value4', y: 'zzz4'}, 'key4')", "0", "'TransactionInactiveError'"); } function secondAdd() { shouldBe("event.target.error.name", "'AbortError'"); shouldBeNull("trans.error"); shouldBeTrue("firstError"); shouldBeFalse("secondError"); shouldBeFalse("abortFired"); secondError = true; } function transactionAborted() { shouldBeTrue("firstError"); shouldBeTrue("secondError"); shouldBeFalse("abortFired"); shouldBeNull("trans.error"); abortFired = true; evalAndExpectException("store.add({x: 'value5', y: 'zzz5'}, 'key5')", "0", "'TransactionInactiveError'"); evalAndExpectException("trans.abort()", "DOMException.INVALID_STATE_ERR", "'InvalidStateError'"); finishJSTest(); }
leighpauls/k2cro4
content/test/data/layout_tests/LayoutTests/storage/indexeddb/resources/transaction-abort.js
JavaScript
bsd-3-clause
2,204
// Copyright (C) 2015 Intel Corporation All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #if ENABLE(WEBCL) #include "modules/webcl/WebCLContext.h" #include "modules/webcl/WebCLObject.h" namespace blink { WebCLObject::~WebCLObject() { if (m_context) m_context->untrackReleaseableWebCLObject(createWeakPtr()); } WebCLObject::WebCLObject(WebCLContext* context) : m_weakFactory(this) , m_context(context) { ASSERT(m_context); m_context->trackReleaseableWebCLObject(createWeakPtr()); } WebCLObject::WebCLObject() : m_weakFactory(this) , m_context(nullptr) { } WebCLContext* WebCLObject::context() { ASSERT(m_context); return m_context; } void WebCLObject::setContext(WebCLContext* context) { m_context = context; m_context->trackReleaseableWebCLObject(createWeakPtr()); } } // namespace blink #endif // ENABLE(WEBCL)
XiaosongWei/blink-crosswalk
Source/modules/webcl/WebCLObject.cpp
C++
bsd-3-clause
970
#!/usr/bin/env python import argparse import time from pytx import ThreatIndicator from pytx.vocabulary import ThreatExchange as te from pytx.vocabulary import ThreatType as tt from pytx.vocabulary import Types as t def get_results(options): ''' Builds a query string based on the specified options and runs it. ''' if options.since is None or options.until is None: raise Exception('You must specify both "since" and "until" values') results = ThreatIndicator.objects(threat_type=tt.COMPROMISED_CREDENTIAL, type_=t.EMAIL_ADDRESS, limit=options.limit, fields=['indicator', 'passwords'], since=options.since, until=options.until) return results def process_result(handle, result): ''' Process the threat indicators received from the server. This version writes the indicators to the output file specified by 'handle', if any. Indicators are written one per line. ''' for password in result.passwords: output = '%s:%s\n' % (result.indicator, password) if handle is None: print output, else: handle.write(output) def run_query(options, handle): start = int(time.time()) print 'READING %s%s' % (te.URL, te.THREAT_INDICATORS) results = get_results(options) count = 0 for result in results: process_result(handle, result) count += 1 end = int(time.time()) print ('SUCCESS: Got %d indicators in %d seconds' % (count, end - start)) return def get_args(): parser = argparse.ArgumentParser(description='Query ThreatExchange for Compromised Credentials') parser.add_argument('-o', '--output', default='/dev/stdout', help='[OPTIONAL] output file path.') parser.add_argument('-s', '--since', help='[OPTIONAL] Start time for search') parser.add_argument('-u', '--until', help='[OPTIONAL] End time for search') parser.add_argument('-l', '--limit', help='[OPTIONAL] Maximum number of results') return parser.parse_args() def main(): args = get_args() with open(args.output, 'w') as fp: run_query(args, fp) if __name__ == '__main__': main()
arirubinstein/ThreatExchange
scripts/get_compromised_credentials.py
Python
bsd-3-clause
2,285
// Copyright Peter Dimov 2001-2002 // Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // *Preprocessed* version of the main "arg.hpp" header // -- DO NOT modify by hand! NDNBOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN template<> struct arg< -1 > { NDNBOOST_STATIC_CONSTANT(int, value = -1); NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag) NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type) template< typename U1, typename U2, typename U3, typename U4, typename U5 > struct apply { typedef U1 type; NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type); }; }; template<> struct arg<1> { NDNBOOST_STATIC_CONSTANT(int, value = 1); typedef arg<2> next; NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag) NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type) template< typename U1, typename U2, typename U3, typename U4, typename U5 > struct apply { typedef U1 type; NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type); }; }; template<> struct arg<2> { NDNBOOST_STATIC_CONSTANT(int, value = 2); typedef arg<3> next; NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag) NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type) template< typename U1, typename U2, typename U3, typename U4, typename U5 > struct apply { typedef U2 type; NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type); }; }; template<> struct arg<3> { NDNBOOST_STATIC_CONSTANT(int, value = 3); typedef arg<4> next; NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag) NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type) template< typename U1, typename U2, typename U3, typename U4, typename U5 > struct apply { typedef U3 type; NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type); }; }; template<> struct arg<4> { NDNBOOST_STATIC_CONSTANT(int, value = 4); typedef arg<5> next; NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag) NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type) template< typename U1, typename U2, typename U3, typename U4, typename U5 > struct apply { typedef U4 type; NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type); }; }; template<> struct arg<5> { NDNBOOST_STATIC_CONSTANT(int, value = 5); typedef arg<6> next; NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, tag) NDNBOOST_MPL_AUX_ARG_TYPEDEF(na, type) template< typename U1, typename U2, typename U3, typename U4, typename U5 > struct apply { typedef U5 type; NDNBOOST_MPL_AUX_ASSERT_NOT_NA(type); }; }; NDNBOOST_MPL_AUX_NONTYPE_ARITY_SPEC(1,int, arg) NDNBOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE
cawka/packaging-ndn-cpp-dev
include/ndnboost/mpl/aux_/preprocessed/bcc_pre590/arg.hpp
C++
bsd-3-clause
2,771
package org.buildmlearn.toolkit.fragment; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.buildmlearn.toolkit.R; import org.buildmlearn.toolkit.activity.TemplateActivity; /** * @brief Fragment displayed on the home screen. */ public class HomeFragment extends Fragment { /** * {@inheritDoc} */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); view.findViewById(R.id.button_template).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getActivity(), TemplateActivity.class)); } }); return view; } }
vishwesh3/BuildmLearn-Toolkit-Android
source-code/app/src/main/java/org/buildmlearn/toolkit/fragment/HomeFragment.java
Java
bsd-3-clause
1,033
package com.xeiam.xchange.btcchina; import java.io.IOException; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import si.mazi.rescu.ParamsDigest; import si.mazi.rescu.SynchronizedValueFactory; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetAccountInfoRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetDepositsRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetWithdrawalRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaGetWithdrawalsRequest; import com.xeiam.xchange.btcchina.dto.account.request.BTCChinaRequestWithdrawalRequest; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetAccountInfoResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetDepositsResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetWithdrawalResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaGetWithdrawalsResponse; import com.xeiam.xchange.btcchina.dto.account.response.BTCChinaRequestWithdrawalResponse; import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaDepth; import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaTicker; import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaTrade; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetIcebergOrdersRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetMarketDepthRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetOrdersRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetStopOrdersRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellIcebergOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellStopOrderRequest; import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaTransactionsRequest; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaBooleanResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetIcebergOrderResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetIcebergOrdersResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetMarketDepthResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetOrderResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetOrdersResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetStopOrderResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetStopOrdersResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaIntegerResponse; import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaTransactionsResponse; @Path("/") @Produces(MediaType.APPLICATION_JSON) public interface BTCChina { @GET @Path("data/ticker") BTCChinaTicker getTicker(@QueryParam("market") String market) throws IOException; /** * Returns all the open orders from the specified {@code market}. * * @param market the market could be {@code btccny}, {@code ltccny}, {@code ltcbtc}. * @return the order book. * @throws IOException indicates I/O exception. * @see #getOrderBook(String, int) */ @GET @Path("data/orderbook") BTCChinaDepth getFullDepth(@QueryParam("market") String market) throws IOException; /** * Order book default contains all open ask and bid orders. Set 'limit' parameter to specify the number of records fetched per request. * <p> * Bid orders are {@code limit} orders with highest price while ask with lowest, and orders are descendingly sorted by price. * </p> * * @param market market could be {@code btccny}, {@code ltccny}, {@code ltcbtc}. * @param limit number of records fetched per request. * @return the order book. * @throws IOException indicates I/O exception. * @see #getFullDepth(String) */ @GET @Path("data/orderbook") BTCChinaDepth getOrderBook(@QueryParam("market") String market, @QueryParam("limit") int limit) throws IOException; /** * Returns last 100 trade records. */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market) throws IOException; /** * Returns last {@code limit} trade records. * * @param market * @param limit the range of limit is [0,5000]. * @throws IOException */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("limit") int limit) throws IOException; /** * Returns 100 trade records starting from id {@code since}. * * @param market * @param since the starting trade ID(exclusive). * @throws IOException */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since) throws IOException; /** * Returns {@code limit} trades starting from id {@code since} * * @param market * @param since the starting trade ID(exclusive). * @param limit the range of limit is [0,5000]. * @throws IOException */ @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since, @QueryParam("limit") int limit) throws IOException; @GET @Path("data/historydata") BTCChinaTrade[] getHistoryData(@QueryParam("market") String market, @QueryParam("since") long since, @QueryParam("limit") int limit, @QueryParam("sincetype") @DefaultValue("id") String sincetype) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetAccountInfoResponse getAccountInfo(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetAccountInfoRequest getAccountInfoRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetDepositsResponse getDeposits(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetDepositsRequest getDepositsRequest) throws IOException; /** * Get the complete market depth. Returns all open bid and ask orders. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetMarketDepthResponse getMarketDepth(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetMarketDepthRequest request) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetWithdrawalResponse getWithdrawal(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetWithdrawalRequest request) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetWithdrawalsResponse getWithdrawals(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetWithdrawalsRequest request) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaRequestWithdrawalResponse requestWithdrawal(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaRequestWithdrawalRequest requestWithdrawalRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetOrderResponse getOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetOrderRequest getOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetOrdersResponse getOrders(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetOrdersRequest getOrdersRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaBooleanResponse cancelOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelOrderRequest cancelOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse buyOrder2(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyOrderRequest buyOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse sellOrder2(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellOrderRequest sellOrderRequest) throws IOException; @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaTransactionsResponse getTransactions(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaTransactionsRequest transactionRequest) throws IOException; /** * Place a buy iceberg order. This method will return an iceberg order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse buyIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyIcebergOrderRequest request) throws IOException; /** * Place a sell iceberg order. This method will return an iceberg order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse sellIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellIcebergOrderRequest request) throws IOException; /** * Get an iceberg order, including the orders placed. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetIcebergOrderResponse getIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetIcebergOrderRequest request) throws IOException; /** * Get iceberg orders, including the orders placed inside each iceberg order. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetIcebergOrdersResponse getIcebergOrders(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetIcebergOrdersRequest request) throws IOException; /** * Cancels an open iceberg order. Fails if iceberg order is already cancelled or closed. The related order with the iceberg order will also be * cancelled. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaBooleanResponse cancelIcebergOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelIcebergOrderRequest request) throws IOException; /** * Place a buy stop order. This method will return a stop order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse buyStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaBuyStopOrderRequest request) throws IOException; /** * Place a sell stop order. This method will return an stop order id. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaIntegerResponse sellStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaSellStopOrderRequest request) throws IOException; /** * Get a stop order. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetStopOrderResponse getStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetStopOrderRequest request) throws IOException; /** * Get stop orders. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaGetStopOrdersResponse getStopOrders(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaGetStopOrdersRequest request) throws IOException; /** * Cancels an open stop order. Fails if stop order is already cancelled or closed. */ @POST @Path("api_trade_v1.php") @Consumes(MediaType.APPLICATION_JSON) BTCChinaBooleanResponse cancelStopOrder(@HeaderParam("Authorization") ParamsDigest authorization, @HeaderParam("Json-Rpc-Tonce") SynchronizedValueFactory<Long> jsonRpcTonce, BTCChinaCancelStopOrderRequest request) throws IOException; }
cinjoff/XChange-1
xchange-btcchina/src/main/java/com/xeiam/xchange/btcchina/BTCChina.java
Java
mit
14,863
<?php namespace Test\TestBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('test_test'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
max05/bootstrap
src/Test/TestBundle/DependencyInjection/Configuration.php
PHP
mit
873
function config ($logProvider) { 'ngInject'; // Enable log $logProvider.debugEnabled(true); } export default config;
mike1808/godtracks
src/app/index.config.js
JavaScript
mit
124
package gforms // Generate password input field: <input type="password" ...> func PasswordInputWidget(attrs map[string]string) Widget { w := new(textInputWidget) w.Type = "password" if attrs == nil { attrs = map[string]string{} } w.Attrs = attrs return w }
gernest/gforms
passwordinputwidget.go
GO
mit
266
# -*- encoding : utf-8 -*- # Use this setup block to configure all options available in SimpleForm. SimpleForm.setup do |config| # Wrappers are used by the form builder to generate a # complete input. You can remove any component from the # wrapper, change the order or even add your own to the # stack. The options given below are used to wrap the # whole input. config.wrappers :default, :class => :input, :hint_class => :field_with_hint, :error_class => :field_with_errors do |b| ## Extensions enabled by default # Any of these extensions can be disabled for a # given input by passing: `f.input EXTENSION_NAME => false`. # You can make any of these extensions optional by # renaming `b.use` to `b.optional`. # Determines whether to use HTML5 (:email, :url, ...) # and required attributes b.use :html5 # Calculates placeholders automatically from I18n # You can also pass a string as f.input :placeholder => "Placeholder" b.use :placeholder ## Optional extensions # They are disabled unless you pass `f.input EXTENSION_NAME => :lookup` # to the input. If so, they will retrieve the values from the model # if any exists. If you want to enable the lookup for any of those # extensions by default, you can change `b.optional` to `b.use`. # Calculates maxlength from length validations for string inputs b.optional :maxlength # Calculates pattern from format validations for string inputs b.optional :pattern # Calculates min and max from length validations for numeric inputs b.optional :min_max # Calculates readonly automatically from readonly attributes b.optional :readonly ## Inputs b.use :label_input b.use :hint, :wrap_with => { :tag => :span, :class => :hint } b.use :error, :wrap_with => { :tag => :span, :class => :error } end config.wrappers :bootstrap, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b| b.use :html5 b.use :placeholder b.use :label b.wrapper :tag => 'div', :class => 'controls' do |ba| ba.use :input ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' } ba.use :hint, :wrap_with => { :tag => 'p', :class => 'help-block' } end end config.wrappers :prepend, :tag => 'div', :class => "control-group", :error_class => 'error' do |b| b.use :html5 b.use :placeholder b.use :label b.wrapper :tag => 'div', :class => 'controls' do |input| input.wrapper :tag => 'div', :class => 'input-prepend' do |prepend| prepend.use :input end input.use :hint, :wrap_with => { :tag => 'span', :class => 'help-block' } input.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' } end end config.wrappers :append, :tag => 'div', :class => "control-group", :error_class => 'error' do |b| b.use :html5 b.use :placeholder b.use :label b.wrapper :tag => 'div', :class => 'controls' do |input| input.wrapper :tag => 'div', :class => 'input-append' do |append| append.use :input end input.use :hint, :wrap_with => { :tag => 'span', :class => 'help-block' } input.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' } end end # Wrappers for forms and inputs using the Twitter Bootstrap toolkit. # Check the Bootstrap docs (http://twitter.github.com/bootstrap) # to learn about the different styles for forms and inputs, # buttons and other elements. config.default_wrapper = :bootstrap # Define the way to render check boxes / radio buttons with labels. # Defaults to :nested for bootstrap config. # :inline => input + label # :nested => label > input config.boolean_style = :nested # Default class for buttons config.button_class = 'btn' # Method used to tidy up errors. Specify any Rails Array method. # :first lists the first message for each field. # Use :to_sentence to list all errors for each field. # config.error_method = :first # Default tag used for error notification helper. config.error_notification_tag = :div # CSS class to add for error notification helper. config.error_notification_class = 'alert alert-error' # ID to add for error notification helper. # config.error_notification_id = nil # Series of attempts to detect a default label method for collection. # config.collection_label_methods = [ :to_label, :name, :title, :to_s ] # Series of attempts to detect a default value method for collection. # config.collection_value_methods = [ :id, :to_s ] # You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none. # config.collection_wrapper_tag = nil # You can define the class to use on all collection wrappers. Defaulting to none. # config.collection_wrapper_class = nil # You can wrap each item in a collection of radio/check boxes with a tag, # defaulting to :span. Please note that when using :boolean_style = :nested, # SimpleForm will force this option to be a label. # config.item_wrapper_tag = :span # You can define a class to use in all item wrappers. Defaulting to none. # config.item_wrapper_class = nil # How the label text should be generated altogether with the required text. # config.label_text = lambda { |label, required| "#{required} #{label}" } # You can define the class to use on all labels. Default is nil. config.label_class = 'control-label' # You can define the class to use on all forms. Default is simple_form. # config.form_class = :simple_form # You can define which elements should obtain additional classes # config.generate_additional_classes_for = [:wrapper, :label, :input] # Whether attributes are required by default (or not). Default is true. # config.required_by_default = true # Tell browsers whether to use default HTML5 validations (novalidate option). # Default is enabled. config.browser_validations = false # Collection of methods to detect if a file type was given. # config.file_methods = [ :mounted_as, :file?, :public_filename ] # Custom mappings for input types. This should be a hash containing a regexp # to match as key, and the input type that will be used when the field name # matches the regexp as value. # config.input_mappings = { /count/ => :integer } # Default priority for time_zone inputs. # config.time_zone_priority = nil # Default priority for country inputs. # config.country_priority = nil # Default size for text inputs. # config.default_input_size = 50 # When false, do not use translations for labels. # config.translate_labels = true # Automatically discover new inputs in Rails' autoload path. # config.inputs_discovery = true # Cache SimpleForm inputs discovery # config.cache_discovery = !Rails.env.development? end
soramugi/gistub
config/initializers/simple_form.rb
Ruby
mit
6,878
/* Copyright 2012-2014 SpringSource. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package grails.plugin.springsecurity.web.access.channel; import java.io.IOException; import java.util.Collection; import javax.servlet.ServletException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.channel.InsecureChannelProcessor; import org.springframework.util.Assert; /** * @author <a href='mailto:burt@burtbeckwith.com'>Burt Beckwith</a> */ public class HeaderCheckInsecureChannelProcessor extends InsecureChannelProcessor { protected String headerName; protected String headerValue; @Override public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException { Assert.isTrue(invocation != null && config != null, "Nulls cannot be provided"); for (ConfigAttribute attribute : config) { if (supports(attribute)) { if (headerValue.equals(invocation.getHttpRequest().getHeader(headerName))) { getEntryPoint().commence(invocation.getRequest(), invocation.getResponse()); } } } } /** * Set the name of the header to check. * @param name the name */ public void setHeaderName(String name) { headerName = name; } /** * Set the header value to trigger a redirect. * @param value the value */ public void setHeaderValue(String value) { headerValue = value; } @Override public void afterPropertiesSet() throws Exception { super.afterPropertiesSet(); Assert.hasLength(headerName, "Header name is required"); Assert.hasLength(headerValue, "Header value is required"); } }
arunabhdas/pizzashop
target/work/plugins/spring-security-core-2.0-RC4/src/java/grails/plugin/springsecurity/web/access/channel/HeaderCheckInsecureChannelProcessor.java
Java
mit
2,217
/* Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'colorbutton', 'bs', { auto: 'Automatska', bgColorTitle: 'Boja pozadine', colors: { '000': 'Black', '800000': 'Maroon', '8B4513': 'Saddle Brown', '2F4F4F': 'Dark Slate Gray', '008080': 'Teal', '000080': 'Navy', '4B0082': 'Indigo', '696969': 'Dark Gray', B22222: 'Fire Brick', A52A2A: 'Brown', DAA520: 'Golden Rod', '006400': 'Dark Green', '40E0D0': 'Turquoise', '0000CD': 'Medium Blue', '800080': 'Purple', '808080': 'Gray', F00: 'Red', FF8C00: 'Dark Orange', FFD700: 'Gold', '008000': 'Green', '0FF': 'Cyan', '00F': 'Blue', EE82EE: 'Violet', A9A9A9: 'Dim Gray', FFA07A: 'Light Salmon', FFA500: 'Orange', FFFF00: 'Yellow', '00FF00': 'Lime', AFEEEE: 'Pale Turquoise', ADD8E6: 'Light Blue', DDA0DD: 'Plum', D3D3D3: 'Light Grey', FFF0F5: 'Lavender Blush', FAEBD7: 'Antique White', FFFFE0: 'Light Yellow', F0FFF0: 'Honeydew', F0FFFF: 'Azure', F0F8FF: 'Alice Blue', E6E6FA: 'Lavender', FFF: 'White', '1ABC9C': 'Strong Cyan', // MISSING '2ECC71': 'Emerald', // MISSING '3498DB': 'Bright Blue', // MISSING '9B59B6': 'Amethyst', // MISSING '4E5F70': 'Grayish Blue', // MISSING 'F1C40F': 'Vivid Yellow', // MISSING '16A085': 'Dark Cyan', // MISSING '27AE60': 'Dark Emerald', // MISSING '2980B9': 'Strong Blue', // MISSING '8E44AD': 'Dark Violet', // MISSING '2C3E50': 'Desaturated Blue', // MISSING 'F39C12': 'Orange', // MISSING 'E67E22': 'Carrot', // MISSING 'E74C3C': 'Pale Red', // MISSING 'ECF0F1': 'Bright Silver', // MISSING '95A5A6': 'Light Grayish Cyan', // MISSING 'DDD': 'Light Gray', // MISSING 'D35400': 'Pumpkin', // MISSING 'C0392B': 'Strong Red', // MISSING 'BDC3C7': 'Silver', // MISSING '7F8C8D': 'Grayish Cyan', // MISSING '999': 'Dark Gray' // MISSING }, more: 'Više boja...', panelTitle: 'Colors', textColorTitle: 'Boja teksta' } );
zweidner/hubzero-cms
core/plugins/editors/ckeditor/assets/plugins/colorbutton/lang/bs.js
JavaScript
mit
2,069
# encoding: utf-8 # require 'spec_helper' describe 'country descriptions' do def self.it_splits number, expected it { Phony.split(number).should == expected } end describe 'regression' do it_splits '33630588659', ["33", "6", "30", "58", "86", "59"] end describe 'splitting' do describe 'Ascension Island' do it_splits '2473551', ['247', false, '3551'] end describe 'Afghanistan' do it_splits '93201234567', ['93', '20', '1234567'] # Kabul end describe 'Algeria' do it_splits '213211231234', ['213', '21', '123', '1234'] # Algiers it_splits '213331231234', ['213', '33', '123', '1234'] # Batna end describe 'Argentina' do it_splits '541112345678', ['54', '11', '1234', '5678'] it_splits '542911234567', ['54', '291', '123', '4567'] it_splits '542965123456', ['54', '2965', '12', '3456'] it_splits '5491112345678', ['54', '911', '1234', '5678'] it_splits '5492201234567', ['54', '9220', '123', '4567'] it_splits '5492221123456', ['54', '92221', '12', '3456'] it_splits '548001234567', ['54', '800', '123', '4567'] end describe 'Austria' do it_splits '43198110', %w( 43 1 98110 ) # Vienna it_splits '4310000000', %w( 43 1 0000000 ) # Vienna it_splits '43800123456789', %w( 43 800 123456789 ) # Free it_splits '4368100000000', %w( 43 681 0000 0000 ) # Mobile it_splits '436880000000', %w( 43 688 0000 000 ) # Mobile it_splits '4366900000000', %w( 43 669 0000 0000 ) # Mobile it_splits '433161234567891', %w( 43 316 1234567891 ) # Graz it_splits '432164123456789', %w( 43 2164 123456789 ) # Rohrau # mobile numbers can have from 7 to 10 digits in the subscriber number it_splits '436641234567', %w( 43 664 1234 567 ) it_splits '4366412345678', %w( 43 664 1234 5678 ) it_splits '43664123456789', %w( 43 664 1234 56789 ) it_splits '436641234567890', %w( 43 664 1234 567890 ) end describe 'Australia' do it_splits '61512341234', ['61', '5', '1234', '1234'] # Landline it_splits '61423123123', ['61', '423', '123', '123'] # Mobile end describe 'Bahrain' do it_splits '97312345678', ['973', false, '1234', '5678'] end describe 'Bangladesh' do it_splits '88021234567', %w(880 2 1234567) it_splits '8805112345', %w(880 51 12345) it_splits '88031123456', %w(880 31 123456) it_splits '88032112345', %w(880 321 12345) it_splits '8804311234567', %w(880 431 1234567) it_splits '880902012345', %w(880 9020 12345) end describe 'Belarus' do it_splits '375152123456', %w(375 152 123456) it_splits '375151512345', %w(375 1515 12345) it_splits '375163423456', %w(375 163 423456) it_splits '375163112345', %w(375 1631 12345) it_splits '375291234567', %w(375 29 1234567) it_splits '375800123', %w(375 800 123) it_splits '3758001234', %w(375 800 1234) it_splits '3758001234567', %w(375 800 1234567) it_splits '37582012345678', %w(375 820 12345678) end describe 'Belgium' do it_splits '3235551212', ['32', '3', '555', '12', '12'] # Antwerpen it_splits '3250551212', ['32', '50', '55', '12', '12'] # Brugge it_splits '3225551212', ['32', '2', '555', '12', '12'] # Brussels it_splits '3295551914', ['32', '9', '555', '19', '14'] # Gent it_splits '3245551414', ['32', '4', '555', '14', '14'] # Liège it_splits '3216473200', ['32', '16', '47', '32', '00'] # Leuven it_splits '32475279584', ['32', '475', '27', '95', '84'] # mobile it_splits '32468279584', ['32', '468', '27', '95', '84'] # mobile (Telenet) it_splits '3270123123', ['32', '70', '123', '123'] # Bus Service? end describe 'Belize' do it_splits '5012051234', %w(501 205 1234) end describe 'Benin' do it_splits '22912345678', ['229', false, '1234', '5678'] end describe 'Bolivia' do it_splits '59122772266', %w(591 2 277 2266) end describe 'Botswana' do it_splits '26780123456', %w(267 80 123 456) it_splits '2672956789', %w(267 29 567 89) it_splits '2674634567', %w(267 463 4567) it_splits '2675812345', %w(267 58 123 45) it_splits '26776712345', %w(267 7 6712 345) it_splits '26781234567', %w(267 8 1234 567) end describe 'Brazil' do it_splits '551112341234', ['55', '11', '1234', '1234'] it_splits '5511981231234', ['55', '11', '98123', '1234'] # São Paulo's 9 digits mobile it_splits '552181231234', ['55', '21', '8123', '1234'] it_splits '5521981231234', ['55', '21', '98123', '1234'] # Rio de Janeiro's 9 digits mobile it_splits '551931311234', ['55', '19', '3131', '1234'] # Rio de Janeiro's 9 digits mobile it_splits '5519991311234', ['55', '19', '99131', '1234'] # Rio de Janeiro's 9 digits mobile context "special states with 9 in mobile" do %w{ 11 12 13 14 15 16 17 18 19 21 22 24 27 28 81 82 83 84 85 86 87 88 89 91 92 93 94 95 96 97 98 99}.each do |state_code| it_splits "55#{state_code}993051123", ['55', state_code, '99305', '1123'] end end context "special numbers" do it_splits '5508002221234', ['55', '0800', '222', '1234'] it_splits '5530032221', ['55', '3003', '2221'] it_splits '5540209999', ['55', '4020', '9999'] it_splits '5540048999', ['55', '4004', '8999'] end context "service numbers" do it_splits '55100', ['55', '100', ""] it_splits '55199', ['55', '199', ""] end end describe 'Cambodia' do it_splits '85512236142', ["855", "12", "236", "142"] # mobile (Mobitel) it_splits '855977100872', ["855", "97", "710", "0872"] # mobile (Metfone) it_splits '855234601183', ["855", "23", "460", "1183"] # Long fixed line (Phnom Penh) it_splits '85533234567', ["855", "33", "234", "567"] # Regular fixed line (Kampot) end describe 'Chile' do it_splits '5621234567', ['56', '2', '1234567'] # Santiago it_splits '5675123456', ['56', '75', '123456'] # Curico it_splits '56912345678', ['56', '9', '12345678'] # Mobile it_splits '56137123456', ['56', '137', '123', '456'] # Service end describe 'China' do it_splits '862112345678', ['86', '21', '1234', '5678'] # Shanghai it_splits '8675582193447', ['86', '755', '8219', '3447'] # Shenzhen end describe 'Colombia' do it_splits '5711234567', ['57', '1', '123', '4567'] it_splits '573101234567', ['57', '310', '123', '4567'] # mobile end describe 'Croatia' do it_splits '38521695900', %w( 385 21 695 900 ) # Landline it_splits '38514566666', %w( 385 1 4566 666 ) # Landline (Zagreb) it_splits '385918967509', %w( 385 91 896 7509 ) # Mobile end describe 'Cuba' do it_splits '5351231234', ['53', '5123', '1234'] # Mobile it_splits '5371234567', ['53', '7', '1234567'] # Havana it_splits '5342123456', ['53', '42', '123456'] # Villa Clara end describe 'Cyprus' do it_splits '35712322123456', ['357', '123', '22', '123456'] # Voicemail it_splits '35722123456', ['357', '22', '123456'] # Fixed it_splits '35791123456', ['357', '91', '123456'] # Mobile end describe 'Denmark' do it_splits '4532121212', ['45', false, '32', '12', '12', '12'] end describe 'Egypt' do it_splits '20212345678', ['20', '2', '12345678'] it_splits '20921234567', ['20', '92', '1234567'] it_splits '20951234567', ['20', '95', '1234567'] end describe 'Equatorial Guinea' do it_splits '240222201123', ['240', false, '222', '201', '123'] it_splits '240335201123', ['240', false, '335', '201', '123'] end describe 'Estonia' do it_splits '3723212345', ['372', '321', '2345'] # Landline it_splits '37251231234', ['372', '5123', '1234'] # Mobile it_splits '3728001234', ['372', '800', '1234'] # Freephone it_splits '37281231234', ['372', '8123', '1234'] # Mobile it_splits '37282231234', ['372', '8223', '1234'] # Mobile it_splits '37252212345', ['372', '5221', '2345'] # Mobile it_splits '3725221234', ['372', '5221', '234'] # Mobile it_splits '37270121234', ['372', '7012', '1234'] # Premium end describe 'Finland' do it_splits '3589123123', ['358', '9', '123', '123'] # Helsinki it_splits '3581912312', ['358', '19', '123', '12'] # Nylandia it_splits '3585012312', ['358', '50', '123', '12'] # Mobile it_splits '358600123', ['358', '600', '123'] # Service end describe 'France' do it_splits '33112345678', ['33', '1', '12','34','56','78'] # Paris it_splits '33812345678', ['33', '8', '12','34','56','78'] # Service number end describe 'Georgia' do it_splits '99522012345', %w(995 220 123 45) it_splits '995321234567', %w(995 32 123 4567) it_splits '995342123456', %w(995 342 123 456) it_splits '995596123456', %w(995 596 123 456) end describe 'Germany' do it_splits '493038625454', ['49', '30', '386', '25454'] # Berlin it_splits '4932221764542', ['49', '32', '221', '764542'] # Non-Geographical it_splits '4922137683323', ['49', '221', '376', '83323'] # Cologne it_splits '497614767676', ['49', '761', '476', '7676'] # Freiburg im Breisgau it_splits '4921535100', ['49', '2153', '510', '0'] # Nettetal-Lobberich it_splits '493434144602', ['49', '34341', '446', '02'] # Geithain it_splits '491805878323', ['49', '180', '587', '8323'] # Service number it_splits '491815878323', ['49', '181', '587', '8323'] # Service number it_splits '498001234567', ['49', '800', '123', '4567'] # Service number it_splits '49800222340010', ['49', '800', '222', '340010'] # Service number it_splits '4915111231234', ['49', '151', '1123', '1234'] # Mobile number it_splits '4915771231234', ['49', '157', '7123', '1234'] # Mobile number it_splits '491601234567', ['49', '160', '1234', '567'] # Mobile number it_splits '4916312345678', ['49', '163', '1234', '5678'] # Mobile number it_splits '4915211231234', ['49', '1521', '123', '1234'] # Mobile number end describe 'Ghana' do it_splits '233302123456', ['233', '30', '212', '3456'] # Mobile Vodafone, Accra end describe 'Gibraltar' do it_splits '35020012345', ['350', '200', '12345'] # Fixed it_splits '35021112345', ['350', '211', '12345'] # Fixed it_splits '35022212345', ['350', '222', '12345'] # Fixed it_splits '35054123456', ['350', '54', '123456'] # Mobile it_splits '35056123456', ['350', '56', '123456'] # Mobile it_splits '35057123456', ['350', '57', '123456'] # Mobile it_splits '35058123456', ['350', '58', '123456'] # Mobile it_splits '35060123456', ['350', '60', '123456'] # Mobile it_splits '3508012', ['350', '8012', '' ] # Freephone end describe 'Greece' do it_splits '302142345678', %w(30 21 4234 5678) it_splits '302442345678', %w(30 24 4234 5678) it_splits '305034571234', %w(30 50 3457 1234) it_splits '306901234567', %w(30 690 123 4567) it_splits '307001234567', %w(30 70 0123 4567) it_splits '308001001234', %w(30 800 100 1234) it_splits '308011001234', %w(30 801 100 1234) it_splits '308071001234', %w(30 807 100 1234) it_splits '308961001234', %w(30 896 100 1234) it_splits '309011234565', %w(30 901 123 4565) it_splits '309091234565', %w(30 909 123 4565) end describe 'Haiti' do it_splits '50922121234', ['509', '22', '12', '1234'] end describe 'Hong Kong' do it_splits '85212341234', ['852', false, '1234', '1234'] # end describe 'Hungary' do it_splits'3612345678', ['36', '1', '234', '5678'] it_splits'3622123456', ['36', '22', '123', '456'] end describe 'Iceland' do it_splits '354112', ['354', false, '112'] # Emergency TODO it_splits '3544211234', ['354', false, '421', '1234'] # Keflavík it_splits '3544621234', ['354', false, '462', '1234'] # Akureyri it_splits '3545511234', ['354', false, '551', '1234'] # Reykjavík end describe 'Indonesia' do it_splits '6242323032', ["62", "4", "2323", "032"] it_splits '6285220119289', ['62', '852', '2011', '9289'] it_splits '62217815263', %w(62 21 781 5263) it_splits '6213123', %w(62 13 123) it_splits '6213123456', %w(62 13 123 456) it_splits '6217412', %w(62 174 12) it_splits '6217412345', %w(62 174 12 345) it_splits '6217712', %w(62 177 12) it_splits '6217712123456', %w(62 177 1212 3456) it_splits '62178123', %w(62 178 123) it_splits '6217812345', %w(62 178 123 45) it_splits '622112345', %w(62 21 123 45) it_splits '622112345567', %w(62 21 1234 5567) it_splits '622212345', %w(62 22 123 45) it_splits '62221234567', %w(62 22 123 4567) it_splits '624311234', %w(62 4 311 234) it_splits '62431123456', %w(62 4 3112 3456) it_splits '6262212345', %w(62 6 221 2345) it_splits '62622123456', %w(62 6 2212 3456) it_splits '6270123456', %w(62 70 123 456) it_splits '6271123456', %w(62 71 123 456) it_splits '62711234567', %w(62 71 123 4567) it_splits '62810123456', %w(62 810 123 456) it_splits '6281012345678', %w(62 810 1234 5678) it_splits '628151234567', %w(62 815 123 4567) it_splits '62820123456', %w(62 820 123 456) it_splits '628231234567', %w(62 823 123 4567) it_splits '6282312345678', %w(62 823 1234 5678) it_splits '6287012345', %w(62 870 123 45) it_splits '62877123456', %w(62 877 123 456) it_splits '62881123456', %w(62 881 123 456) it_splits '6288112345656', %w(62 881 1234 5656) it_splits '6291234567', %w(62 9 1234 567) it_splits '629123456789', %w(62 9 123 456 789) end describe 'India' do it_splits '919911182111', ['91', '99', '111', '82', '111'] # mobile it_splits '912212345678', ['91', '22', '123', '45', '678'] # New Delhi it_splits '911411234567', ['91', '141', '123', '45', '67'] # Jaipur it_splits '913525123456', ['91', '3525', '123', '456'] # DALKHOLA it_splits '914433993939', ['91', '44', '339', '93', '939'] # end describe 'Iran' do it_splits '982112341234', ['98', '21', '1234', '1234'] # Teheran it_splits '989191231234', ['98', '919', '123', '1234'] # Example Cell Phone end describe 'Ireland' do it_splits '35311234567', ['353', '1', '123', '4567'] # Dublin, 7 digit subscriber # it_splits '353539233333', ['353', '53', '923', '3333'] # Wexford, 7 digit subscriber it_splits '3532212345', ['353', '22', '12345'] # Mallow, 5 digit subscriber # it_splits '35345123456', ['353', '45', '123456'] # Naas, 6 digit subscriber # it_splits '353801234567', ['353', '80', '123', '4567'] # Mobile it_splits '353761234567', ['353', '76', '123', '4567'] # VoIP it_splits '353800123456', ['353', '800', '123456'] # Freefone it_splits '353000123456', ['353', '000', '123456'] # Default fixed 3 split for unrecognized end describe 'Israel (972)' do it_splits '972100', ['972', '1', '00'] # Police it_splits '97221231234', ['972', '2', '123', '1234'] # Jerusalem Area it_splits '97282411234', ['972', '8', '241', '1234'] # Gaza Strip (Palestine) it_splits '97291231234', ['972', '9', '123', '1234'] # Sharon Area it_splits '972501231234', ['972', '50', '123', '1234'] # Mobile (Pelephone) it_splits '972591231234', ['972', '59', '123', '1234'] # Mobile Jawwal (Palestine) it_splits '972771231234', ['972', '77', '123', '1234'] # Cable Phone Services it_splits '9721700123123', ['972', '1', '700', '123', '123'] # Cable Phone Services end describe 'Israel (970)' do it_splits '97021231234', ['970', '2', '123', '1234'] # Jerusalem Area it_splits '97082411234', ['970', '8', '241', '1234'] # Gaza Strip (Palestine) it_splits '97091231234', ['970', '9', '123', '1234'] # Sharon Area it_splits '970501231234', ['970', '50', '123', '1234'] # Mobile (Pelephone) it_splits '970591231234', ['970', '59', '123', '1234'] # Mobile Jawwal (Palestine) it_splits '970771231234', ['970', '77', '123', '1234'] # Cable Phone Services it_splits '9701700123123', ['970', '1', '700', '123', '123'] # Cable Phone Services end describe 'Italy' do it_splits '39348695281', ['39', '348', '695', '281'] # Mobile (6-digit subscriber no. - rare, but still used) it_splits '393486952812', ['39', '348', '695', '2812'] # Mobile (7-digit subscriber no. - common) it_splits '3934869528123',['39', '348', '695', '2812', '3'] # Mobile (8-digit subscriber no - new) it_splits '393357210488', ['39', '335', '721', '0488'] # Mobile it_splits '393248644272', ['39', '324', '864', '4272'] # Mobile it_splits '390612341234', ['39', '06', '1234', '1234'] # Roma it_splits '390288838883', ['39', '02', '8883', '8883'] # Milano it_splits '390141595661', ['39', '0141', '595', '661'] # Asti it_splits '3903123391', ['39', '031', '23391'] # Como it_splits '390909709511', ['39', '090', '9709511'] # Barcellona it_splits '390471811353', ['39', '0471', '811', '353'] # Bolzano end describe 'Japan' do it_splits '81312345678', %w(81 3 1234 5678) # Tokyo it_splits '81612345678', %w(81 6 1234 5678) # Osaka it_splits '81120123456', %w(81 120 123 456) # Freephone it_splits '81111234567', %w(81 11 123 4567) it_splits '81123123456', %w(81 123 12 3456) it_splits '81126712345', %w(81 1267 1 2345) it_splits '812012345678', %w(81 20 1234 5678) # Pager(Calling Party Pay) it_splits '815012345678', %w(81 50 1234 5678) # IP Telephone it_splits '816012345678', %w(81 60 1234 5678) # UPT it_splits '817012345678', %w(81 70 1234 5678) # PHS it_splits '818012345678', %w(81 80 1234 5678) # Cellular it_splits '819012345678', %w(81 90 1234 5678) # Cellular end describe 'Kenya' do it_splits '254201234567', ['254', '20', '1234567'] # Nairobi it_splits '254111234567', ['254', '11', '1234567'] # Mombasa it_splits '254723100220', ['254', '723', '100220'] # Mombasa end describe 'Kyrgyzstan' do it_splits '996312212345', %w(996 312 212 345) it_splits '996315212345', %w(996 315 212 345) it_splits '996313121234', %w(996 3131 212 34) it_splits '996394621234', %w(996 3946 212 34) it_splits '996501234567', %w(996 50 123 4567) it_splits '996521234567', %w(996 52 123 4567) it_splits '996581234567', %w(996 58 123 4567) it_splits '996800123456', %w(996 800 123 456) end describe 'Lithuania' do it_splits '37070012123', ['370', '700', '12', '123'] # Service it_splits '37061212123', ['370', '612', '12', '123'] # Mobile it_splits '37051231212', ['370', '5', '123', '12', '12'] # Vilnius it_splits '37037121212', ['370', '37', '12', '12', '12'] # Kaunas it_splits '37044011212', ['370', '440', '1', '12', '12'] # Skuodas end describe 'Luxembourg' do it_splits '352222809', ['352', '22', '28', '09'] it_splits '35226222809', ['352', '26', '22', '28', '09'] it_splits '352621123456', ['352', '621', '123', '456'] it_splits '3524123456', ['352', '4', '12', '34', '56'] it_splits '352602112345678', ['352', '6021', '12', '34', '56', '78'] it_splits '352370431', ['352', '37', '04', '31'] it_splits '35227855', ['352', '27', '85', '5'] end describe 'Malaysia' do it_splits '6082123456', ['60', '82', '123456'] # Kuching it_splits '60312345678', ['60', '3', '12345678'] # Kuala Lumpur it_splits '60212345678', ['60', '2', '12345678'] # Singapore it_splits '60111231234', ['60', '11', '123', '1234'] # Mobile it_splits '601112312345', ['60', '11', '123', '12345'] # Mobile it_splits '60800121234', ['60', '800', '12', '1234'] # Freephone # it_splits '60112', ['60', '112'] # Service end describe 'Malta' do it_splits '35621231234', ['356', '2123', '1234'] # Fixed it_splits '35677123456', ['356', '77', '123456'] # Mobile it_splits '35698123456', ['356', '98', '123456'] # Mobile it_splits '35651231234', ['356', '5123', '1234'] # Voice Mail end describe 'Mexico' do it_splits '525512121212', ['52', '55', '1212', '1212'] # Mexico City it_splits '5215512121212', ['52', '1', '55', '1212', '1212'] # Mexico City cell phone from abroad it_splits '526641231212', ['52', '664', '123', '1212'] # Tijuana it_splits '5216641231212', ['52', '1', '664', '123', '1212'] # Tijuana cell phone from abroad it_splits '520446641231212', ['52', '044', '664', '123', '1212'] # Tijuana cell phone local from landline end describe 'Monaco' do it_splits '37741123456', ['377', '41', '12', '34', '56'] # Mobile it_splits '377612345678', ['377', '6', '12', '34', '56', '78'] # Mobile end describe 'Montenegro' do it_splits '38280123456', %w(382 80 123 456) it_splits '3822012345', %w(382 20 123 45) it_splits '38220123456', %w(382 20 123 456) it_splits '38232123456', %w(382 32 123 456) it_splits '38278103456', %w(382 78 103 456) it_splits '38263123', %w(382 63 123) it_splits '382631234567890', %w(382 63 123 456 7890) it_splits '38277103456', %w(382 77 103 456) it_splits '38294103456', %w(382 94 103 456) it_splits '38288103456', %w(382 88 103 456) it_splits '3826812', %w(382 68 12) it_splits '382681212345678', %w(382 68 12 1234 5678) it_splits '38270123', %w(382 70 123) it_splits '382701234567890', %w(382 70 123 456 7890) end describe 'Morocco' do it_splits '212537718685', ['212', '53', '7718', '685'] it_splits '212612345678', ['212', '6', '12', '34', '56', '78'] end describe 'The Netherlands' do it_splits '31612345678', ['31', '6', '12', '34', '56', '78'] # mobile it_splits '31201234567', ['31', '20', '123', '4567'] it_splits '31222123456', ['31', '222', '123', '456'] end describe 'Norway' do it_splits '4721234567', ['47',false,'21','23','45','67'] it_splits '4731234567', ['47',false,'31','23','45','67'] it_splits '4741234567', ['47',false,'412','34','567'] it_splits '4751234567', ['47',false,'51','23','45','67'] it_splits '4761234567', ['47',false,'61','23','45','67'] it_splits '4771234567', ['47',false,'71','23','45','67'] it_splits '4781234567', ['47',false,'812','34','567'] it_splits '4791234567', ['47',false,'912','34','567'] end describe 'Oman' do it_splits '96824423123', %w(968 24 423 123) it_splits '96825423123', %w(968 25 423 123) end describe 'Pakistan' do it_splits '922112345678', %w(92 21 1234 5678) it_splits '92221234567', %w(92 22 1234 567) it_splits '92232123456', %w(92 232 123 456) it_splits '923012345678', %w(92 30 1234 5678) end describe 'Paraguay (Republic of)' do it_splits '59521123456', %w(595 21 123 456) it_splits '595211234567', %w(595 21 123 4567) it_splits '595345123456', %w(595 345 123 456) it_splits '595961611234', %w(595 96 161 1234) end describe 'Peru' do it_splits '51112341234', ['51', '1', '1234', '1234'] # Lima it_splits '51912341234', ['51', '9', '1234', '1234'] # mobile it_splits '51841234123', ['51', '84', '1234', '123'] # Cuzco, best effort end describe 'Philippines' do it_splits '6321234567', ['63', '2', '1234567'] it_splits '6321234567890', ['63', '2', '1234567890'] it_splits '632123456789012', ['63', '2', '123456789012'] it_splits '639121234567', ['63', '912', '1234567'] it_splits '63881234567', ['63', '88', '1234567'] end describe 'Poland' do it_splits '48123456789', ['48', '12', '345', '67', '89'] # Landline it_splits '48501123456', ['48', '501', '123', '456'] # Mobile it_splits '48800123456', ['48', '800', '123', '456'] # Free it_splits '48801123456', ['48', '801', '123', '456'] # Shared cost it_splits '48701123456', ['48', '701', '123', '456'] # Premium end describe 'Portugal' do it_splits '351211231234', ['351', '21', '123', '1234'] # Lisboa it_splits '351241123123', ['351', '241', '123', '123'] # Abrantes it_splits '351931231234', ['351', '93', '123', '1234'] # mobile end describe 'Qatar' do it_splits '9741245123456', %w(974 1245 123 456) it_splits '9742613456', %w(974 26 134 56) it_splits '97433123456', %w(974 33 123 456) it_splits '97444412456', %w(974 44 412 456) it_splits '9748001234', %w(974 800 12 34) it_splits '9749001234', %w(974 900 12 34) it_splits '97492123', %w(974 92 123) it_splits '97497123', %w(974 97 123) end describe 'Romania' do it_splits '40211231234', ['40', '21', '123', '1234'] # Bucureşti it_splits '40721231234', ['40', '72', '123', '1234'] # mobile it_splits '40791231234', ['40', '79', '123', '1234'] # mobile it_splits '40249123123', ['40', '249', '123', '123'] # Olt end describe 'Russia' do it_splits '78122345678', ['7', '812', '234', '56', '78'] # Russia 3-digit it_splits '74012771077', ['7', '4012', '77', '10', '77'] # Russia 4-digit it_splits '78402411212', ['7', '84024', '1', '12', '12'] # Russia 5-digit it_splits '79296119119', ['7', '929', '611', '91', '19'] # Russia 3-digit, Megafon Mobile. it_splits '7840121212', ['7', '840', '12', '1212'] # Abhasia it_splits '7799121212', ['7', '799', '12', '1212'] # Kazachstan it_splits '7995344121212', ['7','995344','12','1212'] # South Osetia it_splits '7209175276', ['7', '209', '17', '5276'] # Fantasy number end describe 'Rwanda' do it_splits '250781234567', ['250', '78', '1234567'] # mobile it_splits '250721234567', ['250', '72', '1234567'] # mobile it_splits '250731234567', ['250', '73', '1234567'] # mobile it_splits '250251234567', ['250', '25', '1234567'] # fixed it_splits '25006123456', ['250', '06', '123456'] # fixed end describe 'Sao Tome and Principe' do it_splits '2392220012', %w(239 2 220 012) it_splits '2399920012', %w(239 9 920 012) end describe 'South Korea' do it_splits '82212345678', ['82', '2', '1234', '5678'] # Seoul it_splits '825112345678', ['82', '51', '1234', '5678'] # Busan it_splits '821027975588', ['82', '10', '2797', '5588'] # mobile it_splits '821087971234', ['82', '10', '8797', '1234'] # mobile end describe 'Serbia' do it_splits '38163512529', ['381', '63', '512', '529'] end describe 'South Sudan' do it_splits '211123212345', ['211', '123', '212', '345'] it_splits '211973212345', ['211', '973', '212', '345'] end describe 'Sudan' do it_splits '249187171100', ['249', '18', '717', '1100'] end describe 'Thailand' do it_splits '6621231234', ['66', '2', '123', '1234'] # Bangkok it_splits '6636123123', ['66', '36', '123', '123'] # Lop Buri it_splits '66851234567', ['66', '851', '234', '567'] # Lop Buri it_splits '66921234567', ['66', '921', '234', '567'] # mobile end describe 'Tunesia' do it_splits '21611231234', ['216', '1', '123', '1234'] # Ariana it_splits '21621231234', ['216', '2', '123', '1234'] # Bizerte end describe 'Salvador (El)' do it_splits '50321121234', ['503', '2112', '1234'] # Fixed number it_splits '50361121234', ['503', '6112', '1234'] # Mobile number end describe 'Singapore' do it_splits '6561231234', ['65', false, '6123', '1234'] # Fixed line end describe 'Slovakia' do it_splits '421912123456', ['421', '912', '123456'] # Mobile it_splits '421212345678', ['421', '2', '12345678'] # Bratislava it_splits '421371234567', ['421', '37', '1234567'] # Nitra / Other end describe 'Slovenia' do it_splits '38651234567', ['386', '51', '234', '567'] # Mobile it_splits '38611234567', ['386', '1', '123', '4567'] # LJUBLJANA end describe 'Spain' do it_splits '34600123456', ['34', '600', '123', '456'] # Mobile it_splits '34900123456', ['34', '900', '123', '456'] # Special it_splits '34931234567', ['34', '93', '123', '45', '67'] # Landline large regions it_splits '34975123456', ['34', '975', '12', '34', '56'] # Landline it_splits '34123456789', ['34', '123', '456', '789'] # Default end describe 'Sri Lanka' do it_splits '94711231212', ['94', '71', '123', '12', '12'] # Mobile end describe 'Sweden' do it_splits '46812345678', ['46', '8', '123', '45', '678'] # Stockholm it_splits '46111234567', ['46', '11', '123', '45', '67'] it_splits '46721234567', ['46', '72', '123', '45', '67'] # mobile it_splits '46125123456', ['46', '125', '123', '456'] end describe 'Switzerland' do it_splits '41443643532', ['41', '44', '364', '35', '32'] # Zurich (usually) it_splits '41800334455', ['41', '800', '334', '455'] # Service number end describe 'Tanzania' do it_splits '255221231234', ['255', '22', '123', '1234'] # Dar Es Salaam it_splits '255651231234', ['255', '65', '123', '1234'] # TIGO it_splits '255861123123', ['255', '861', '123', '123'] # Special Rates end describe 'Turkey' do it_splits '903121234567', ['90', '312', '123', '4567'] # Ankara end describe 'Uganda' do it_splits '256414123456', ['256', '41', '4123456'] # Kampania it_splits '256464441234', ['256', '464', '441234'] # Mubende end describe 'The UK' do it_splits '442075671113', ['44', '20', '7567', '1113'] # [2+8] London it_splits '442920229901', ['44', '29', '2022', '9901'] # [2+8] Cardiff it_splits '441134770011', ['44', '113', '477', '0011'] # [3+7] Leeds it_splits '441412770022', ['44', '141', '277', '0022'] # [3+7] Glasgow it_splits '441204500532', ['44', '1204', '500532'] # [4+6] Bolton it_splits '44120462532', ['44', '1204', '62532'] # [4+5] Bolton it_splits '441333247700', ['44', '1333', '247700'] # [4+6] Leven (Fife) it_splits '441382229845', ['44', '1382', '229845'] # [4+6] Dundee it_splits '441420700378', ['44', '1420', '700378'] # [4+6] Alton it_splits '44142080378', ['44', '1420', '80378'] # [4+5] Alton it_splits '441475724688', ['44', '1475', '724688'] # [4+6] Greenock it_splits '441539248756', ['44', '1539', '248756'] # [4+6] Kendal (Mixed area) it_splits '441539648788', ['44', '15396', '48788'] # [5+5] Sedbergh (Mixed area) it_splits '441652757248', ['44', '1652', '757248'] # [4+6] Brigg it_splits '441664333456', ['44', '1664', '333456'] # [4+6] Melton Mowbray it_splits '441697222555', ['44', '1697', '222555'] # [4+6] Brampton (Mixed area) it_splits '441697388555', ['44', '16973', '88555'] # [5+5] Wigton (Mixed area) it_splits '441697433777', ['44', '16974', '33777'] # [5+5] Raughton Head (Mixed area) it_splits '44169772333', ['44', '16977', '2333'] # [5+4] Brampton (Mixed area) it_splits '441697744888', ['44', '16977', '44888'] # [5+5] Brampton (Mixed area) it_splits '441757850526', ['44', '1757', '850526'] # [4+6] Selby it_splits '441890234567', ['44', '1890', '234567'] # [4+6] Coldstream (ELNS area) it_splits '441890595378', ['44', '1890', '595378'] # [4+6] Ayton (ELNS area) it_splits '441931306526', ['44', '1931', '306526'] # [4+6] Shap it_splits '441946555777', ['44', '1946', '555777'] # [4+6] Whitehaven (Mixed area) it_splits '44194662888', ['44', '1946', '62888'] # [4+5] Whitehaven (Mixed area) it_splits '441946722444', ['44', '19467', '22444'] # [5+5] Gosforth (Mixed area) it_splits '441987705337', ['44', '1987', '705337'] # [4+6] Ebbsfleet it_splits '443005828323', ['44', '300', '582', '8323'] # Non-geographic (NTS) it_splits '443334253344', ['44', '333', '425', '3344'] # Non-geographic (NTS) it_splits '443437658834', ['44', '343', '765', '8834'] # Non-geographic (NTS) it_splits '443452273512', ['44', '345', '227', '3512'] # Non-geographic (NTS) it_splits '443707774444', ['44', '370', '777', '4444'] # Non-geographic (NTS) it_splits '443725247722', ['44', '372', '524', '7722'] # Non-geographic (NTS) it_splits '44500557788', ['44', '500', '557788'] # Freefone (500 + 6) it_splits '445575671113', ['44', '55', '7567', '1113'] # Corporate numbers it_splits '445644775533', ['44', '56', '4477', '5533'] # LIECS/VoIP it_splits '447020229901', ['44', '70', '2022', '9901'] # Personal numbers it_splits '447688554246', ['44', '76', '8855', '4246'] # Pager it_splits '447180605207', ['44', '7180', '605207'] # Mobile it_splits '447480605207', ['44', '7480', '605207'] # Mobile it_splits '447624605207', ['44', '7624', '605207'] # Mobile (Isle of Man) it_splits '447780605207', ['44', '7780', '605207'] # Mobile it_splits '447980605207', ['44', '7980', '605207'] # Mobile it_splits '44800557788', ['44', '800', '557788'] # Freefone (800 + 6) it_splits '448084682355', ['44', '808', '468', '2355'] # Freefone (808 + 7) it_splits '448005878323', ['44', '800', '587', '8323'] # Freefone (800 + 7), regression it_splits '448437777334', ['44', '843', '777', '7334'] # Non-geographic (NTS) it_splits '448457777334', ['44', '845', '777', '7334'] # Non-geographic (NTS) it_splits '448707777334', ['44', '870', '777', '7334'] # Non-geographic (NTS) it_splits '448727777334', ['44', '872', '777', '7334'] # Non-geographic (NTS) it_splits '449052463456', ['44', '905', '246', '3456'] # Non-geographic (PRS) it_splits '449122463456', ['44', '912', '246', '3456'] # Non-geographic (PRS) it_splits '449832463456', ['44', '983', '246', '3456'] # Non-geographic (SES) end describe 'US' do it_splits '15551115511', ['1', '555', '111', '5511'] end describe 'Venezuela' do it_splits '582121234567', ['58', '212', '1234567'] end describe 'Vietnam' do it_splits '8498123456', ['84', '98', '123456'] # Viettel Mobile it_splits '8499612345', ['84', '996', '12345'] # GTel it_splits '84412345678', ['84', '4', '1234', '5678'] # Hanoi end describe 'Zambia' do it_splits '260955123456', ['260', '955', '123456'] # mobile it_splits '260211123456', ['260', '211', '123456'] # fixed end describe 'New Zealand' do it_splits '6491234567', ['64', '9', '123', '4567'] end describe 'Bhutan (Kingdom of)' do it_splits '9759723642', %w(975 9 723 642) end describe 'Brunei Darussalam' do it_splits '6737932744', %w(673 7 932 744) end describe 'Burkina Faso' do it_splits '22667839323', ['226', false, '6783', '9323'] end describe 'Burundi' do it_splits '25712345678', ['257', false, '1234', '5678'] end describe 'Cameroon' do it_splits '23727659381', ['237', false, '2765', '9381'] end describe 'Cape Verde' do it_splits '2385494177', ['238', false, '549', '4177'] end describe 'Central African Republic' do it_splits '23612345678', ['236', false, '1234', '5678'] end describe 'Chad' do it_splits '23512345678', ['235', false, '1234', '5678'] end describe 'Comoros' do it_splits '2693901234', ['269', false, '3901', '234'] it_splits '2693401234', ['269', false, '3401', '234'] end describe 'Congo' do it_splits '242123456789', ['242', false, '1234', '56789'] end describe 'Cook Islands' do it_splits '68251475', ['682', false, '51', '475'] end describe 'Costa Rica' do it_splits '50622345678', %w(506 2 234 5678) end describe "Côte d'Ivoire" do it_splits '22507335518', ['225', '07', '33', '55', '18'] it_splits '22537335518', ['225', '37', '33', '55', '18'] end describe 'Democratic Republic of Timor-Leste' do it_splits '6701742945', ['670', false, '174', '2945'] end describe 'Democratic Republic of the Congo' do it_splits '24311995381', %w(243 1 199 5381) end describe 'Diego Garcia' do it_splits '2461234683', ['246', false, '123', '4683'] end describe 'Djibouti' do it_splits '25349828978', ['253', false, '4982', '8978'] end describe 'Ecuador' do it_splits '593445876756', %w(593 44 587 6756) end describe 'Eritrea' do it_splits '2916537192', %w(291 6 537 192) end describe 'Ethiopia' do it_splits '251721233486', %w(251 72 123 3486) end describe 'Falkland Islands (Malvinas)' do it_splits '50014963', ['500', false, '14', '963'] end describe 'Faroe Islands' do it_splits '298997986', ['298', false, '997', '986'] end describe 'Fiji (Republic of)' do it_splits '6798668123', ['679', false, '866', '8123'] end describe 'French Guiana (French Department of)' do it_splits '594594123456', %w(594 594 123 456) end describe "French Polynesia (Territoire français d'outre-mer)" do it_splits '68921988900', ['689', false, '21', '98', '89', '00'] end describe 'Gabonese Republic' do it_splits '2411834375', ['241', '1', '834', '375'] end describe 'Gambia' do it_splits '2206683355', ['220', false, '668', '3355'] end describe 'Greenland' do it_splits '299314185', ['299', '31', '4185'] it_splits '299691123', ['299', '691', '123'] end describe 'Guadeloupe (French Department of)' do it_splits '590590456789', %w(590 590 45 67 89) end describe 'Guatemala (Republic of)' do it_splits '50219123456789', ['502', '19', '123', '456', '789'] it_splits '50221234567', ['502', '2', '123', '4567'] end describe 'Guinea' do it_splits '22430311234', ['224', '3031', '12', '34'] it_splits '224662123456', ['224', '662', '12', '34', '56'] end describe 'Guinea-Bissau' do it_splits '2453837652', ['245', false, '383', '7652'] end describe 'Guyana' do it_splits '5922631234', %w(592 263 1234) end describe 'Honduras (Republic of)' do it_splits '50412961637', %w(504 12 961 637) end describe 'Iraq' do it_splits '96411234567', %w(964 1 123 4567) it_splits '96421113456', %w(964 21 113 456) it_splits '9647112345678', %w(964 71 1234 5678) end describe 'Jordan (Hashemite Kingdom of)' do it_splits '96280012345', %w(962 800 123 45) it_splits '96226201234', %w(962 2 620 1234) it_splits '962712345678', %w(962 7 1234 5678) it_splits '962746612345', %w(962 7 4661 2345) it_splits '96290012345', %w(962 900 123 45) it_splits '96285123456', %w(962 85 123 456) it_splits '96270123456', %w(962 70 123 456) it_splits '96262501456', %w(962 6250 1456) it_splits '96287901456', %w(962 8790 1456) end describe 'Kiribati (Republic of)' do it_splits '68634814', ['686', false, '34', '814'] end describe "Democratic People's Republic of Korea" do it_splits '850212345', %w(850 2 123 45) it_splits '8502123456789', %w(850 2 123 456 789) it_splits '85023812356', %w(850 2 381 2356) #it_splits '85028801123456781256', %w(850 2 8801 1234 5678 1256) it_splits '8501911234567', %w(850 191 123 4567) end describe 'Kuwait (State of)' do it_splits '96523456789', ['965', false, '2345', '6789'] it_splits '9651812345', ['965', false, '181', '2345'] end describe "Lao People's Democratic Republic" do it_splits '85697831195', %w(856 97 831 195) end describe 'Latvia' do it_splits '37180123456', %w(371 801 234 56) it_splits '37163723456', %w(371 637 234 56) it_splits '37129412345', %w(371 294 123 45) end describe 'Lebanon' do it_splits '9611123456', %w(961 1 123 456) it_splits '9614123456', %w(961 4 123 456) it_splits '9613123456', %w(961 3 123 456) it_splits '96170123456', %w(961 70 123 456) it_splits '96190123456', %w(961 90 123 456) it_splits '96181123456', %w(961 81 123 456) end describe 'Lesotho' do it_splits '26623592495', ['266', false, '2359', '2495'] end describe 'Liberia' do it_splits '23121234567', ['231', false, '2123', '4567'] it_splits '2314123456', ['231', false, '4123', '456'] it_splits '231771234567', ['231', false, '77', '123', '4567'] end describe 'Libya' do it_splits '21820512345', %w(218 205 123 45) it_splits '21822123456', %w(218 22 123 456) it_splits '218211234456', %w(218 21 1234 456) it_splits '218911234456', %w(218 91 1234 456) end describe 'Madagascar' do it_splits '26120012345678', ['261', false, '20', '012', '345', '678'] it_splits '261201243456', ['261', false, *%w(20 124 3456)] it_splits '261512345678', ['261', false, *%w(512 345 678)] end describe 'Malawi' do it_splits '2651725123', ['265', false, '1725', '123'] it_splits '265213456789',[ '265', false, '213', '456', '789'] it_splits '2659123456', ['265', false, '9123', '456'] it_splits '265991123456', ['265', false, '991', '123', '456'] end describe 'Maldives (Republic of)' do it_splits '9606568279', ['960', '656', '8279'] end describe 'Mali' do it_splits '22379249349', ['223', false, '7924', '9349'] end describe 'Marshall Islands (Republic of the)' do it_splits '6924226536', ['692', false, '422', '6536'] end describe 'Martinique (French Department of)' do it_splits '596596123456', %w(596 596 12 34 56) end describe 'Mauritania' do it_splits '22212345678', ['222', false, '1234', '5678'] end describe 'Mauritius' do it_splits '2309518919', ['230', false, '951', '8919'] end describe 'Micronesia (Federated States of)' do it_splits '6911991754', ['691', false, '199', '1754'] end describe 'Moldova' do it_splits '37380012345', %w(373 800 123 45) it_splits '37322123345', %w(373 22 123 345) it_splits '37324112345', %w(373 241 123 45) it_splits '37360512345', %w(373 605 123 45) it_splits '37380312345', %w(373 803 123 45) end describe 'Mongolia' do it_splits '9761112345', %w(976 11 123 45) it_splits '9761211234', %w(976 121 12 34) it_splits '97612112345', %w(976 121 12 345) it_splits '97670123456', %w(976 70 123 456) it_splits '97675123456', %w(976 75 123 456) it_splits '97688123456', %w(976 88 123 456) it_splits '97650123456', %w(976 50 123 456) end describe 'Mozambique' do it_splits '258600123456', %w(258 600 123 456) it_splits '25825112345', %w(258 251 123 45) it_splits '258821234456', %w(258 82 1234 456) it_splits '258712344567', %w(258 7 1234 4567) end describe 'Namibia' do it_splits '264675161324', %w(264 6751 613 24) it_splits '26467175890', %w(264 67 175 890) it_splits '26463088612345', %w(264 63 088 612 345) it_splits '264851234567', %w(264 85 1234 567) end describe 'Nauru (Republic of)' do it_splits '6741288739', ['674', false, '128', '8739'] end describe 'Nepal' do it_splits '97714345678', %w(977 1 434 5678) it_splits '97710123456', %w(977 10 123 456) it_splits '9779812345678', %w(977 98 1234 5678) end describe "New Caledonia (Territoire français d'outre-mer)" do it_splits '687747184', ['687', false, '747', '184'] end describe 'Nicaragua' do it_splits '50512345678', ['505', '12', '345', '678'] end describe 'Niger' do it_splits '22712345678', ['227', false, '1234', '5678'] end describe 'Nigeria' do it_splits '23411231234', %w(234 1 123 1234) # Lagos # mobile numbers it_splits '2347007661234', %w(234 700 766 1234) it_splits '2347017661234', %w(234 701 766 1234) it_splits '2347027661234', %w(234 702 766 1234) it_splits '2347037661234', %w(234 703 766 1234) it_splits '2347047661234', %w(234 704 766 1234) it_splits '2347057661234', %w(234 705 766 1234) it_splits '2347067661234', %w(234 706 766 1234) it_splits '2347077661234', %w(234 707 766 1234) it_splits '2347087661234', %w(234 708 766 1234) it_splits '2347097661234', %w(234 709 766 1234) it_splits '2348007661234', %w(234 800 766 1234) it_splits '2348017661234', %w(234 801 766 1234) it_splits '2348027661234', %w(234 802 766 1234) it_splits '2348037661234', %w(234 803 766 1234) it_splits '2348047661234', %w(234 804 766 1234) it_splits '2348057661234', %w(234 805 766 1234) it_splits '2348067661234', %w(234 806 766 1234) it_splits '2348077661234', %w(234 807 766 1234) it_splits '2348087661234', %w(234 808 766 1234) it_splits '2348097661234', %w(234 809 766 1234) it_splits '2349007661234', %w(234 900 766 1234) it_splits '2349017661234', %w(234 901 766 1234) it_splits '2349027661234', %w(234 902 766 1234) it_splits '2349037661234', %w(234 903 766 1234) it_splits '2349047661234', %w(234 904 766 1234) it_splits '2349057661234', %w(234 905 766 1234) it_splits '2349067661234', %w(234 906 766 1234) it_splits '2349077661234', %w(234 907 766 1234) it_splits '2349087661234', %w(234 908 766 1234) it_splits '2349097661234', %w(234 909 766 1234) it_splits '2348107661234', %w(234 810 766 1234) it_splits '2348117661234', %w(234 811 766 1234) it_splits '2348127661234', %w(234 812 766 1234) it_splits '2348137661234', %w(234 813 766 1234) it_splits '2348147661234', %w(234 814 766 1234) it_splits '2348157661234', %w(234 815 766 1234) it_splits '2348167661234', %w(234 816 766 1234) it_splits '2348177661234', %w(234 817 766 1234) it_splits '2348187661234', %w(234 818 766 1234) it_splits '2348197661234', %w(234 819 766 1234) end describe 'Niue' do it_splits '6833651', ['683', false, '3651'] end describe 'Palau (Republic of)' do it_splits '6804873653', ['680', false, '487', '3653'] end describe 'Panama (Republic of)' do it_splits '5078001234', %w(507 800 1234) it_splits '50761234567', %w(507 6 123 4567) it_splits '5072123456', %w(507 2 123 456) end describe 'Papua New Guinea' do it_splits '6753123567', %w(675 3 123 567) it_splits '6751801234', %w(675 180 1234) it_splits '67580123456', %w(675 80 123 456) it_splits '67591123456', %w(675 91 123 456) it_splits '6751612345', %w(675 16 123 45) it_splits '67518412345678', %w(675 184 1234 5678) it_splits '67517012', %w(675 170 12) it_splits '6751891', %w(675 189 1) it_splits '6752701234', %w(675 270 1234) it_splits '6752751234', %w(675 275 1234) it_splits '67527912', %w(675 279 12) it_splits '67511512345678', %w(675 115 1234 5678) end describe 'Reunion / Mayotte (new)' do it_splits '262594399265', ['262', '594', '39', '92', '65'] end describe 'Saint Helena' do it_splits '2903614', ['290', false, '3614'] end describe 'Saint Pierre and Miquelon (Collectivité territoriale de la République française)' do it_splits '508418826', ['508', false, '418', '826'] end describe 'Samoa (Independent State of)' do it_splits '685800123', ['685', false, '800', '123'] it_splits '68561123', ['685', false, '61', '123'] it_splits '6857212345', ['685', false, '721', '2345'] it_splits '685830123', ['685', false, '830', '123'] it_splits '685601234', ['685', false, '601', '234'] it_splits '6858412345', ['685', false, '841', '2345'] end describe 'San Marino' do it_splits '378800123', ['378', false, '800', '123'] it_splits '3788001234567', ['378', false, '800', '123', '4567'] it_splits '378012345', ['378', false, '012', '345'] it_splits '3780123456789', ['378', false, '012', '345', '6789'] it_splits '378512345', ['378', false, '512', '345'] it_splits '3785123456789', ['378', false, '512', '345', '6789'] end describe 'Saudi Arabia (Kingdom of)' do it_splits '9660208528423', %w(966 020 852 8423) it_splits '966506306201', %w(966 50 630 6201) end describe 'Senegal' do it_splits '221123456789', ['221', false, '1234', '56789'] end describe 'Serbia' do it_splits '38180012345', %w(381 800 123 45) it_splits '3811012345', %w(381 10 123 45) it_splits '38110123456', %w(381 10 123 456) it_splits '38111123456', %w(381 11 123 456) it_splits '381111234567', %w(381 11 123 4567) it_splits '381721234567', %w(381 72 123 4567) it_splits '38160123', %w(381 60 123) it_splits '381601234567', %w(381 60 123 4567) it_splits '38142123456', %w(381 42 123 456) it_splits '38191234567', %w(381 9 123 4567) it_splits '38160123', %w(381 60 123) it_splits '381601234567890', %w(381 60 123 456 7890) it_splits '38170123456', %w(381 70 123 456) end describe 'Sierra Leone' do it_splits '23264629769', %w(232 64 629 769) end describe 'Solomon Islands' do it_splits '67754692', ['677', false, '54', '692'] it_splits '6777546921', ['677', false, '7546', '921'] end describe 'Somali Democratic Republic' do it_splits '252103412345', %w(252 1034 123 45) it_splits '2521313123', %w(252 1313 123) it_splits '2521601234', %w(252 160 12 34) it_splits '25250012345', %w(252 500 123 45) it_splits '252671234567', %w(252 67 1234 567) end describe 'Suriname (Republic of)' do it_splits '597958434', ['597', false, '958', '434'] it_splits '597212345', ['597', false, '212', '345'] it_splits '5976123456', ['597', false, '612', '3456'] end describe 'Swaziland' do it_splits '26822071234', ['268', false, '2207', '1234'] it_splits '2685501234', ['268', false, '550', '1234'] end describe 'Syrian Arab Republic' do it_splits '963111234567', %w(963 11 123 4567) it_splits '963311234567', %w(963 31 123 4567) it_splits '96315731234', %w(963 15 731 234) it_splits '963912345678', %w(963 9 1234 5678) end describe 'Taiwan' do it_splits '88618123456', %w(886 18 123 456) it_splits '8866121234567', %w(886 612 123 4567) it_splits '886212345678', %w(886 2 1234 5678) it_splits '88631234567', %w(886 3 123 4567) it_splits '88633123456', %w(886 33 123 456) it_splits '88682712345', %w(886 827 123 45) it_splits '8864121234', %w(886 412 1234) it_splits '88690123456', %w(886 90 123 456) it_splits '886901234567', %w(886 90 123 4567) it_splits '88694991345', %w(886 94 991 345) end describe 'Togolese Republic' do it_splits '22812345678', ['228', false, '1234', '5678'] end describe 'Tajikistan' do it_splits '992313012345', %w(992 3130 123 45) it_splits '992331700123', %w(992 331700 123) it_splits '992372123345', %w(992 372 123 345) it_splits '992505123456', %w(992 505 123 456) it_splits '992973123456', %w(992 973 123 456) it_splits '992474456123', %w(992 474 456 123) end describe 'Tokelau' do it_splits '6901371', %w(690 1 371) end describe 'Tonga (Kingdom of)' do it_splits '67620123', ['676', false, '20', '123'] it_splits '67684123', ['676', false, '84', '123'] it_splits '6767712345', ['676', false, '77', '123', '45'] it_splits '6768912345', ['676', false, '89', '123', '45'] end describe 'Tuvalu' do it_splits '68893741', ['688', false, '93741'] end describe 'Turkmenistan' do it_splits '99312456789', %w(993 12 456 789) it_splits '99313145678', %w(993 131 456 78) it_splits '99313924567', %w(993 1392 4567) it_splits '99361234567', %w(993 6 123 4567) end describe 'Ukraine' do it_splits '380800123456', %w(380 800 123 456) it_splits '380312123456', %w(380 312 123 456) it_splits '380320123456', %w(380 32 0123 456) it_splits '380325912345', %w(380 3259 123 45) it_splits '380326061234', %w(380 32606 1234) it_splits '380391234567', %w(380 39 123 45 67) it_splits '380501234567', %w(380 50 123 45 67) it_splits '380631234567', %w(380 63 123 45 67) it_splits '380661234567', %w(380 66 123 45 67) it_splits '380671234567', %w(380 67 123 45 67) it_splits '380681234567', %w(380 68 123 45 67) it_splits '380911234567', %w(380 91 123 45 67) it_splits '380921234567', %w(380 92 123 45 67) it_splits '380931234567', %w(380 93 123 45 67) it_splits '380941234567', %w(380 94 123 45 67) it_splits '380951234567', %w(380 95 123 45 67) it_splits '380961234567', %w(380 96 123 45 67) it_splits '380971234567', %w(380 97 123 45 67) it_splits '380981234567', %w(380 98 123 45 67) it_splits '380991234567', %w(380 99 123 45 67) end describe 'United Arab Emirates' do it_splits '97180012', %w(971 800 12) it_splits '971800123456789', %w(971 800 12 345 6789) it_splits '97121234567', %w(971 2 123 4567) it_splits '971506412345', %w(971 50 641 2345) it_splits '971600641234', %w(971 600 641 234) it_splits '971500641234', %w(971 500 641 234) it_splits '971200641234', %w(971 200 641 234) end describe 'Uruguay (Eastern Republic of)' do it_splits '59880012345', %w(598 800 123 45) it_splits '59820123456', %w(598 2 012 3456) it_splits '59821123456', %w(598 21 123 456) it_splits '59890912345', %w(598 909 123 45) it_splits '59893123456', %w(598 93 123 456) it_splits '59890812345', %w(598 908 123 45) it_splits '59880512345', %w(598 805 123 45) end describe 'Uzbekistan (Republic of)' do it_splits '998433527869', %w(998 43 352 7869) end describe 'Vanuatu (Republic of)' do it_splits '67889683', ['678', false, '89', '683'] end describe 'Yemen' do it_splits '9671234567', %w(967 1 234 567) it_splits '96712345678', %w(967 1 234 5678) it_splits '9677234567', %w(967 7 234 567) it_splits '967771234567', %w(967 77 123 4567) it_splits '967581234', %w(967 58 1234) end describe 'Zimbabwe' do it_splits '2632582123456', %w(263 2582 123 456) it_splits '2632582123', %w(263 2582 123) it_splits '263147123456', %w(263 147 123 456) it_splits '263147123', %w(263 147 123) it_splits '263270123456', %w(263 270 123 456) it_splits '26327012345', %w(263 270 123 45) it_splits '2638612354567', %w(263 86 1235 4567) # mobile numbers (see http://www.itu.int/dms_pub/itu-t/oth/02/02/T02020000E90002PDFE.pdf, Table 4, Page 25) %w(71 73 77 78).each do |prefix| number = "263#{prefix}2345678" it_splits number, ['263', prefix, '234', '5678'] end end end end
tpena/phony
spec/lib/phony/countries_spec.rb
Ruby
mit
56,003
var http = require("http"); var url = require("url"); var server; // Diese Funktion reagiert auf HTTP Requests, // hier wird also die Web Anwendung implementiert! var simpleHTTPResponder = function(req, res) { // Routing bedeutet, anhand der URL Adresse // unterschiedliche Funktionen zu steuern. // Dazu wird zunächst die URL Adresse benötigt var url_parts = url.parse(req.url, true); // Nun erfolgt die Fallunterscheidung, // hier anhand des URL Pfads if (url_parts.pathname == "/greetme") { // HTTP Header müssen gesetzt werden res.writeHead(200, { "Content-Type": "text/html" }); // Auch URL Query Parameter können abgefragt werden var query = url_parts.query; var name = "Anonymous"; if (query["name"] != undefined) { name = query["name"]; } // HTML im Script zu erzeugen ist mühselig... res.end("<html><head><title>Greetme</title></head><body><H1>Greetings " + name + "!</H1></body></html>"); // nun folgt der zweite Fall... } else { res.writeHead(404, { "Content-Type": "text/html" }); res.end( "<html><head><title>Error</title></head><body><H1>Only /greetme is implemented.</H1></body></html>" ); } } // Webserver erzeugen, an Endpunkt binden und starten server = http.createServer(simpleHTTPResponder); var port = process.argv[2]; server.listen(port);
MaximilianKucher/vs1Lab
Beispiele/nodejs_webserver/web.js
JavaScript
mit
1,328
package engine.menu.managers; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.util.List; import engine.dialogue.InteractionBox; import engine.gridobject.person.Player; import engine.images.ScaledImage; import engine.item.Weapon; import engine.menu.MenuInteractionMatrix; import engine.menu.nodes.WeaponInfoNode; public class WeaponManager extends MenuManager implements InteractionBox { private Player myPlayer; private MenuInteractionMatrix myMIM; private MenuManager myMenuManager; public WeaponManager(Player p, MenuManager mm, MenuInteractionMatrix mim) { super(p, null, mim); myPlayer = p; myMIM = mim; myMenuManager = mm; } @Override public void paintDisplay(Graphics2D g2d, int xSize, int ySize, int width, int height) { paintMenu(g2d, height, width); paintFeatureBox(g2d, "ImageFiles/PokemonBox.png", 17, 20, 300, 200); paintWeaponData(g2d); drawSelector(g2d, 198, 40, 280, 45, 44, myMIM); } @Override public void getNextText() { // TODO Auto-generated method stub } protected void paintFeatureBox(Graphics g2d, String imgPath, int x, int y, int width, int height) { Image img = new ScaledImage(width, height, imgPath).scaleImage(); g2d.drawImage(img, x, y, null); } protected void paintFeatureImage(Graphics g2d, Image feature, int x, int y) { g2d.drawImage(feature, x, y, null); } protected void paintFeatureName(Graphics g2d, String name, int x, int y) { g2d.drawString(name, x, y); } private void paintWeaponData(Graphics g2d) { List<Weapon> features = myPlayer.getWeaponList(); int emptySpace = 0; for (int i = 0; i < features.size(); i++) { if (i != 0) { emptySpace = 1; } else { emptySpace = 0; } Image scaledWeaponImage = features.get(i).getImage() .getScaledInstance(35, 35, Image.SCALE_SMOOTH); paintFeatureImage(g2d, scaledWeaponImage, 37, 45 + i * 40 + 5 * emptySpace); paintFeatureName(g2d, features.get(i).toString(), 80, 67 + i * 40 + 5 * emptySpace); } } public void createWeaponInfoNodes() { for (int i = 0; i < myPlayer.getWeaponList().size(); i++) { myMIM.setNode(new WeaponInfoNode(myPlayer, this, myMenuManager, i), 0, i); } } }
yomikaze/OOGASalad
src/engine/menu/managers/WeaponManager.java
Java
mit
2,233
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\BlockBundle\Tests\Block; use Sonata\BlockBundle\Block\BlockServiceManager; use Symfony\Component\DependencyInjection\ContainerInterface; class BlockServiceManagerTest extends \PHPUnit_Framework_TestCase { public function testGetBlockService() { $service = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface'); $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->once())->method('get')->will($this->returnValue($service)); $manager = new BlockServiceManager($container, true); $manager->add('test', 'test'); $block = $this->getMock('Sonata\BlockBundle\Model\BlockInterface'); $block->expects($this->any())->method('getType')->will($this->returnValue('test')); $this->assertInstanceOf(get_class($service), $manager->get($block)); } /** * @expectedException \RuntimeException */ public function testInvalidServiceType() { $service = $this->getMock('stdClass'); $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $container->expects($this->once())->method('get')->will($this->returnValue($service)); $manager = new BlockServiceManager($container, true); $manager->add('test', 'test'); $block = $this->getMock('Sonata\BlockBundle\Model\BlockInterface'); $block->expects($this->any())->method('getType')->will($this->returnValue('test')); $this->assertInstanceOf(get_class($service), $manager->get($block)); } /** * @expectedException \RuntimeException */ public function testGetBlockServiceException() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $manager = new BlockServiceManager($container, true); $block = $this->getMock('Sonata\BlockBundle\Model\BlockInterface'); $block->expects($this->any())->method('getType')->will($this->returnValue('fakse')); $manager->get($block); } public function testGetEmptyListFromInvalidContext() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $manager = new BlockServiceManager($container, true); $service = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface'); $manager->add('foo.bar', $service); $this->assertEmpty($manager->getServicesByContext('fake')); } public function testGetListFromValidContext() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $manager = new BlockServiceManager($container, true); $service = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface'); $manager->add('foo.bar', $service, array('fake')); $this->assertNotEmpty($manager->getServicesByContext('fake')); } public function testOrderServices() { $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); $manager = new BlockServiceManager($container, true); $serviceAbc = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface'); $serviceAbc->expects($this->any())->method('getName')->will($this->returnValue('GHI')); $manager->add('ghi', $serviceAbc); $serviceAbc = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface'); $serviceAbc->expects($this->any())->method('getName')->will($this->returnValue('ABC')); $manager->add('abc', $serviceAbc); $serviceAbc = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface'); $serviceAbc->expects($this->any())->method('getName')->will($this->returnValue('DEF')); $manager->add('def', $serviceAbc); $services = array_keys($manager->getServices()); $this->assertEquals('abc', $services[0], 'After order, the first service should be "ABC"'); $this->assertEquals('def', $services[1], 'After order, the second service should be "DEF"'); $this->assertEquals('ghi', $services[2], 'After order, the third service should be "GHI"'); } }
sonata-project/sandbox-build
vendor/sonata-project/block-bundle/Tests/Block/BlockServiceManagerTest.php
PHP
mit
4,478
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp), Shared] internal class UsingStatementHighlighter : AbstractKeywordHighlighter<UsingStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UsingStatementHighlighter() { } protected override void AddHighlights(UsingStatementSyntax usingStatement, List<TextSpan> highlights, CancellationToken cancellationToken) => highlights.Add(usingStatement.UsingKeyword.Span); } }
mavasani/roslyn
src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/UsingStatementHighlighter.cs
C#
mit
1,116
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; using Microsoft.VisualStudio.LanguageServices.Telemetry; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class VisualStudioWorkspace_OutOfProc : OutOfProcComponent { private readonly VisualStudioWorkspace_InProc _inProc; internal VisualStudioWorkspace_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<VisualStudioWorkspace_InProc>(visualStudioInstance); } public void SetOptionInfer(string projectName, bool value) { _inProc.SetOptionInfer(projectName, value); WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); } public bool IsPrettyListingOn(string languageName) => _inProc.IsPrettyListingOn(languageName); public void SetPrettyListing(string languageName, bool value) => _inProc.SetPrettyListing(languageName, value); public void SetPerLanguageOption(string optionName, string feature, string language, object value) => _inProc.SetPerLanguageOption(optionName, feature, language, value); public void SetOption(string optionName, string feature, object value) => _inProc.SetOption(optionName, feature, value); public void WaitForAsyncOperations(TimeSpan timeout, string featuresToWaitFor, bool waitForWorkspaceFirst = true) => _inProc.WaitForAsyncOperations(timeout, featuresToWaitFor, waitForWorkspaceFirst); public void WaitForAllAsyncOperations(TimeSpan timeout, params string[] featureNames) => _inProc.WaitForAllAsyncOperations(timeout, featureNames); public void WaitForAllAsyncOperationsOrFail(TimeSpan timeout, params string[] featureNames) => _inProc.WaitForAllAsyncOperationsOrFail(timeout, featureNames); public void CleanUpWorkspace() => _inProc.CleanUpWorkspace(); public void ResetOptions() => _inProc.ResetOptions(); public void CleanUpWaitingService() => _inProc.CleanUpWaitingService(); public void SetImportCompletionOption(bool value) { SetGlobalOption(WellKnownGlobalOption.CompletionOptions_ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, value); SetGlobalOption(WellKnownGlobalOption.CompletionOptions_ShowItemsFromUnimportedNamespaces, LanguageNames.VisualBasic, value); } public void SetEnableDecompilationOption(bool value) { SetOption("NavigateToDecompiledSources", "FeatureOnOffOptions", value); } public void SetArgumentCompletionSnippetsOption(bool value) { SetGlobalOption(WellKnownGlobalOption.CompletionViewOptions_EnableArgumentCompletionSnippets, LanguageNames.CSharp, value); SetGlobalOption(WellKnownGlobalOption.CompletionViewOptions_EnableArgumentCompletionSnippets, LanguageNames.VisualBasic, value); } public void SetTriggerCompletionInArgumentLists(bool value) => SetGlobalOption(WellKnownGlobalOption.CompletionOptions_TriggerInArgumentLists, LanguageNames.CSharp, value); public void SetFullSolutionAnalysis(bool value) { SetPerLanguageOption( optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name, feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature, language: LanguageNames.CSharp, value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default); SetPerLanguageOption( optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name, feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature, language: LanguageNames.VisualBasic, value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default); } public void SetFileScopedNamespaces(bool value) => _inProc.SetFileScopedNamespaces(value); public void SetEnableOpeningSourceGeneratedFilesInWorkspaceExperiment(bool value) { SetGlobalOption( WellKnownGlobalOption.VisualStudioSyntaxTreeConfigurationService_EnableOpeningSourceGeneratedFilesInWorkspace, language: null, value); } public void SetFeatureOption(string feature, string optionName, string? language, string? valueString) => _inProc.SetFeatureOption(feature, optionName, language, valueString); public void SetGlobalOption(WellKnownGlobalOption option, string? language, object? value) => _inProc.SetGlobalOption(option, language, value); } }
CyrusNajmabadi/roslyn
src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/VisualStudioWorkspace_OutOfProc.cs
C#
mit
5,369
<?php namespace SMW\Tests\SPARQLStore; use SMW\SPARQLStore\RedirectLookup; use SMW\InMemoryPoolCache; use SMW\DIWikiPage; use SMW\DIProperty; use SMW\Exporter\Escaper; use SMWExpNsResource as ExpNsResource; use SMWExpLiteral as ExpLiteral; use SMWExpResource as ExpResource; use SMWExporter as Exporter; /** * @covers \SMW\SPARQLStore\RedirectLookup * @group semantic-mediawiki * * @license GNU GPL v2+ * @since 2.0 * * @author mwjames */ class RedirectLookupTest extends \PHPUnit_Framework_TestCase { public function testCanConstruct() { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $this->assertInstanceOf( '\SMW\SPARQLStore\RedirectLookup', new RedirectLookup( $repositoryConnection ) ); } public function testRedirectTragetForBlankNode() { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $expNsResource = new ExpNsResource( '', '', '', null ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertFalse( $exists ); } public function testRedirectTragetForDataItemWithSubobject() { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $dataItem = new DIWikiPage( 'Foo', 1, '', 'beingASubobject' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithNoEntry() { $repositoryConnection = $this->createRepositoryConnectionMockToUse( false ); $instance = new RedirectLookup( $repositoryConnection ); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertFalse( $exists ); } public function testRedirectTragetForDBLookupWithSingleEntry() { $expLiteral = new ExpLiteral( 'Redirect' ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithMultipleEntries() { $expLiteral = new ExpLiteral( 'Redirect' ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral, null ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithMultipleEntriesForcesNewResource() { $propertyPage = new DIWikiPage( 'Foo', SMW_NS_PROPERTY ); $resource = new ExpNsResource( 'Foo', Exporter::getInstance()->getNamespaceUri( 'property' ), 'property', $propertyPage ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $resource, $resource ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $targetResource = $instance->findRedirectTargetResource( $expNsResource, $exists ); $this->assertNotSame( $expNsResource, $targetResource ); $expectedResource = new ExpNsResource( Escaper::encodePage( $propertyPage ), Exporter::getInstance()->getNamespaceUri( 'wiki' ), 'wiki' ); $this->assertEquals( $expectedResource, $targetResource ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithForNonMultipleResourceEntryThrowsException() { $expLiteral = new ExpLiteral( 'Redirect' ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral, $expLiteral ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->setExpectedException( 'RuntimeException' ); $instance->findRedirectTargetResource( $expNsResource, $exists ); } public function testRedirectTargetForCachedLookup() { $dataItem = new DIWikiPage( 'Foo', NS_MAIN ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $poolCache = InMemoryPoolCache::getInstance()->getPoolCacheFor( 'sparql.store.redirectlookup' ); $poolCache->save( $expNsResource->getUri(), $expNsResource ); $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $exists = null; $instance->findRedirectTargetResource( $expNsResource, $exists ); $this->assertTrue( $exists ); $instance->reset(); } /** * @dataProvider nonRedirectableResourceProvider */ public function testRedirectTargetForNonRedirectableResource( $expNsResource ) { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $exists = null; $instance->findRedirectTargetResource( $expNsResource, $exists ); $instance->reset(); $this->assertFalse( $exists ); } private function createRepositoryConnectionMockToUse( $listReturnValue ) { $repositoryResult = $this->getMockBuilder( '\SMW\SPARQLStore\QueryEngine\RepositoryResult' ) ->disableOriginalConstructor() ->getMock(); $repositoryResult->expects( $this->once() ) ->method( 'current' ) ->will( $this->returnValue( $listReturnValue ) ); $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $repositoryConnection->expects( $this->once() ) ->method( 'select' ) ->will( $this->returnValue( $repositoryResult ) ); return $repositoryConnection; } public function nonRedirectableResourceProvider() { $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_INST' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_SUBC' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_REDI' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_MDAT' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_MDAT', true ) ); return $provider; } }
stuartbman/mediawiki-vagrant
mediawiki/extensions/SemanticMediaWiki/tests/phpunit/Unit/SPARQLStore/RedirectLookupTest.php
PHP
mit
7,584
package xpath //please check the search tests in gokogiri/xml and gokogiri/html import "testing" func TestCompileGoodExpr(t *testing.T) { defer CheckXmlMemoryLeaks(t) e := Compile(`./*`) if e == nil { t.Error("expr should be good") } e.Free() } func TestCompileBadExpr(t *testing.T) { //defer CheckXmlMemoryLeaks(t) //this test causes memory leaks in libxml //however, the memory leak is very small and does not grow as more bad expressions are compiled e := Compile("./") if e != nil { t.Error("expr should be bad") } e = Compile(".//") if e != nil { t.Error("expr should be bad") } }
jbowtie/gokogiri
xpath/xpath_test.go
GO
mit
609
<?php /* * This file is part of the Sismo utility. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ use Sismo\Sismo; use Sismo\BuildException; use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\ProcessBuilder; $console = new Application('Sismo', Sismo::VERSION); $console ->register('output') ->setDefinition(array( new InputArgument('slug', InputArgument::REQUIRED, 'Project slug'), )) ->setDescription('Displays the latest output for a project') ->setHelp(<<<EOF The <info>%command.name%</info> command displays the latest output for a project: <info>php %command.full_name% twig</info> EOF ) ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { $sismo = $app['sismo']; $slug = $input->getArgument('slug'); if (!$sismo->hasProject($slug)) { $output->writeln(sprintf('<error>Project "%s" does not exist.</error>', $slug)); return 1; } $project = $sismo->getProject($slug); if (!$project->getLatestCommit()) { $output->writeln(sprintf('<error>Project "%s" has never been built yet.</error>', $slug)); return 2; } $output->write($project->getLatestCommit()->getOutput()); $now = new \DateTime(); $diff = $now->diff($project->getLatestCommit()->getBuildDate()); if ($m = $diff->format('%i')) { $time = $m.' minutes'; } else { $time = $diff->format('%s').' seconds'; } $output->writeln(''); $output->writeln(sprintf('<info>This output was generated by Sismo %s ago</info>', $time)); }) ; $console ->register('projects') ->setDescription('List available projects') ->setHelp(<<<EOF The <info>%command.name%</info> command displays the available projects Sismo can build. EOF ) ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { $sismo = $app['sismo']; $projects = array(); $width = 0; foreach ($sismo->getProjects() as $slug => $project) { $projects[$slug] = $project->getName(); $width = strlen($project->getName()) > $width ? strlen($project->getName()) : $width; } $width += 2; $output->writeln(''); $output->writeln('<comment>Available projects:</comment>'); foreach ($projects as $slug => $project) { $output->writeln(sprintf(" <info>%-${width}s</info> %s", $slug, $project)); } $output->writeln(''); }) ; $console ->register('build') ->setDefinition(array( new InputArgument('slug', InputArgument::OPTIONAL, 'Project slug'), new InputArgument('sha', InputArgument::OPTIONAL, 'Commit sha'), new InputOption('force', '', InputOption::VALUE_NONE, 'Force the build'), new InputOption('local', '', InputOption::VALUE_NONE, 'Disable remote sync'), new InputOption('silent', '', InputOption::VALUE_NONE, 'Disable notifications'), new InputOption('timeout', '', InputOption::VALUE_REQUIRED, 'Time limit'), new InputOption('data-path', '', InputOption::VALUE_REQUIRED, 'The data path'), new InputOption('config-file', '', InputOption::VALUE_REQUIRED, 'The config file'), )) ->setDescription('Build projects') ->setHelp(<<<EOF Without any arguments, the <info>%command.name%</info> command builds the latest commit of all configured projects one after the other: <info>php %command.full_name%</info> The command loads project configurations from <comment>~/.sismo/config.php</comment>. Change it with the <info>--config-file</info> option: <info>php %command.full_name% --config-file=/path/to/config.php</info> Data (repository, DB, ...) are stored in <comment>~/.sismo/data/</comment>. The <info>--data-path</info> option allows you to change the default: <info>php %command.full_name% --data-path=/path/to/data</info> Pass the project slug to build a specific project: <info>php %command.full_name% twig</info> Force a specific commit to be built by passing the SHA: <info>php %command.full_name% twig a1ef34</info> Use <comment>--force</comment> to force the built even if it has already been built previously: <info>php %command.full_name% twig a1ef34 --force</info> Disable notifications with <comment>--silent</comment>: <info>php %command.full_name% twig a1ef34 --silent</info> Disable repository synchonization with <comment>--local</comment>: <info>php %command.full_name% twig a1ef34 --local</info> Limit the time (in seconds) spent by the command building projects by using the <comment>--timeout</comment> option: <info>php %command.full_name% twig --timeout 3600</info> When you use this command as a cron job, <comment>--timeout</comment> can avoid the command to be run concurrently. Be warned that this is a rough estimate as the time is only checked between two builds. When a build is started, it won't be stopped if the time limit is over. Use the <comment>--verbose</comment> option to debug builds in case of a problem. EOF ) ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { if ($input->getOption('data-path')) { $app['data.path'] = $input->getOption('data-path'); } if ($input->getOption('config-file')) { $app['config.file'] = $input->getOption('config-file'); } $sismo = $app['sismo']; if ($slug = $input->getArgument('slug')) { if (!$sismo->hasProject($slug)) { $output->writeln(sprintf('<error>Project "%s" does not exist.</error>', $slug)); return 1; } $projects = array($sismo->getProject($slug)); } else { $projects = $sismo->getProjects(); } $start = time(); $startedOut = false; $startedErr = false; $callback = null; if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) { $callback = function ($type, $buffer) use ($output, &$startedOut, &$startedErr) { if ('err' === $type) { if (!$startedErr) { $output->write("\n<bg=red;fg=white> ERR </> "); $startedErr = true; $startedOut = false; } $output->write(str_replace("\n", "\n<bg=red;fg=white> ERR </> ", $buffer)); } else { if (!$startedOut) { $output->write("\n<bg=green;fg=white> OUT </> "); $startedOut = true; $startedErr = false; } $output->write(str_replace("\n", "\n<bg=green;fg=white> OUT </> ", $buffer)); } }; } $flags = 0; if ($input->getOption('force')) { $flags = $flags | Sismo::FORCE_BUILD; } if ($input->getOption('local')) { $flags = $flags | Sismo::LOCAL_BUILD; } if ($input->getOption('silent')) { $flags = $flags | Sismo::SILENT_BUILD; } $returnValue = 0; foreach ($projects as $project) { // out of time? if ($input->getOption('timeout') && time() - $start > $input->getOption('timeout')) { break; } try { $output->writeln(sprintf('<info>Building Project "%s" (into "%s")</info>', $project, $app['builder']->getBuildDir($project))); $sismo->build($project, $input->getArgument('sha'), $flags, $callback); $output->writeln(''); } catch (BuildException $e) { $output->writeln("\n".sprintf('<error>%s</error>', $e->getMessage())); $returnValue = 1; } } return $returnValue; }) ; $console ->register('run') ->setDefinition(array( new InputArgument('address', InputArgument::OPTIONAL, 'Address:port', 'localhost:9000'), )) ->setDescription('Runs Sismo with PHP built-in web server') ->setHelp(<<<EOF The <info>%command.name%</info> command runs the embedded Sismo web server: <info>%command.full_name%</info> You can also customize the default address and port the web server listens to: <info>%command.full_name% 127.0.0.1:8080</info> EOF ) ->setCode(function (InputInterface $input, OutputInterface $output) use ($console) { if (version_compare(PHP_VERSION, '5.4.0') < 0) { throw new \Exception('This feature only runs with PHP 5.4.0 or higher.'); } $sismo = __DIR__.'/sismo.php'; while (!file_exists($sismo)) { $dialog = $console->getHelperSet()->get('dialog'); $sismo = $dialog->ask($output, sprintf('<comment>I cannot find "%s". What\'s the absoulte path of "sismo.php"?</comment> ', $sismo), __DIR__.'/sismo.php'); } $output->writeln(sprintf("Sismo running on <info>%s</info>\n", $input->getArgument('address'))); $builder = new ProcessBuilder(array(PHP_BINARY, '-S', $input->getArgument('address'), $sismo)); $builder->setWorkingDirectory(getcwd()); $builder->setTimeout(null); $builder->getProcess()->run(function ($type, $buffer) use ($output) { if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) { $output->write($buffer); } }); }) ; return $console;
druid628/Sismo
src/console.php
PHP
mit
9,948
#include "scripting/lua-bindings/manual/ui/lua_cocos2dx_experimental_video_manual.hpp" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #include "ui/UIVideoPlayer.h" #include "scripting/lua-bindings/manual/tolua_fix.h" #include "scripting/lua-bindings/manual/LuaBasicConversions.h" #include "scripting/lua-bindings/manual/CCLuaValue.h" #include "scripting/lua-bindings/manual/CCLuaEngine.h" static int lua_cocos2dx_experimental_video_VideoPlayer_addEventListener(lua_State* L) { int argc = 0; cocos2d::experimental::ui::VideoPlayer* self = nullptr; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; if (!tolua_isusertype(L,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast<cocos2d::experimental::ui::VideoPlayer*>(tolua_tousertype(L,1,0)); #if COCOS2D_DEBUG >= 1 if (nullptr == self) { tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Widget_addTouchEventListener'\n", nullptr); return 0; } #endif argc = lua_gettop(L) - 1; if (argc == 1) { #if COCOS2D_DEBUG >= 1 if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err)) { goto tolua_lerror; } #endif LUA_FUNCTION handler = ( toluafix_ref_function(L,2,0)); self->addEventListener([=](cocos2d::Ref* ref, cocos2d::experimental::ui::VideoPlayer::EventType eventType){ LuaStack* stack = LuaEngine::getInstance()->getLuaStack(); stack->pushObject(ref, "cc.Ref"); stack->pushInt((int)eventType); stack->executeFunctionByHandler(handler, 2); }); return 0; } luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d\n ", "ccexp.VideoPlayer:addEventListener",argc, 0); return 0; #if COCOS2D_DEBUG >= 1 tolua_lerror: tolua_error(L, "#ferror in function 'lua_cocos2dx_experimental_VideoPlayer_addEventListener'.", &tolua_err); #endif return 0; } static void extendVideoPlayer(lua_State* L) { lua_pushstring(L, "ccexp.VideoPlayer"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { tolua_function(L, "addEventListener", lua_cocos2dx_experimental_video_VideoPlayer_addEventListener); } lua_pop(L, 1); } int register_all_cocos2dx_experimental_video_manual(lua_State* L) { if (nullptr == L) return 0; extendVideoPlayer(L); return 0; } #endif
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/manual/ui/lua_cocos2dx_experimental_video_manual.cpp
C++
mit
2,501
require File.expand_path('../../test_helper', __FILE__) require 'mocha/metaclass' class MetaclassTest < Test::Unit::TestCase def test_should_return_objects_singleton_class object = Object.new assert_raises(NoMethodError) { object.success? } object = Object.new assert object.__metaclass__.ancestors.include?(Object) assert object.__metaclass__.ancestors.include?(Kernel) assert object.__metaclass__.is_a?(Class) object.__metaclass__.class_eval { def success?; true; end } assert object.success? object = Object.new assert_raises(NoMethodError) { object.success? } end end
natematias/Our-Things
vendor/gems/mocha-0.9.12/test/unit/metaclass_test.rb
Ruby
mit
629
/* _____ __ ___ __ ____ _ __ / ___/__ ___ _ ___ / |/ /__ ___ / /_____ __ __/ __/_______(_)__ / /_ / (_ / _ `/ ' \/ -_) /|_/ / _ \/ _ \/ '_/ -_) // /\ \/ __/ __/ / _ \/ __/ \___/\_,_/_/_/_/\__/_/ /_/\___/_//_/_/\_\\__/\_, /___/\__/_/ /_/ .__/\__/ /___/ /_/ See Copyright Notice in gmMachine.h */ #include "gmDebug.h" #include "gmConfig.h" #include "gmMachine.h" #include "gmThread.h" #if GMDEBUG_SUPPORT #define ID_mrun GM_MAKE_ID32('m','r','u','n') #define ID_msin GM_MAKE_ID32('m','s','i','n') #define ID_msou GM_MAKE_ID32('m','s','o','u') #define ID_msov GM_MAKE_ID32('m','s','o','v') #define ID_mgct GM_MAKE_ID32('m','g','c','t') #define ID_mgsr GM_MAKE_ID32('m','g','s','r') #define ID_mgsi GM_MAKE_ID32('m','g','s','i') #define ID_mgti GM_MAKE_ID32('m','g','t','i') #define ID_mgvi GM_MAKE_ID32('m','g','v','i') #define ID_msbp GM_MAKE_ID32('m','s','b','p') #define ID_mbrk GM_MAKE_ID32('m','b','r','k') #define ID_mend GM_MAKE_ID32('m','e','n','d') #define ID_dbrk GM_MAKE_ID32('d','b','r','k') #define ID_dexc GM_MAKE_ID32('d','e','x','c') #define ID_drun GM_MAKE_ID32('d','r','u','n') #define ID_dstp GM_MAKE_ID32('d','s','t','p') #define ID_dsrc GM_MAKE_ID32('d','s','r','c') #define ID_dctx GM_MAKE_ID32('d','c','t','x') #define ID_call GM_MAKE_ID32('c','a','l','l') #define ID_vari GM_MAKE_ID32('v','a','r','i') #define ID_done GM_MAKE_ID32('d','o','n','e') #define ID_dsri GM_MAKE_ID32('d','s','r','i') #define ID_srci GM_MAKE_ID32('s','r','c','i') #define ID_done GM_MAKE_ID32('d','o','n','e') #define ID_dthi GM_MAKE_ID32('d','t','h','i') #define ID_thri GM_MAKE_ID32('t','h','r','i') #define ID_done GM_MAKE_ID32('d','o','n','e') #define ID_derr GM_MAKE_ID32('d','e','r','r') #define ID_dmsg GM_MAKE_ID32('d','m','s','g') #define ID_dack GM_MAKE_ID32('d','a','c','k') #define ID_dend GM_MAKE_ID32('d','e','n','d') // // functions to handle incomming commands from a debugger // void gmMachineRun(gmDebugSession * a_session, int a_threadId); void gmMachineStepInto(gmDebugSession * a_session, int a_threadId); void gmMachineStepOver(gmDebugSession * a_session, int a_threadId); void gmMachineStepOut(gmDebugSession * a_session, int a_threadId); void gmMachineGetContext(gmDebugSession * a_session, int a_threadId, int a_callframe); void gmMachineGetSource(gmDebugSession * a_session, int a_sourceId); void gmMachineGetSourceInfo(gmDebugSession * a_session); void gmMachineGetThreadInfo(gmDebugSession * a_session); void gmMachineGetVariableInfo(gmDebugSession * a_session, int a_variableId); void gmMachineSetBreakPoint(gmDebugSession * a_session, int a_responseId, int a_sourceId, int a_lineNumber, int a_threadId, int a_enabled); void gmMachineBreak(gmDebugSession * a_session, int a_threadId); void gmMachineQuit(gmDebugSession * a_session); // // functions to package outgoing messages to a debugger // void gmDebuggerBreak(gmDebugSession * a_session, int a_threadId, int a_sourceId, int a_lineNumber); void gmDebuggerRun(gmDebugSession * a_session, int a_threadId); void gmDebuggerStop(gmDebugSession * a_session, int a_threadId); void gmDebuggerSource(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName, const char * a_source); void gmDebuggerException(gmDebugSession * a_session, int a_threadId); void gmDebuggerBeginContext(gmDebugSession * a_session, int a_threadId, int a_callFrame); void gmDebuggerContextCallFrame(gmDebugSession * a_session, int a_callFrame, const char * a_functionName, int a_sourceId, int a_lineNumber, const char * a_thisSymbol, const char * a_thisValue, int a_thisId); void gmDebuggerContextVariable(gmDebugSession * a_session, const char * a_varSymbol, const char * a_varValue, int a_varId); void gmDebuggerEndContext(gmDebugSession * a_session); void gmDebuggerBeginSourceInfo(gmDebugSession * a_session); void gmDebuggerSourceInfo(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName); void gmDebuggerEndSourceInfo(gmDebugSession * a_session); void gmDebuggerBeginThreadInfo(gmDebugSession * a_session); void gmDebuggerThreadInfo(gmDebugSession * a_session, int a_threadId, int a_threadState); void gmDebuggerEndThreadInfo(gmDebugSession * a_session); void gmDebuggerError(gmDebugSession * a_session, const char * a_error); void gmDebuggerMessage(gmDebugSession * a_session, const char * a_message); void gmDebuggerAck(gmDebugSession * a_session, int a_response, int a_posNeg); void gmDebuggerQuit(gmDebugSession * a_session); // // debug machine callback // enum gmdThreadFlags { TF_STEPOVER = (1 << 0), TF_STEPINTO = (1 << 1), TF_STEPOUT = (1 << 2), TF_BREAK = (1 << 3), }; // the following callbacks return true if the thread is to yield after completion of the callback. static bool LineCallback(gmThread * a_thread) { gmDebugSession * session = (gmDebugSession *) a_thread->GetMachine()->m_debugUser; GM_ASSERT(session); if(!(a_thread->m_debugFlags & TF_STEPOVER) || (a_thread->m_debugUser != ((a_thread->GetFrame()) ? a_thread->GetFrame()->m_returnBase : 0))) { int * bp = session->FindBreakPoint((void *) a_thread->GetInstruction()); if(bp == NULL) return false; if(*bp && *bp != a_thread->GetId()) return false; } a_thread->m_debugFlags = TF_BREAK; const gmFunctionObject * fn = a_thread->GetFunctionObject(); gmDebuggerBreak(session, a_thread->GetId(), fn->GetSourceId(), fn->GetLine(a_thread->GetInstruction())); return true; } static bool CallCallback(gmThread * a_thread) { gmDebugSession * session = (gmDebugSession *) a_thread->GetMachine()->m_debugUser; GM_ASSERT(session); if(a_thread->m_debugFlags & TF_STEPINTO) { a_thread->m_debugFlags = TF_BREAK; const gmFunctionObject * fn = a_thread->GetFunctionObject(); gmDebuggerBreak(session, a_thread->GetId(), fn->GetSourceId(), fn->GetLine(a_thread->GetInstruction())); return true; } return false; } static bool RetCallback(gmThread * a_thread) { gmDebugSession * session = (gmDebugSession *) a_thread->GetMachine()->m_debugUser; GM_ASSERT(session); if(((a_thread->m_debugFlags & TF_STEPOUT) && (a_thread->m_debugUser == a_thread->GetIntBase())) || ((a_thread->m_debugFlags & TF_STEPOVER) && (a_thread->m_debugUser == a_thread->GetIntBase()))) { a_thread->m_debugFlags = TF_BREAK; const gmFunctionObject * fn = a_thread->GetFunctionObject(); gmDebuggerBreak(session, a_thread->GetId(), fn->GetSourceId(), fn->GetLine(a_thread->GetInstruction())); return true; } return false; } static bool IsBrokenCallback(gmThread * a_thread) { return (a_thread->m_debugFlags & TF_BREAK) > 0; } static gmMachineCallback s_prevMachineCallback = NULL; bool GM_CDECL gmdMachineCallback(gmMachine * a_machine, gmMachineCommand a_command, const void * a_context) { gmDebugSession * session = (gmDebugSession *) a_machine->m_debugUser; const gmThread * thread = (const gmThread *) a_context; // chain callback if(s_prevMachineCallback) s_prevMachineCallback(a_machine, a_command, a_context); // do we have a debug session? if(session == NULL) return false; // command switch(a_command) { case MC_THREAD_EXCEPTION : { // send thread exception message gmDebuggerException(session, thread->GetId()); a_machine->GetLog(); bool first = true; const char * entry; while((entry = a_machine->GetLog().GetEntry(first))) { gmDebuggerError(session, entry); } return true; } case MC_THREAD_CREATE : { gmDebuggerRun(session, thread->GetId()); break; } case MC_THREAD_DESTROY : { gmDebuggerStop(session, thread->GetId()); break; } default : break; }; return false; } // // debug session // gmDebugSession::gmDebugSession() : m_breaks(32) { m_machine = NULL; } gmDebugSession::~gmDebugSession() { m_breaks.RemoveAndDeleteAll(); } void gmDebugSession::Update() { for(;;) { int len; const void * msg = m_pumpMessage(this, len); if(msg == NULL) break; m_in.Open(msg, len); // parse the message int id, pa, pb, pc, pd; Unpack(id); switch(id) { case ID_mrun : Unpack(id); gmMachineRun(this, id); break; case ID_msin : Unpack(id); gmMachineStepInto(this, id); break; case ID_msou : Unpack(id); gmMachineStepOut(this, id); break; case ID_msov : Unpack(id); gmMachineStepOver(this, id); break; case ID_mgct : Unpack(id).Unpack(pa); gmMachineGetContext(this, id, pa); break; case ID_mgsr : Unpack(id); gmMachineGetSource(this, id); break; case ID_mgsi : gmMachineGetSourceInfo(this); break; case ID_mgti : gmMachineGetThreadInfo(this); break; case ID_mgvi : Unpack(id); gmMachineGetVariableInfo(this, id); break; case ID_msbp : Unpack(pa).Unpack(pb).Unpack(pc).Unpack(id).Unpack(pd); gmMachineSetBreakPoint(this, pa, pb, pc, id, pd); break; case ID_mbrk : Unpack(id); gmMachineBreak(this, id); break; case ID_mend : gmMachineQuit(this); break; default:; } } } bool gmDebugSession::Open(gmMachine * a_machine) { Close(); m_machine = a_machine; m_machine->m_debugUser = this; m_machine->m_line = LineCallback; m_machine->m_call = CallCallback; m_machine->m_isBroken = IsBrokenCallback; m_machine->m_return = RetCallback; s_prevMachineCallback = a_machine->s_machineCallback; a_machine->s_machineCallback = gmdMachineCallback; return true; } static bool threadIterClose(gmThread * a_thread, void * a_context) { a_thread->m_debugFlags = 0; a_thread->m_debugUser = 0; return true; } bool gmDebugSession::Close() { if(m_machine && m_machine->m_debugUser == this) { gmDebuggerQuit(this); m_machine->m_debugUser = NULL; m_machine->s_machineCallback = s_prevMachineCallback; m_machine->m_line = NULL; m_machine->m_call = NULL; m_machine->m_return = NULL; m_machine->m_isBroken = NULL; m_machine->KillExceptionThreads(); m_machine->ForEachThread(threadIterClose, NULL); m_machine = NULL; m_breaks.RemoveAndDeleteAll(); m_out.ResetAndFreeMemory(); return true; } m_breaks.RemoveAndDeleteAll(); m_out.ResetAndFreeMemory(); return false; } gmDebugSession &gmDebugSession::Pack(int a_val) { m_out << a_val; return *this; } gmDebugSession &gmDebugSession::Pack(const char * a_val) { if(a_val) m_out.Write(a_val, strlen(a_val) + 1); else m_out.Write("", 1); return *this; } void gmDebugSession::Send() { m_sendMessage(this, m_out.GetData(), m_out.GetSize()); m_out.Reset(); } gmDebugSession &gmDebugSession::Unpack(int &a_val) { if(m_in.Read(&a_val, 4) != 4) a_val = 0; return *this; } gmDebugSession &gmDebugSession::Unpack(const char * &a_val) { // this is dangerous!!! a_val = &m_in.GetData()[m_in.Tell()]; int len = strlen(a_val); m_in.Seek(m_in.Tell() + len + 1); return *this; } bool gmDebugSession::AddBreakPoint(const void * a_bp, int a_threadId) { BreakPoint * bp = m_breaks.Find((void *const&)a_bp); if(bp) return false; bp = GM_NEW( BreakPoint() ); bp->m_bp = a_bp; bp->m_threadId = a_threadId; m_breaks.Insert(bp); return true; } int * gmDebugSession::FindBreakPoint(const void * a_bp) { BreakPoint * bp = m_breaks.Find((void *const&)a_bp); if(bp) { return &bp->m_threadId; } return NULL; } bool gmDebugSession::RemoveBreakPoint(const void * a_bp) { BreakPoint * bp = m_breaks.Find((void *const&)a_bp); if(bp) { m_breaks.Remove(bp); delete bp; return true; } return false; } // // implementation // void gmMachineRun(gmDebugSession * a_session, int a_threadId) { gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { thread->m_debugFlags = 0; } } void gmMachineStepInto(gmDebugSession * a_session, int a_threadId) { gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0; thread->m_debugFlags = TF_STEPINTO | TF_STEPOVER; } } void gmMachineStepOver(gmDebugSession * a_session, int a_threadId) { gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0; thread->m_debugFlags = TF_STEPOVER; } } void gmMachineStepOut(gmDebugSession * a_session, int a_threadId) { gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0; thread->m_debugFlags = TF_STEPOUT; } } void gmMachineGetContext(gmDebugSession * a_session, int a_threadId, int a_callframe) { const int buffSize = 256; char buff[buffSize]; // buff is used for AsString gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { // count the number of frames on the thread int numFrames = 0; const gmStackFrame * frame = thread->GetFrame(); while(frame) { ++numFrames; frame = frame->m_prev; } // if a valid frame was requested, fill out a context. if(a_callframe >= 0 && a_callframe <= numFrames) { gmDebuggerBeginContext(a_session, a_threadId, a_callframe); // pack frames frame = thread->GetFrame(); numFrames = 0; gmVariable * base = thread->GetBase(); const gmuint8 * ip = thread->GetInstruction(); while(frame) { // get the function object gmVariable * fnVar = base - 1; if(fnVar->m_type == GM_FUNCTION) { gmFunctionObject * fn = (gmFunctionObject *) GM_MOBJECT(thread->GetMachine(), fnVar->m_value.m_ref); // this base[-2].AsStringWithType(thread->GetMachine(), buff, buffSize); gmDebuggerContextCallFrame(a_session, numFrames, fn->GetDebugName(), fn->GetSourceId(), fn->GetLine(ip), "this", buff, (base[-2].IsReference()) ? base[-2].m_value.m_ref : 0); if(numFrames == a_callframe) { // this is the active frame, fill out the variables int i; for(i = 0; i < fn->GetNumParamsLocals(); ++i) { base[i].AsStringWithType(thread->GetMachine(), buff, buffSize); gmDebuggerContextVariable(a_session, fn->GetSymbol(i), buff, (base[i].IsReference()) ? base[i].m_value.m_ref : 0); } } } else { base[-2].AsStringWithType(thread->GetMachine(), buff, buffSize); gmDebuggerContextCallFrame(a_session, numFrames, "unknown", 0, 0, "this", buff, (base[-2].IsReference()) ? base[-2].m_value.m_ref : 0); } // next call frame ++numFrames; base = thread->GetBottom() + frame->m_returnBase; ip = frame->m_returnAddress; frame = frame->m_prev; } gmDebuggerEndContext(a_session); } } } void gmMachineGetSource(gmDebugSession * a_session, int a_sourceId) { const char * source; const char * filename; if(a_session->GetMachine()->GetSourceCode(a_sourceId, source, filename)) { gmDebuggerSource(a_session, a_sourceId, filename, source); } } void gmMachineGetSourceInfo(gmDebugSession * a_session) { // todo } static bool threadIter(gmThread * a_thread, void * a_context) { gmDebugSession * session = (gmDebugSession *) a_context; int state = 0; // 0 - running, 1 - blocked, 2 - sleeping, 3 - exception, 4 - debug if(a_thread->m_debugFlags) state = 4; else if(a_thread->GetState() == gmThread::EXCEPTION) state = 3; else if(a_thread->GetState() == gmThread::RUNNING) state = 0; else if(a_thread->GetState() == gmThread::BLOCKED) state = 1; else if(a_thread->GetState() == gmThread::SLEEPING) state = 2; else state = 3; gmDebuggerThreadInfo(session, a_thread->GetId(), state); return true; } void gmMachineGetThreadInfo(gmDebugSession * a_session) { gmDebuggerBeginThreadInfo(a_session); a_session->GetMachine()->ForEachThread(threadIter, a_session); gmDebuggerEndThreadInfo(a_session); } void gmMachineGetVariableInfo(gmDebugSession * a_session, int a_variableId) { // todo } void gmMachineSetBreakPoint(gmDebugSession * a_session, int a_responseId, int a_sourceId, int a_lineNumber, int a_threadId, int a_enabled) { bool sendAck = false; // get break point const void * bp = (const void *) a_session->GetMachine()->GetInstructionAtBreakPoint(a_sourceId, a_lineNumber); if(bp) { // get to next instruction bp = (const void *) (((const char *) bp) + 4); int * id = a_session->FindBreakPoint(bp); if(id) { if(!a_enabled) { a_session->RemoveBreakPoint(bp); sendAck = true; } } else { if(a_session->AddBreakPoint(bp, a_threadId)) { sendAck = true; } } } if(sendAck) gmDebuggerAck(a_session, a_responseId, 1); else gmDebuggerAck(a_session, a_responseId, 0); } void gmMachineBreak(gmDebugSession * a_session, int a_threadId) { gmThread * thread = a_session->GetMachine()->GetThread(a_threadId); if(thread) { thread->m_debugUser = (thread->GetFrame()) ? thread->GetFrame()->m_returnBase : 0; thread->m_debugFlags = TF_STEPINTO | TF_STEPOVER; } } void gmMachineQuit(gmDebugSession * a_session) { a_session->Close(); } void gmDebuggerBreak(gmDebugSession * a_session, int a_threadId, int a_sourceId, int a_lineNumber) { a_session->Pack(ID_dbrk).Pack(a_threadId).Pack(a_sourceId).Pack(a_lineNumber).Send(); } void gmDebuggerException(gmDebugSession * a_session, int a_threadId) { a_session->Pack(ID_dexc).Pack(a_threadId).Send(); } void gmDebuggerRun(gmDebugSession * a_session, int a_threadId) { a_session->Pack(ID_drun).Pack(a_threadId).Send(); } void gmDebuggerStop(gmDebugSession * a_session, int a_threadId) { a_session->Pack(ID_dstp).Pack(a_threadId).Send(); } void gmDebuggerSource(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName, const char * a_source) { a_session->Pack(ID_dsrc).Pack(a_sourceId).Pack(a_sourceName).Pack(a_source).Send(); } void gmDebuggerBeginContext(gmDebugSession * a_session, int a_threadId, int a_callFrame) { a_session->Pack(ID_dctx).Pack(a_threadId).Pack(a_callFrame); } void gmDebuggerContextCallFrame(gmDebugSession * a_session, int a_callFrame, const char * a_functionName, int a_sourceId, int a_lineNumber, const char * a_thisSymbol, const char * a_thisValue, int a_thisId) { a_session->Pack(ID_call).Pack(a_callFrame).Pack(a_functionName).Pack(a_sourceId).Pack(a_lineNumber).Pack(a_thisSymbol).Pack(a_thisValue).Pack(a_thisId); } void gmDebuggerContextVariable(gmDebugSession * a_session, const char * a_varSymbol, const char * a_varValue, int a_varId) { a_session->Pack(ID_vari).Pack(a_varSymbol).Pack(a_varValue).Pack(a_varId); } void gmDebuggerEndContext(gmDebugSession * a_session) { a_session->Pack(ID_done).Send(); } void gmDebuggerBeginSourceInfo(gmDebugSession * a_session) { a_session->Pack(ID_dsri); } void gmDebuggerSourceInfo(gmDebugSession * a_session, int a_sourceId, const char * a_sourceName) { a_session->Pack(ID_srci).Pack(a_sourceId).Pack(a_sourceName); } void gmDebuggerEndSourceInfo(gmDebugSession * a_session) { a_session->Pack(ID_done).Send(); } void gmDebuggerBeginThreadInfo(gmDebugSession * a_session) { a_session->Pack(ID_dthi); } void gmDebuggerThreadInfo(gmDebugSession * a_session, int a_threadId, int a_threadState) { a_session->Pack(ID_thri).Pack(a_threadId).Pack(a_threadState); } void gmDebuggerEndThreadInfo(gmDebugSession * a_session) { a_session->Pack(ID_done).Send(); } void gmDebuggerError(gmDebugSession * a_session, const char * a_error) { a_session->Pack(ID_derr).Pack(a_error).Send(); } void gmDebuggerMessage(gmDebugSession * a_session, const char * a_message) { a_session->Pack(ID_dmsg).Pack(a_message).Send(); } void gmDebuggerAck(gmDebugSession * a_session, int a_response, int a_posNeg) { a_session->Pack(ID_dack).Pack(a_response).Pack(a_posNeg).Send(); } void gmDebuggerQuit(gmDebugSession * a_session) { a_session->Pack(ID_dend).Send(); } // // lib binding // int GM_CDECL gmdDebug(gmThread * a_thread) { // if the machine has a debug session, attach a debug hook to the thread if(a_thread->GetMachine()->m_debugUser && a_thread->GetMachine()->GetDebugMode()) { a_thread->m_debugUser = (a_thread->GetFrame()) ? a_thread->GetFrame()->m_returnBase : 0; a_thread->m_debugFlags = TF_STEPINTO | TF_STEPOVER; } return GM_OK; } static gmFunctionEntry s_debugLib[] = { /*gm \lib gm \brief functions in the gm lib are all global scope */ /*gm \function debug \brief debug will cause a the debugger to break at this point while running. */ {"debug", gmdDebug}, }; void gmBindDebugLib(gmMachine * a_machine) { a_machine->RegisterLibrary(s_debugLib, sizeof(s_debugLib) / sizeof(s_debugLib[0])); } #endif
LothusMarque/Furnarchy
furnarchy2/furnarchyskin/gm/gmDebug.cpp
C++
mit
22,124
module Jasminerice module ApplicationHelper end end
ajacksified/restful-clients-in-rails-demo
rack-proxy/ruby/1.9.1/gems/jasminerice-0.0.8/app/helpers/jasminerice/application_helper.rb
Ruby
mit
56
goog.require('ol.Map'); goog.require('ol.View'); goog.require('ol.control'); goog.require('ol.layer.Tile'); goog.require('ol.layer.Vector'); goog.require('ol.source.GeoJSON'); goog.require('ol.source.OSM'); var map = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }), new ol.layer.Vector({ source: new ol.source.GeoJSON({ projection: 'EPSG:3857', url: 'data/geojson/countries.geojson' }) }) ], target: 'map', controls: ol.control.defaults({ attributionOptions: /** @type {olx.control.AttributionOptions} */ ({ collapsible: false }) }), view: new ol.View({ center: [0, 0], zoom: 2 }) }); var exportPNGElement = document.getElementById('export-png'); if ('download' in exportPNGElement) { exportPNGElement.addEventListener('click', function(e) { map.once('postcompose', function(event) { var canvas = event.context.canvas; exportPNGElement.href = canvas.toDataURL('image/png'); }); map.renderSync(); }, false); } else { var info = document.getElementById('no-download'); /** * display error message */ info.style.display = ''; }
buddebej/ol3-dem
ol3/examples/export-map.js
JavaScript
mit
1,180
'use strict'; angular.module('sumaAnalysis') .factory('actsLocs', function () { function calculateDepthAndTooltip (item, list, root, depth) { var parent; depth = depth || {depth: 0, tooltipTitle: item.title, ancestors: []}; if (parseInt(item.parent, 10) === parseInt(root, 10)) { return depth; } parent = _.find(list, {'id': item.parent}); depth.depth += 1; depth.tooltipTitle = parent.title + ': ' + depth.tooltipTitle; depth.ancestors.push(parent.id); return calculateDepthAndTooltip(parent, list, root, depth); } function processActivities (activities, activityGroups) { var activityList = [], activityGroupsHash; // Sort activities and activity groups activities = _.sortBy(activities, 'rank'); activityGroups = _.sortBy(activityGroups, 'rank'); activityGroupsHash = _.object(_.map(activityGroups, function (aGrp) { return [aGrp.id, aGrp.title]; })); // For each activity group, build a list of activities _.each(activityGroups, function (activityGroup) { // Add activity group metadata to activityGroupList array activityList.push({ 'id' : activityGroup.id, 'rank' : activityGroup.rank, 'title' : activityGroup.title, 'type' : 'activityGroup', 'depth' : 0, 'filter' : 'allow', 'enabled': true }); // Loop over activities and add the ones belonging to the current activityGroup _.each(activities, function (activity) { if (activity.activityGroup === activityGroup.id) { // Add activities to activityList array behind proper activityGroup activityList.push({ 'id' : activity.id, 'rank' : activity.rank, 'title' : activity.title, 'type' : 'activity', 'depth' : 1, 'activityGroup' : activityGroup.id, 'activityGroupTitle': activityGroupsHash[activityGroup.id], 'tooltipTitle' : activityGroupsHash[activityGroup.id] + ': ' + activity.title, 'altName' : activityGroupsHash[activityGroup.id] + ': ' + activity.title, 'filter' : 'allow', 'enabled' : true }); } }); }); return activityList; } function processLocations (locations, root) { return _.map(locations, function (loc, index, list) { var depth = calculateDepthAndTooltip(loc, list, root); loc.depth = depth.depth; loc.tooltipTitle = depth.tooltipTitle; loc.ancestors = depth.ancestors; loc.filter = true; loc.enabled = true; return loc; }); } return { get: function (init) { return { activities: processActivities(init.dictionary.activities, init.dictionary.activityGroups), locations: processLocations(init.dictionary.locations, init.rootLocation) }; } }; });
cazzerson/Suma
analysis/src/scripts/services/actsLocs.js
JavaScript
mit
3,247
""" kombu.transport.pyamqp ====================== pure python amqp transport. """ from __future__ import absolute_import import amqp from kombu.five import items from kombu.utils.amq_manager import get_manager from kombu.utils.text import version_string_as_tuple from . import base DEFAULT_PORT = 5672 DEFAULT_SSL_PORT = 5671 class Message(base.Message): def __init__(self, channel, msg, **kwargs): props = msg.properties super(Message, self).__init__( channel, body=msg.body, delivery_tag=msg.delivery_tag, content_type=props.get('content_type'), content_encoding=props.get('content_encoding'), delivery_info=msg.delivery_info, properties=msg.properties, headers=props.get('application_headers') or {}, **kwargs) class Channel(amqp.Channel, base.StdChannel): Message = Message def prepare_message(self, body, priority=None, content_type=None, content_encoding=None, headers=None, properties=None, _Message=amqp.Message): """Prepares message so that it can be sent using this transport.""" return _Message( body, priority=priority, content_type=content_type, content_encoding=content_encoding, application_headers=headers, **properties or {} ) def message_to_python(self, raw_message): """Convert encoded message body back to a Python value.""" return self.Message(self, raw_message) class Connection(amqp.Connection): Channel = Channel class Transport(base.Transport): Connection = Connection default_port = DEFAULT_PORT default_ssl_port = DEFAULT_SSL_PORT # it's very annoying that pyamqp sometimes raises AttributeError # if the connection is lost, but nothing we can do about that here. connection_errors = amqp.Connection.connection_errors channel_errors = amqp.Connection.channel_errors recoverable_connection_errors = \ amqp.Connection.recoverable_connection_errors recoverable_channel_errors = amqp.Connection.recoverable_channel_errors driver_name = 'py-amqp' driver_type = 'amqp' supports_heartbeats = True supports_ev = True def __init__(self, client, default_port=None, default_ssl_port=None, **kwargs): self.client = client self.default_port = default_port or self.default_port self.default_ssl_port = default_ssl_port or self.default_ssl_port def driver_version(self): return amqp.__version__ def create_channel(self, connection): return connection.channel() def drain_events(self, connection, **kwargs): return connection.drain_events(**kwargs) def establish_connection(self): """Establish connection to the AMQP broker.""" conninfo = self.client for name, default_value in items(self.default_connection_params): if not getattr(conninfo, name, None): setattr(conninfo, name, default_value) if conninfo.hostname == 'localhost': conninfo.hostname = '127.0.0.1' opts = dict({ 'host': conninfo.host, 'userid': conninfo.userid, 'password': conninfo.password, 'login_method': conninfo.login_method, 'virtual_host': conninfo.virtual_host, 'insist': conninfo.insist, 'ssl': conninfo.ssl, 'connect_timeout': conninfo.connect_timeout, 'heartbeat': conninfo.heartbeat, }, **conninfo.transport_options or {}) conn = self.Connection(**opts) conn.client = self.client return conn def verify_connection(self, connection): return connection.connected def close_connection(self, connection): """Close the AMQP broker connection.""" connection.client = None connection.close() def get_heartbeat_interval(self, connection): return connection.heartbeat def register_with_event_loop(self, connection, loop): loop.add_reader(connection.sock, self.on_readable, connection, loop) def heartbeat_check(self, connection, rate=2): return connection.heartbeat_tick(rate=rate) def qos_semantics_matches_spec(self, connection): props = connection.server_properties if props.get('product') == 'RabbitMQ': return version_string_as_tuple(props['version']) < (3, 3) return True @property def default_connection_params(self): return { 'userid': 'guest', 'password': 'guest', 'port': (self.default_ssl_port if self.client.ssl else self.default_port), 'hostname': 'localhost', 'login_method': 'AMQPLAIN', } def get_manager(self, *args, **kwargs): return get_manager(self.client, *args, **kwargs)
sunze/py_flask
venv/lib/python3.4/site-packages/kombu/transport/pyamqp.py
Python
mit
5,008
<?php defined('C5_EXECUTE') or die("Access Denied."); use Concrete\Core\Entity\Sharing\SocialNetwork\Link; use Concrete\Core\Form\Service\Form; use Concrete\Core\Sharing\SocialNetwork\Service; use Concrete\Core\Support\Facade\Application; use Concrete\Core\Support\Facade\Url; /** @var Link[] $links */ /** @var Link[] $selectedLinks */ $app = Application::getFacadeApplication(); /** @var Form $form */ $form = $app->make(Form::class); ?> <div class="form-group"> <label class="control-label form-label"> <?php echo t('Choose Social Links to Show'); ?> </label> <div id="ccm-block-social-links-list"> <?php if (0 == count($links)) { ?> <p> <?php echo t('You have not added any social links.'); ?> </p> <?php } ?> <?php foreach ($links as $link) { ?> <?php /** @var Service $service */ $service = $link->getServiceObject(); ?> <?php if ($service) { ?> <div class="form-check"> <label for="<?php echo "slID" . $link->getID(); ?>" class="form-check-label"> <?php echo $form->checkbox("socialService", $link->getID(), is_array($selectedLinks) && in_array($link, $selectedLinks), ["name" => "slID[]", "id" => "slID" . $link->getID()]); ?> <?php echo $service->getDisplayName(); ?> </label> <i class="fas fa-arrows-alt"></i> </div> <?php } ?> <?php } ?> </div> </div> <div class="alert alert-info"> <?php echo t(/*i18n: the two %s will be replaced with HTML code*/'Add social links %sin the dashboard%s', '<a href="' . (string)Url::to('/dashboard/system/basics/social') . '">' ,'</a>'); ?> </div> <!--suppress CssUnusedSymbol --> <style type="text/css"> #ccm-block-social-links-list { -webkit-user-select: none; position: relative; } #ccm-block-social-links-list .form-check { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; margin-bottom: 0; padding: 6px; } #ccm-block-social-links-list .form-check:hover { background: #e7e7e7; border-radius: 4px; transition: background-color .1s linear; } #ccm-block-social-links-list .form-check.ui-sortable-helper { background: none; } #ccm-block-social-links-list i.fa-arrows-alt { display: none; color: #666; cursor: move; margin-left: auto; } #ccm-block-social-links-list div.form-check:hover i.fa-arrows-alt { display: block; } </style> <script> $(function () { $('#ccm-block-social-links-list').sortable({ axis: 'y' }); }); </script>
mlocati/concrete5
concrete/blocks/social_links/form.php
PHP
mit
2,919
#! /usr/bin/env ruby require 'spec_helper' require 'matchers/json' require 'puppet/util/instrumentation' require 'puppet/util/instrumentation/listener' describe Puppet::Util::Instrumentation::Listener do Listener = Puppet::Util::Instrumentation::Listener before(:each) do @delegate = stub 'listener', :notify => nil, :name => 'listener' @listener = Listener.new(@delegate) @listener.enabled = true end it "should indirect instrumentation_listener" do Listener.indirection.name.should == :instrumentation_listener end it "should raise an error if delegate doesn't support notify" do lambda { Listener.new(Object.new) }.should raise_error end it "should not be enabled by default" do Listener.new(@delegate).should_not be_enabled end it "should delegate notification" do @delegate.expects(:notify).with(:event, :start, {}) listener = Listener.new(@delegate) listener.notify(:event, :start, {}) end it "should not listen is not enabled" do @listener.enabled = false @listener.should_not be_listen_to(:label) end it "should listen to all label if created without pattern" do @listener.should be_listen_to(:improbable_label) end it "should listen to specific string pattern" do listener = Listener.new(@delegate, "specific") listener.enabled = true listener.should be_listen_to(:specific) end it "should not listen to non-matching string pattern" do listener = Listener.new(@delegate, "specific") listener.enabled = true listener.should_not be_listen_to(:unspecific) end it "should listen to specific regex pattern" do listener = Listener.new(@delegate, /spe.*/) listener.enabled = true listener.should be_listen_to(:specific_pattern) end it "should not listen to non matching regex pattern" do listener = Listener.new(@delegate, /^match.*/) listener.enabled = true listener.should_not be_listen_to(:not_matching) end it "should delegate its name to the underlying listener" do @delegate.expects(:name).returns("myname") @listener.name.should == "myname" end it "should delegate data fetching to the underlying listener" do @delegate.expects(:data).returns(:data) @listener.data.should == {:data => :data } end describe "when serializing to pson" do it "should return a pson object containing pattern, name and status" do @listener.should set_json_attribute('enabled').to(true) @listener.should set_json_attribute('name').to("listener") end end describe "when deserializing from pson" do it "should lookup the archetype listener from the instrumentation layer" do Puppet::Util::Instrumentation.expects(:[]).with("listener").returns(@listener) Puppet::Util::Instrumentation::Listener.from_pson({"name" => "listener"}) end it "should create a new listener shell instance delegating to the archetypal listener" do Puppet::Util::Instrumentation.expects(:[]).with("listener").returns(@listener) @listener.stubs(:listener).returns(@delegate) Puppet::Util::Instrumentation::Listener.expects(:new).with(@delegate, nil, true) Puppet::Util::Instrumentation::Listener.from_pson({"name" => "listener", "enabled" => true}) end end end
kieran-bamforth/our-boxen
vendor/bundle/ruby/2.0.0/gems/puppet-3.4.3/spec/unit/util/instrumentation/listener_spec.rb
Ruby
mit
3,283
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreCommon.h" #include "OgreWindowEventUtilities.h" #include "OgreRenderWindow.h" #include "OgreLogManager.h" #include "OgreRoot.h" #include "OgreException.h" #include "OgreStringConverter.h" #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX #include <X11/Xlib.h> void GLXProc( Ogre::RenderWindow *win, const XEvent &event ); #endif //using namespace Ogre; Ogre::WindowEventUtilities::WindowEventListeners Ogre::WindowEventUtilities::_msListeners; Ogre::RenderWindowList Ogre::WindowEventUtilities::_msWindows; namespace Ogre { //--------------------------------------------------------------------------------// void WindowEventUtilities::messagePump() { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 // Windows Message Loop (NULL means check all HWNDs belonging to this context) MSG msg; while( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } #elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX //GLX Message Pump RenderWindowList::iterator win = _msWindows.begin(); RenderWindowList::iterator end = _msWindows.end(); Display* xDisplay = 0; // same for all windows for (; win != end; win++) { XID xid; XEvent event; if (!xDisplay) (*win)->getCustomAttribute("XDISPLAY", &xDisplay); (*win)->getCustomAttribute("WINDOW", &xid); while (XCheckWindowEvent (xDisplay, xid, StructureNotifyMask | VisibilityChangeMask | FocusChangeMask, &event)) { GLXProc(*win, event); } // The ClientMessage event does not appear under any Event Mask while (XCheckTypedWindowEvent (xDisplay, xid, ClientMessage, &event)) { GLXProc(*win, event); } } #elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE && !defined __OBJC__ && !defined __LP64__ // OSX Message Pump EventRef event = NULL; EventTargetRef targetWindow; targetWindow = GetEventDispatcherTarget(); // If we are unable to get the target then we no longer care about events. if( !targetWindow ) return; // Grab the next event, process it if it is a window event while( ReceiveNextEvent( 0, NULL, kEventDurationNoWait, true, &event ) == noErr ) { // Dispatch the event SendEventToEventTarget( event, targetWindow ); ReleaseEvent( event ); } #endif } //--------------------------------------------------------------------------------// void WindowEventUtilities::addWindowEventListener( RenderWindow* window, WindowEventListener* listener ) { _msListeners.insert(std::make_pair(window, listener)); } //--------------------------------------------------------------------------------// void WindowEventUtilities::removeWindowEventListener( RenderWindow* window, WindowEventListener* listener ) { WindowEventListeners::iterator i = _msListeners.begin(), e = _msListeners.end(); for( ; i != e; ++i ) { if( i->first == window && i->second == listener ) { _msListeners.erase(i); break; } } } //--------------------------------------------------------------------------------// void WindowEventUtilities::_addRenderWindow(RenderWindow* window) { _msWindows.push_back(window); } //--------------------------------------------------------------------------------// void WindowEventUtilities::_removeRenderWindow(RenderWindow* window) { RenderWindowList::iterator i = std::find(_msWindows.begin(), _msWindows.end(), window); if( i != _msWindows.end() ) _msWindows.erase( i ); } } #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 //--------------------------------------------------------------------------------// namespace Ogre { LRESULT CALLBACK WindowEventUtilities::_WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (uMsg == WM_CREATE) { // Store pointer to Win32Window in user data area SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)(((LPCREATESTRUCT)lParam)->lpCreateParams)); return 0; } // look up window instance // note: it is possible to get a WM_SIZE before WM_CREATE RenderWindow* win = (RenderWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA); if (!win) return DefWindowProc(hWnd, uMsg, wParam, lParam); //LogManager* log = LogManager::getSingletonPtr(); //Iterator of all listeners registered to this RenderWindow WindowEventListeners::iterator index, start = _msListeners.lower_bound(win), end = _msListeners.upper_bound(win); switch( uMsg ) { case WM_ACTIVATE: { bool active = (LOWORD(wParam) != WA_INACTIVE); if( active ) { win->setActive( true ); } else { if( win->isDeactivatedOnFocusChange() ) { win->setActive( false ); } } for( ; start != end; ++start ) (start->second)->windowFocusChange(win); break; } case WM_SYSKEYDOWN: switch( wParam ) { case VK_CONTROL: case VK_SHIFT: case VK_MENU: //ALT //return zero to bypass defProc and signal we processed the message return 0; } break; case WM_SYSKEYUP: switch( wParam ) { case VK_CONTROL: case VK_SHIFT: case VK_MENU: //ALT case VK_F10: //return zero to bypass defProc and signal we processed the message return 0; } break; case WM_SYSCHAR: // return zero to bypass defProc and signal we processed the message, unless it's an ALT-space if (wParam != VK_SPACE) return 0; break; case WM_ENTERSIZEMOVE: //log->logMessage("WM_ENTERSIZEMOVE"); break; case WM_EXITSIZEMOVE: //log->logMessage("WM_EXITSIZEMOVE"); break; case WM_MOVE: //log->logMessage("WM_MOVE"); win->windowMovedOrResized(); for(index = start; index != end; ++index) (index->second)->windowMoved(win); break; case WM_DISPLAYCHANGE: win->windowMovedOrResized(); for(index = start; index != end; ++index) (index->second)->windowResized(win); break; case WM_SIZE: //log->logMessage("WM_SIZE"); win->windowMovedOrResized(); for(index = start; index != end; ++index) (index->second)->windowResized(win); break; case WM_GETMINMAXINFO: // Prevent the window from going smaller than some minimu size ((MINMAXINFO*)lParam)->ptMinTrackSize.x = 100; ((MINMAXINFO*)lParam)->ptMinTrackSize.y = 100; break; case WM_CLOSE: { //log->logMessage("WM_CLOSE"); bool close = true; for(index = start; index != end; ++index) { if (!(index->second)->windowClosing(win)) close = false; } if (!close) return 0; for(index = _msListeners.lower_bound(win); index != end; ++index) (index->second)->windowClosed(win); win->destroy(); return 0; } } return DefWindowProc( hWnd, uMsg, wParam, lParam ); } } #elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX //--------------------------------------------------------------------------------// void GLXProc( Ogre::RenderWindow *win, const XEvent &event ) { //An iterator for the window listeners Ogre::WindowEventUtilities::WindowEventListeners::iterator index, start = Ogre::WindowEventUtilities::_msListeners.lower_bound(win), end = Ogre::WindowEventUtilities::_msListeners.upper_bound(win); switch(event.type) { case ClientMessage: { ::Atom atom; win->getCustomAttribute("ATOM", &atom); if(event.xclient.format == 32 && event.xclient.data.l[0] == (long)atom) { //Window closed by window manager //Send message first, to allow app chance to unregister things that need done before //window is shutdown bool close = true; for(index = start ; index != end; ++index) { if (!(index->second)->windowClosing(win)) close = false; } if (!close) return; for(index = start ; index != end; ++index) (index->second)->windowClosed(win); win->destroy(); } break; } case DestroyNotify: { if (!win->isClosed()) { // Window closed without window manager warning. for(index = start ; index != end; ++index) (index->second)->windowClosed(win); win->destroy(); } break; } case ConfigureNotify: { // This could be slightly more efficient if windowMovedOrResized took arguments: unsigned int oldWidth, oldHeight, oldDepth; int oldLeft, oldTop; win->getMetrics(oldWidth, oldHeight, oldDepth, oldLeft, oldTop); win->windowMovedOrResized(); unsigned int newWidth, newHeight, newDepth; int newLeft, newTop; win->getMetrics(newWidth, newHeight, newDepth, newLeft, newTop); if (newLeft != oldLeft || newTop != oldTop) { for(index = start ; index != end; ++index) (index->second)->windowMoved(win); } if (newWidth != oldWidth || newHeight != oldHeight) { for(index = start ; index != end; ++index) (index->second)->windowResized(win); } break; } case FocusIn: // Gained keyboard focus case FocusOut: // Lost keyboard focus for(index = start ; index != end; ++index) (index->second)->windowFocusChange(win); break; case MapNotify: //Restored win->setActive( true ); for(index = start ; index != end; ++index) (index->second)->windowFocusChange(win); break; case UnmapNotify: //Minimised win->setActive( false ); win->setVisible( false ); for(index = start ; index != end; ++index) (index->second)->windowFocusChange(win); break; case VisibilityNotify: switch(event.xvisibility.state) { case VisibilityUnobscured: win->setActive( true ); win->setVisible( true ); break; case VisibilityPartiallyObscured: win->setActive( true ); win->setVisible( true ); break; case VisibilityFullyObscured: win->setActive( false ); win->setVisible( false ); break; } for(index = start ; index != end; ++index) (index->second)->windowFocusChange(win); break; default: break; } //End switch event.type } #elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE && !defined __OBJC__ && !defined __LP64__ //--------------------------------------------------------------------------------// namespace Ogre { OSStatus WindowEventUtilities::_CarbonWindowHandler(EventHandlerCallRef nextHandler, EventRef event, void* wnd) { OSStatus status = noErr; // Only events from our window should make it here // This ensures that our user data is our WindowRef RenderWindow* curWindow = (RenderWindow*)wnd; if(!curWindow) return eventNotHandledErr; //Iterator of all listeners registered to this RenderWindow WindowEventListeners::iterator index, start = _msListeners.lower_bound(curWindow), end = _msListeners.upper_bound(curWindow); // We only get called if a window event happens UInt32 eventKind = GetEventKind( event ); switch( eventKind ) { case kEventWindowActivated: curWindow->setActive( true ); for( ; start != end; ++start ) (start->second)->windowFocusChange(curWindow); break; case kEventWindowDeactivated: if( curWindow->isDeactivatedOnFocusChange() ) { curWindow->setActive( false ); } for( ; start != end; ++start ) (start->second)->windowFocusChange(curWindow); break; case kEventWindowShown: case kEventWindowExpanded: curWindow->setActive( true ); curWindow->setVisible( true ); for( ; start != end; ++start ) (start->second)->windowFocusChange(curWindow); break; case kEventWindowHidden: case kEventWindowCollapsed: curWindow->setActive( false ); curWindow->setVisible( false ); for( ; start != end; ++start ) (start->second)->windowFocusChange(curWindow); break; case kEventWindowDragCompleted: curWindow->windowMovedOrResized(); for( ; start != end; ++start ) (start->second)->windowMoved(curWindow); break; case kEventWindowBoundsChanged: curWindow->windowMovedOrResized(); for( ; start != end; ++start ) (start->second)->windowResized(curWindow); break; case kEventWindowClose: { bool close = true; for( ; start != end; ++start ) { if (!(start->second)->windowClosing(curWindow)) close = false; } if (close) // This will cause event handling to continue on to the standard handler, which calls // DisposeWindow(), which leads to the 'kEventWindowClosed' event status = eventNotHandledErr; break; } case kEventWindowClosed: curWindow->destroy(); for( ; start != end; ++start ) (start->second)->windowClosed(curWindow); break; default: status = eventNotHandledErr; break; } return status; } } #endif
uspgamedev/3D-experiment
externals/Ogre/OgreMain/src/OgreWindowEventUtilities.cpp
C++
mit
14,140
#------------------------------------------------------------------------------ # pycparser: c_generator.py # # C code generator from pycparser AST nodes. # # Copyright (C) 2008-2012, Eli Bendersky # License: BSD #------------------------------------------------------------------------------ from . import c_ast class CGenerator(object): """ Uses the same visitor pattern as c_ast.NodeVisitor, but modified to return a value from each visit method, using string accumulation in generic_visit. """ def __init__(self): self.output = '' # Statements start with indentation of self.indent_level spaces, using # the _make_indent method # self.indent_level = 0 def _make_indent(self): return ' ' * self.indent_level def visit(self, node): method = 'visit_' + node.__class__.__name__ return getattr(self, method, self.generic_visit)(node) def generic_visit(self, node): #~ print('generic:', type(node)) if node is None: return '' else: return ''.join(self.visit(c) for c in node.children()) def visit_Constant(self, n): return n.value def visit_ID(self, n): return n.name def visit_ArrayRef(self, n): arrref = self._parenthesize_unless_simple(n.name) return arrref + '[' + self.visit(n.subscript) + ']' def visit_StructRef(self, n): sref = self._parenthesize_unless_simple(n.name) return sref + n.type + self.visit(n.field) def visit_FuncCall(self, n): fref = self._parenthesize_unless_simple(n.name) return fref + '(' + self.visit(n.args) + ')' def visit_UnaryOp(self, n): operand = self._parenthesize_unless_simple(n.expr) if n.op == 'p++': return '%s++' % operand elif n.op == 'p--': return '%s--' % operand elif n.op == 'sizeof': # Always parenthesize the argument of sizeof since it can be # a name. return 'sizeof(%s)' % self.visit(n.expr) else: return '%s%s' % (n.op, operand) def visit_BinaryOp(self, n): lval_str = self._parenthesize_if(n.left, lambda d: not self._is_simple_node(d)) rval_str = self._parenthesize_if(n.right, lambda d: not self._is_simple_node(d)) return '%s %s %s' % (lval_str, n.op, rval_str) def visit_Assignment(self, n): rval_str = self._parenthesize_if( n.rvalue, lambda n: isinstance(n, c_ast.Assignment)) return '%s %s %s' % (self.visit(n.lvalue), n.op, rval_str) def visit_IdentifierType(self, n): return ' '.join(n.names) def visit_Decl(self, n, no_type=False): # no_type is used when a Decl is part of a DeclList, where the type is # explicitly only for the first delaration in a list. # s = n.name if no_type else self._generate_decl(n) if n.bitsize: s += ' : ' + self.visit(n.bitsize) if n.init: if isinstance(n.init, c_ast.InitList): s += ' = {' + self.visit(n.init) + '}' elif isinstance(n.init, c_ast.ExprList): s += ' = (' + self.visit(n.init) + ')' else: s += ' = ' + self.visit(n.init) return s def visit_DeclList(self, n): s = self.visit(n.decls[0]) if len(n.decls) > 1: s += ', ' + ', '.join(self.visit_Decl(decl, no_type=True) for decl in n.decls[1:]) return s def visit_Typedef(self, n): s = '' if n.storage: s += ' '.join(n.storage) + ' ' s += self._generate_type(n.type) return s def visit_Cast(self, n): s = '(' + self._generate_type(n.to_type) + ')' return s + ' ' + self._parenthesize_unless_simple(n.expr) def visit_ExprList(self, n): visited_subexprs = [] for expr in n.exprs: if isinstance(expr, c_ast.ExprList): visited_subexprs.append('{' + self.visit(expr) + '}') else: visited_subexprs.append(self.visit(expr)) return ', '.join(visited_subexprs) def visit_InitList(self, n): visited_subexprs = [] for expr in n.exprs: if isinstance(expr, c_ast.InitList): visited_subexprs.append('(' + self.visit(expr) + ')') else: visited_subexprs.append(self.visit(expr)) return ', '.join(visited_subexprs) def visit_Enum(self, n): s = 'enum' if n.name: s += ' ' + n.name if n.values: s += ' {' for i, enumerator in enumerate(n.values.enumerators): s += enumerator.name if enumerator.value: s += ' = ' + self.visit(enumerator.value) if i != len(n.values.enumerators) - 1: s += ', ' s += '}' return s def visit_FuncDef(self, n): decl = self.visit(n.decl) self.indent_level = 0 body = self.visit(n.body) if n.param_decls: knrdecls = ';\n'.join(self.visit(p) for p in n.param_decls) return decl + '\n' + knrdecls + ';\n' + body + '\n' else: return decl + '\n' + body + '\n' def visit_FileAST(self, n): s = '' for ext in n.ext: if isinstance(ext, c_ast.FuncDef): s += self.visit(ext) else: s += self.visit(ext) + ';\n' return s def visit_Compound(self, n): s = self._make_indent() + '{\n' self.indent_level += 2 if n.block_items: s += ''.join(self._generate_stmt(stmt) for stmt in n.block_items) self.indent_level -= 2 s += self._make_indent() + '}\n' return s def visit_EmptyStatement(self, n): return ';' def visit_ParamList(self, n): return ', '.join(self.visit(param) for param in n.params) def visit_Return(self, n): s = 'return' if n.expr: s += ' ' + self.visit(n.expr) return s + ';' def visit_Break(self, n): return 'break;' def visit_Continue(self, n): return 'continue;' def visit_TernaryOp(self, n): s = self.visit(n.cond) + ' ? ' s += self.visit(n.iftrue) + ' : ' s += self.visit(n.iffalse) return s def visit_If(self, n): s = 'if (' if n.cond: s += self.visit(n.cond) s += ')\n' s += self._generate_stmt(n.iftrue, add_indent=True) if n.iffalse: s += self._make_indent() + 'else\n' s += self._generate_stmt(n.iffalse, add_indent=True) return s def visit_For(self, n): s = 'for (' if n.init: s += self.visit(n.init) s += ';' if n.cond: s += ' ' + self.visit(n.cond) s += ';' if n.next: s += ' ' + self.visit(n.next) s += ')\n' s += self._generate_stmt(n.stmt, add_indent=True) return s def visit_While(self, n): s = 'while (' if n.cond: s += self.visit(n.cond) s += ')\n' s += self._generate_stmt(n.stmt, add_indent=True) return s def visit_DoWhile(self, n): s = 'do\n' s += self._generate_stmt(n.stmt, add_indent=True) s += self._make_indent() + 'while (' if n.cond: s += self.visit(n.cond) s += ');' return s def visit_Switch(self, n): s = 'switch (' + self.visit(n.cond) + ')\n' s += self._generate_stmt(n.stmt, add_indent=True) return s def visit_Case(self, n): s = 'case ' + self.visit(n.expr) + ':\n' for stmt in n.stmts: s += self._generate_stmt(stmt, add_indent=True) return s def visit_Default(self, n): s = 'default:\n' for stmt in n.stmts: s += self._generate_stmt(stmt, add_indent=True) return s def visit_Label(self, n): return n.name + ':\n' + self._generate_stmt(n.stmt) def visit_Goto(self, n): return 'goto ' + n.name + ';' def visit_EllipsisParam(self, n): return '...' def visit_Struct(self, n): return self._generate_struct_union(n, 'struct') def visit_Typename(self, n): return self._generate_type(n.type) def visit_Union(self, n): return self._generate_struct_union(n, 'union') def visit_NamedInitializer(self, n): s = '' for name in n.name: if isinstance(name, c_ast.ID): s += '.' + name.name elif isinstance(name, c_ast.Constant): s += '[' + name.value + ']' s += ' = ' + self.visit(n.expr) return s def _generate_struct_union(self, n, name): """ Generates code for structs and unions. name should be either 'struct' or union. """ s = name + ' ' + (n.name or '') if n.decls: s += '\n' s += self._make_indent() self.indent_level += 2 s += '{\n' for decl in n.decls: s += self._generate_stmt(decl) self.indent_level -= 2 s += self._make_indent() + '}' return s def _generate_stmt(self, n, add_indent=False): """ Generation from a statement node. This method exists as a wrapper for individual visit_* methods to handle different treatment of some statements in this context. """ typ = type(n) if add_indent: self.indent_level += 2 indent = self._make_indent() if add_indent: self.indent_level -= 2 if typ in ( c_ast.Decl, c_ast.Assignment, c_ast.Cast, c_ast.UnaryOp, c_ast.BinaryOp, c_ast.TernaryOp, c_ast.FuncCall, c_ast.ArrayRef, c_ast.StructRef, c_ast.Constant, c_ast.ID, c_ast.Typedef): # These can also appear in an expression context so no semicolon # is added to them automatically # return indent + self.visit(n) + ';\n' elif typ in (c_ast.Compound,): # No extra indentation required before the opening brace of a # compound - because it consists of multiple lines it has to # compute its own indentation. # return self.visit(n) else: return indent + self.visit(n) + '\n' def _generate_decl(self, n): """ Generation from a Decl node. """ s = '' if n.funcspec: s = ' '.join(n.funcspec) + ' ' if n.storage: s += ' '.join(n.storage) + ' ' s += self._generate_type(n.type) return s def _generate_type(self, n, modifiers=[]): """ Recursive generation from a type node. n is the type node. modifiers collects the PtrDecl, ArrayDecl and FuncDecl modifiers encountered on the way down to a TypeDecl, to allow proper generation from it. """ typ = type(n) #~ print(n, modifiers) if typ == c_ast.TypeDecl: s = '' if n.quals: s += ' '.join(n.quals) + ' ' s += self.visit(n.type) nstr = n.declname if n.declname else '' # Resolve modifiers. # Wrap in parens to distinguish pointer to array and pointer to # function syntax. # for i, modifier in enumerate(modifiers): if isinstance(modifier, c_ast.ArrayDecl): if (i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl)): nstr = '(' + nstr + ')' nstr += '[' + self.visit(modifier.dim) + ']' elif isinstance(modifier, c_ast.FuncDecl): if (i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl)): nstr = '(' + nstr + ')' nstr += '(' + self.visit(modifier.args) + ')' elif isinstance(modifier, c_ast.PtrDecl): if modifier.quals: nstr = '* %s %s' % (' '.join(modifier.quals), nstr) else: nstr = '*' + nstr if nstr: s += ' ' + nstr return s elif typ == c_ast.Decl: return self._generate_decl(n.type) elif typ == c_ast.Typename: return self._generate_type(n.type) elif typ == c_ast.IdentifierType: return ' '.join(n.names) + ' ' elif typ in (c_ast.ArrayDecl, c_ast.PtrDecl, c_ast.FuncDecl): return self._generate_type(n.type, modifiers + [n]) else: return self.visit(n) def _parenthesize_if(self, n, condition): """ Visits 'n' and returns its string representation, parenthesized if the condition function applied to the node returns True. """ s = self.visit(n) if condition(n): return '(' + s + ')' else: return s def _parenthesize_unless_simple(self, n): """ Common use case for _parenthesize_if """ return self._parenthesize_if(n, lambda d: not self._is_simple_node(d)) def _is_simple_node(self, n): """ Returns True for nodes that are "simple" - i.e. nodes that always have higher precedence than operators. """ return isinstance(n,( c_ast.Constant, c_ast.ID, c_ast.ArrayRef, c_ast.StructRef, c_ast.FuncCall))
bussiere/pypyjs
website/demo/home/rfk/repos/pypy/lib_pypy/cffi/_pycparser/c_generator.py
Python
mit
13,798
import Ember from 'ember'; import { module, test } from 'qunit'; import startApp from '../../tests/helpers/start-app'; module('Acceptance | navs', { beforeEach() { this.application = startApp(); }, afterEach() { Ember.run(this.application, 'destroy'); } }); test('visiting /navs', function(assert) { visit('/navs'); andThen(function() { assert.equal(currentURL(), '/navs'); }); });
leoeuclids/ember-material-lite
tests/acceptance/navs-test.js
JavaScript
mit
412
<?php namespace N98\Magento\Command\Developer\Theme; use N98\Magento\Command\TestCase; use Symfony\Component\Console\Tester\CommandTester; class ListCommandTest extends TestCase { public function testExecute() { $application = $this->getApplication(); $application->add(new ListCommand()); $command = $this->getApplication()->find('dev:theme:list'); $commandTester = new CommandTester($command); $commandTester->execute( array( 'command' => $command->getName(), ) ); $this->assertContains('base/default', $commandTester->getDisplay()); } }
pocallaghan/n98-magerun
tests/N98/Magento/Command/Developer/Theme/ListCommandTest.php
PHP
mit
653
//===----------------- lib/Jit/options.cpp ----------------------*- C++ -*-===// // // LLILC // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // See LICENSE file in the project root for full license information. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Definition of the Options class that encapsulates JIT options /// extracted from CoreCLR config values. /// //===----------------------------------------------------------------------===// #include "earlyincludes.h" #include "global.h" #include "jitpch.h" #include "LLILCJit.h" #include "jitoptions.h" // Define a macro for cross-platform UTF-16 string literals. #if defined(_MSC_VER) #define UTF16(lit) L##lit #else #define UTF16(lit) u##lit #endif // For now we're always running as the altjit #define ALT_JIT 1 // These are the instantiations of the static method sets in Options.h. // This MethodSets are initialized from CLRConfig values passed through // the corinfo.h interface. MethodSet JitOptions::AltJitMethodSet; MethodSet JitOptions::AltJitNgenMethodSet; MethodSet JitOptions::ExcludeMethodSet; MethodSet JitOptions::BreakMethodSet; MethodSet JitOptions::MSILMethodSet; MethodSet JitOptions::LLVMMethodSet; MethodSet JitOptions::CodeRangeMethodSet; template <typename UTF16CharT> char16_t *getStringConfigValue(ICorJitInfo *CorInfo, const UTF16CharT *Name) { static_assert(sizeof(UTF16CharT) == 2, "UTF16CharT is the wrong size!"); return (char16_t *)LLILCJit::TheJitHost->getStringConfigValue( (const wchar_t *)Name); } template <typename UTF16CharT> void freeStringConfigValue(ICorJitInfo *CorInfo, UTF16CharT *Value) { static_assert(sizeof(UTF16CharT) == 2, "UTF16CharT is the wrong size!"); return LLILCJit::TheJitHost->freeStringConfigValue((wchar_t *)Value); } JitOptions::JitOptions(LLILCJitContext &Context) { // Set 'IsAltJit' based on environment information. IsAltJit = queryIsAltJit(Context); // Set dump level for this JIT invocation. DumpLevel = queryDumpLevel(Context); // Set optimization level for this JIT invocation. OptLevel = queryOptLevel(Context); EnableOptimization = OptLevel != ::OptLevel::DEBUG_CODE; // Set whether to use conservative GC. UseConservativeGC = queryUseConservativeGC(Context); // Set whether to insert statepoints. DoInsertStatepoints = queryDoInsertStatepoints(Context); DoSIMDIntrinsic = queryDoSIMDIntrinsic(Context); // Set whether to do tail call opt. DoTailCallOpt = queryDoTailCallOpt(Context); LogGcInfo = queryLogGcInfo(Context); // Set whether to insert failfast in exception handlers. ExecuteHandlers = queryExecuteHandlers(Context); IsExcludeMethod = queryIsExcludeMethod(Context); IsBreakMethod = queryIsBreakMethod(Context); IsMSILDumpMethod = queryIsMSILDumpMethod(Context); IsLLVMDumpMethod = queryIsLLVMDumpMethod(Context); IsCodeRangeMethod = queryIsCodeRangeMethod(Context); if (IsAltJit) { PreferredIntrinsicSIMDVectorLength = 0; } else { PreferredIntrinsicSIMDVectorLength = 32; } // Validate Statepoint and Conservative GC state. assert(DoInsertStatepoints || UseConservativeGC && "Statepoints required for precise-GC"); } bool JitOptions::queryDoTailCallOpt(LLILCJitContext &Context) { return (bool)DEFAULT_TAIL_CALL_OPT; } bool JitOptions::queryIsAltJit(LLILCJitContext &Context) { // Initial state is that we are not an alternative jit until proven otherwise; bool IsAlternateJit = false; // NDEBUG is !Debug #if !defined(NDEBUG) // DEBUG case // Get/reuse method set that contains the altjit method value. MethodSet *AltJit = nullptr; if (Context.Flags & CORJIT_FLG_PREJIT) { if (!AltJitNgenMethodSet.isInitialized()) { char16_t *NgenStr = getStringConfigValue(Context.JitInfo, UTF16("AltJitNgen")); std::unique_ptr<std::string> NgenUtf8 = Convert::utf16ToUtf8(NgenStr); AltJitNgenMethodSet.init(std::move(NgenUtf8)); freeStringConfigValue(Context.JitInfo, NgenStr); } // Set up AltJitNgen set to be used for AltJit test. AltJit = &AltJitNgenMethodSet; } else { if (!AltJitMethodSet.isInitialized()) { char16_t *JitStr = getStringConfigValue(Context.JitInfo, UTF16("AltJit")); // Move this to the UTIL code and ifdef it for platform std::unique_ptr<std::string> JitUtf8 = Convert::utf16ToUtf8(JitStr); AltJitMethodSet.init(std::move(JitUtf8)); freeStringConfigValue(Context.JitInfo, JitStr); } // Set up AltJit set to be use for AltJit test. AltJit = &AltJitMethodSet; } #ifdef ALT_JIT const char *ClassName = nullptr; const char *MethodName = nullptr; MethodName = Context.JitInfo->getMethodName(Context.MethodInfo->ftn, &ClassName); IsAlternateJit = AltJit->contains(MethodName, ClassName, Context.MethodInfo->args.pSig); #endif // ALT_JIT #else if (Context.Flags & CORJIT_FLG_PREJIT) { char16_t *NgenStr = getStringConfigValue(Context.JitInfo, UTF16("AltJitNgen")); std::unique_ptr<std::string> NgenUtf8 = Convert::utf16ToUtf8(NgenStr); if (NgenUtf8->compare("*") == 0) { IsAlternateJit = true; } } else { char16_t *JitStr = getStringConfigValue(Context.JitInfo, UTF16("AltJit")); std::unique_ptr<std::string> JitUtf8 = Convert::utf16ToUtf8(JitStr); if (JitUtf8->compare("*") == 0) { IsAlternateJit = true; } } #endif return IsAlternateJit; } ::DumpLevel JitOptions::queryDumpLevel(LLILCJitContext &Context) { ::DumpLevel JitDumpLevel = ::DumpLevel::NODUMP; char16_t *LevelWStr = getStringConfigValue(Context.JitInfo, UTF16("DUMPLLVMIR")); if (LevelWStr) { std::unique_ptr<std::string> Level = Convert::utf16ToUtf8(LevelWStr); std::transform(Level->begin(), Level->end(), Level->begin(), ::toupper); if (Level->compare("VERBOSE") == 0) { JitDumpLevel = ::DumpLevel::VERBOSE; } else if (Level->compare("SUMMARY") == 0) { JitDumpLevel = ::DumpLevel::SUMMARY; } } return JitDumpLevel; } bool JitOptions::queryIsExcludeMethod(LLILCJitContext &JitContext) { return queryMethodSet(JitContext, ExcludeMethodSet, (const char16_t *)UTF16("AltJitExclude")); } bool JitOptions::queryIsBreakMethod(LLILCJitContext &JitContext) { return queryMethodSet(JitContext, BreakMethodSet, (const char16_t *)UTF16("AltJitBreakAtJitStart")); } bool JitOptions::queryIsMSILDumpMethod(LLILCJitContext &JitContext) { return queryMethodSet(JitContext, MSILMethodSet, (const char16_t *)UTF16("AltJitMSILDump")); } bool JitOptions::queryIsLLVMDumpMethod(LLILCJitContext &JitContext) { return queryMethodSet(JitContext, LLVMMethodSet, (const char16_t *)UTF16("AltJitLLVMDump")); } bool JitOptions::queryIsCodeRangeMethod(LLILCJitContext &JitContext) { return queryMethodSet(JitContext, CodeRangeMethodSet, (const char16_t *)UTF16("AltJitCodeRangeDump")); } bool JitOptions::queryMethodSet(LLILCJitContext &JitContext, MethodSet &TheSet, const char16_t *Name) { if (!TheSet.isInitialized()) { char16_t *ConfigStr = getStringConfigValue(JitContext.JitInfo, Name); bool NeedFree = true; if (ConfigStr == nullptr) { ConfigStr = const_cast<char16_t *>((const char16_t *)UTF16("")); NeedFree = false; } std::unique_ptr<std::string> ConfigUtf8 = Convert::utf16ToUtf8(ConfigStr); TheSet.init(std::move(ConfigUtf8)); if (NeedFree) { freeStringConfigValue(JitContext.JitInfo, ConfigStr); } } const char *ClassName = nullptr; const char *MethodName = nullptr; MethodName = JitContext.JitInfo->getMethodName(JitContext.MethodInfo->ftn, &ClassName); bool IsInMethodSet = TheSet.contains(MethodName, ClassName, JitContext.MethodInfo->args.pSig); return IsInMethodSet; } bool JitOptions::queryNonNullNonEmpty(LLILCJitContext &JitContext, const char16_t *Name) { char16_t *ConfigStr = getStringConfigValue(JitContext.JitInfo, Name); return (ConfigStr != nullptr) && (*ConfigStr != 0); } // Get the GC-Scheme used by the runtime -- conservative/precise bool JitOptions::queryUseConservativeGC(LLILCJitContext &Context) { return queryNonNullNonEmpty(Context, (const char16_t *)UTF16("gcConservative")); } // Determine if GC statepoints should be inserted. bool JitOptions::queryDoInsertStatepoints(LLILCJitContext &Context) { return queryNonNullNonEmpty(Context, (const char16_t *)UTF16("INSERTSTATEPOINTS")); } // Determine if GCInfo encoding logs should be emitted bool JitOptions::queryLogGcInfo(LLILCJitContext &Context) { return queryNonNullNonEmpty(Context, (const char16_t *)UTF16("JitGCInfoLogging")); } // Determine if exception handlers should be executed. bool JitOptions::queryExecuteHandlers(LLILCJitContext &Context) { return queryNonNullNonEmpty(Context, (const char16_t *)UTF16("ExecuteHandlers")); } // Determine if SIMD intrinsics should be used. bool JitOptions::queryDoSIMDIntrinsic(LLILCJitContext &Context) { return queryNonNullNonEmpty(Context, (const char16_t *)UTF16("SIMDINTRINSIC")); } OptLevel JitOptions::queryOptLevel(LLILCJitContext &Context) { ::OptLevel JitOptLevel = ::OptLevel::BLENDED_CODE; // Currently we only check for the debug flag but this will be extended // to account for further opt levels as we move forward. if ((Context.Flags & CORJIT_FLG_DEBUG_CODE) != 0) { JitOptLevel = ::OptLevel::DEBUG_CODE; } return JitOptLevel; } JitOptions::~JitOptions() {}
dotnet/llilc
lib/Jit/jitoptions.cpp
C++
mit
9,832
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.appservice; import com.fasterxml.jackson.annotation.JsonProperty; /** * Actions which to take by the auto-heal module when a rule is triggered. */ public class AutoHealActions { /** * Predefined action to be taken. Possible values include: 'Recycle', * 'LogEvent', 'CustomAction'. */ @JsonProperty(value = "actionType") private AutoHealActionType actionType; /** * Custom action to be taken. */ @JsonProperty(value = "customAction") private AutoHealCustomAction customAction; /** * Minimum time the process must execute * before taking the action. */ @JsonProperty(value = "minProcessExecutionTime") private String minProcessExecutionTime; /** * Get the actionType value. * * @return the actionType value */ public AutoHealActionType actionType() { return this.actionType; } /** * Set the actionType value. * * @param actionType the actionType value to set * @return the AutoHealActions object itself. */ public AutoHealActions withActionType(AutoHealActionType actionType) { this.actionType = actionType; return this; } /** * Get the customAction value. * * @return the customAction value */ public AutoHealCustomAction customAction() { return this.customAction; } /** * Set the customAction value. * * @param customAction the customAction value to set * @return the AutoHealActions object itself. */ public AutoHealActions withCustomAction(AutoHealCustomAction customAction) { this.customAction = customAction; return this; } /** * Get the minProcessExecutionTime value. * * @return the minProcessExecutionTime value */ public String minProcessExecutionTime() { return this.minProcessExecutionTime; } /** * Set the minProcessExecutionTime value. * * @param minProcessExecutionTime the minProcessExecutionTime value to set * @return the AutoHealActions object itself. */ public AutoHealActions withMinProcessExecutionTime(String minProcessExecutionTime) { this.minProcessExecutionTime = minProcessExecutionTime; return this; } }
jianghaolu/azure-sdk-for-java
azure-mgmt-appservice/src/main/java/com/microsoft/azure/management/appservice/AutoHealActions.java
Java
mit
2,569
using UnityEngine; using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_Bounds : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { LuaDLL.lua_remove(l,1); UnityEngine.Bounds o; if(matchType(l,1,typeof(UnityEngine.Vector3),typeof(UnityEngine.Vector3))){ UnityEngine.Vector3 a1; checkType(l,1,out a1); UnityEngine.Vector3 a2; checkType(l,2,out a2); o=new UnityEngine.Bounds(a1,a2); pushObject(l,o); return 1; } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetMinMax(IntPtr l) { try{ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); UnityEngine.Vector3 a2; checkType(l,3,out a2); self.SetMinMax(a1,a2); setBack(l,self); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Encapsulate(IntPtr l) { try{ if(matchType(l,2,typeof(UnityEngine.Vector3))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); self.Encapsulate(a1); setBack(l,self); return 0; } else if(matchType(l,2,typeof(UnityEngine.Bounds))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Bounds a1; checkType(l,2,out a1); self.Encapsulate(a1); setBack(l,self); return 0; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Expand(IntPtr l) { try{ if(matchType(l,2,typeof(System.Single))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); System.Single a1; checkType(l,2,out a1); self.Expand(a1); setBack(l,self); return 0; } else if(matchType(l,2,typeof(UnityEngine.Vector3))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); self.Expand(a1); setBack(l,self); return 0; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Intersects(IntPtr l) { try{ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Bounds a1; checkType(l,2,out a1); System.Boolean ret=self.Intersects(a1); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Contains(IntPtr l) { try{ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); System.Boolean ret=self.Contains(a1); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SqrDistance(IntPtr l) { try{ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); System.Single ret=self.SqrDistance(a1); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int IntersectRay(IntPtr l) { try{ if(matchType(l,2,typeof(UnityEngine.Ray))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Ray a1; checkType(l,2,out a1); System.Boolean ret=self.IntersectRay(a1); pushValue(l,ret); return 1; } else if(matchType(l,2,typeof(UnityEngine.Ray),typeof(System.Single))){ UnityEngine.Bounds self=checkSelf<UnityEngine.Bounds>(l); UnityEngine.Ray a1; checkType(l,2,out a1); System.Single a2; System.Boolean ret=self.IntersectRay(a1,out a2); pushValue(l,ret); pushValue(l,a2); return 2; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int op_Equality(IntPtr l) { try{ UnityEngine.Bounds a1; checkType(l,1,out a1); UnityEngine.Bounds a2; checkType(l,2,out a2); System.Boolean ret=(a1==a2); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int op_Inequality(IntPtr l) { try{ UnityEngine.Bounds a1; checkType(l,1,out a1); UnityEngine.Bounds a2; checkType(l,2,out a2); System.Boolean ret=(a1!=a2); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_center(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); pushValue(l,o.center); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_center(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 v; checkType(l,2,out v); o.center=v; setBack(l,o); return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_size(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); pushValue(l,o.size); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_size(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 v; checkType(l,2,out v); o.size=v; setBack(l,o); return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_extents(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); pushValue(l,o.extents); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_extents(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 v; checkType(l,2,out v); o.extents=v; setBack(l,o); return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_min(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); pushValue(l,o.min); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_min(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 v; checkType(l,2,out v); o.min=v; setBack(l,o); return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_max(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); pushValue(l,o.max); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_max(IntPtr l) { UnityEngine.Bounds o = checkSelf<UnityEngine.Bounds>(l); UnityEngine.Vector3 v; checkType(l,2,out v); o.max=v; setBack(l,o); return 0; } static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.Bounds"); addMember(l,SetMinMax, "SetMinMax"); addMember(l,Encapsulate, "Encapsulate"); addMember(l,Expand, "Expand"); addMember(l,Intersects, "Intersects"); addMember(l,Contains, "Contains"); addMember(l,SqrDistance, "SqrDistance"); addMember(l,IntersectRay, "IntersectRay"); addMember(l,op_Equality, "op_Equality"); addMember(l,op_Inequality, "op_Inequality"); addMember(l,get_center, "get_center"); addMember(l,set_center, "set_center"); addMember(l,get_size, "get_size"); addMember(l,set_size, "set_size"); addMember(l,get_extents, "get_extents"); addMember(l,set_extents, "set_extents"); addMember(l,get_min, "get_min"); addMember(l,set_min, "set_min"); addMember(l,get_max, "get_max"); addMember(l,set_max, "set_max"); newType(l, constructor); createTypeMetatable(l, typeof(UnityEngine.Bounds)); LuaDLL.lua_pop(l, 1); } }
idada/slua
Assets/Slua/LuaObject/Lua_UnityEngine_Bounds.cs
C#
mit
8,284
namespace OJS.Workers.Checkers.Tests { using System; using NUnit.Framework; [TestFixture] public class CSharpCodeCheckerTests { [Test] [ExpectedException(typeof(InvalidOperationException))] public void CallingCheckMethodBeforeSetParameterShouldThrowAnException() { var checker = new CSharpCodeChecker(); checker.Check(string.Empty, string.Empty, string.Empty, false); } [Test] [ExpectedException(typeof(Exception))] public void SetParameterThrowsExceptionWhenGivenInvalidCode() { var checker = new CSharpCodeChecker(); checker.SetParameter(@"."); } [Test] [ExpectedException(typeof(Exception))] public void SetParameterThrowsExceptionWhenNotGivenICheckerImplementation() { var checker = new CSharpCodeChecker(); checker.SetParameter(@"public class MyChecker { }"); } [Test] [ExpectedException(typeof(Exception))] public void SetParameterThrowsExceptionWhenGivenMoreThanOneICheckerImplementation() { var checker = new CSharpCodeChecker(); checker.SetParameter(@" using OJS.Workers.Common; public class MyChecker1 : IChecker { public CheckerResult Check(string inputData, string receivedOutput, string expectedOutput) { return new CheckerResult { IsCorrect = true, ResultType = CheckerResultType.Ok, CheckerDetails = new CheckerDetails(), }; } public void SetParameter(string parameter) { } } public class MyChecker2 : IChecker { public CheckerResult Check(string inputData, string receivedOutput, string expectedOutput) { return new CheckerResult { IsCorrect = true, ResultType = CheckerResultType.Ok, CheckerDetails = new CheckerDetails(), }; } public void SetParameter(string parameter) { } }"); } [Test] public void CheckMethodWorksCorrectlyWithSomeCheckerCode() { var checker = new CSharpCodeChecker(); checker.SetParameter(@" using OJS.Workers.Common; public class MyChecker : IChecker { public CheckerResult Check(string inputData, string receivedOutput, string expectedOutput, bool isTrialTest) { return new CheckerResult { IsCorrect = true, ResultType = CheckerResultType.Ok, CheckerDetails = new CheckerDetails { Comment = ""It was me"" }, }; } public void SetParameter(string parameter) { } }"); var checkerResult = checker.Check(string.Empty, string.Empty, string.Empty, false); Assert.IsNotNull(checkerResult); Assert.IsTrue(checkerResult.IsCorrect); Assert.AreEqual("It was me", checkerResult.CheckerDetails.Comment); } [Test] public void CheckMethodReceivesCorrectParameters() { var checker = new CSharpCodeChecker(); checker.SetParameter(@" using OJS.Workers.Common; public class MyChecker : IChecker { public CheckerResult Check(string inputData, string receivedOutput, string expectedOutput, bool isTrialTest) { bool isCorrect = true; if (inputData != ""One"") isCorrect = false; if (receivedOutput != ""Two"") isCorrect = false; if (expectedOutput != ""Three"") isCorrect = false; return new CheckerResult { IsCorrect = isCorrect, ResultType = CheckerResultType.Ok, CheckerDetails = new CheckerDetails(), }; } public void SetParameter(string parameter) { } }"); var checkerResult = checker.Check("One", "Two", "Three", false); Assert.IsNotNull(checkerResult); Assert.IsTrue(checkerResult.IsCorrect); } } }
nakov/OpenJudgeSystem
Open Judge System/Tests/OJS.Workers.Checkers.Tests/CSharpCodeCheckerTests.cs
C#
mit
5,295
/*! * screenfull * v4.2.0 - 2019-04-01 * (c) Sindre Sorhus; MIT License */ (function () { 'use strict'; var document = typeof window !== 'undefined' && typeof window.document !== 'undefined' ? window.document : {}; var isCommonjs = typeof module !== 'undefined' && module.exports; var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element; var fn = (function () { var val; var fnMap = [ [ 'requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror' ], // New WebKit [ 'webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror' ], // Old WebKit (Safari 5.1) [ 'webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror' ], [ 'mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror' ], [ 'msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError' ] ]; var i = 0; var l = fnMap.length; var ret = {}; for (; i < l; i++) { val = fnMap[i]; if (val && val[1] in document) { for (i = 0; i < val.length; i++) { ret[fnMap[0][i]] = val[i]; } return ret; } } return false; })(); var eventNameMap = { change: fn.fullscreenchange, error: fn.fullscreenerror }; var screenfull = { request: function (elem) { return new Promise(function (resolve) { var request = fn.requestFullscreen; var onFullScreenEntered = function () { this.off('change', onFullScreenEntered); resolve(); }.bind(this); elem = elem || document.documentElement; // Work around Safari 5.1 bug: reports support for // keyboard in fullscreen even though it doesn't. // Browser sniffing, since the alternative with // setTimeout is even worse. if (/ Version\/5\.1(?:\.\d+)? Safari\//.test(navigator.userAgent)) { elem[request](); } else { elem[request](keyboardAllowed ? Element.ALLOW_KEYBOARD_INPUT : {}); } this.on('change', onFullScreenEntered); }.bind(this)); }, exit: function () { return new Promise(function (resolve) { if (!this.isFullscreen) { resolve(); return; } var onFullScreenExit = function () { this.off('change', onFullScreenExit); resolve(); }.bind(this); document[fn.exitFullscreen](); this.on('change', onFullScreenExit); }.bind(this)); }, toggle: function (elem) { return this.isFullscreen ? this.exit() : this.request(elem); }, onchange: function (callback) { this.on('change', callback); }, onerror: function (callback) { this.on('error', callback); }, on: function (event, callback) { var eventName = eventNameMap[event]; if (eventName) { document.addEventListener(eventName, callback, false); } }, off: function (event, callback) { var eventName = eventNameMap[event]; if (eventName) { document.removeEventListener(eventName, callback, false); } }, raw: fn }; if (!fn) { if (isCommonjs) { module.exports = false; } else { window.screenfull = false; } return; } Object.defineProperties(screenfull, { isFullscreen: { get: function () { return Boolean(document[fn.fullscreenElement]); } }, element: { enumerable: true, get: function () { return document[fn.fullscreenElement]; } }, enabled: { enumerable: true, get: function () { // Coerce to boolean in case of old WebKit return Boolean(document[fn.fullscreenEnabled]); } } }); if (isCommonjs) { module.exports = screenfull; // TODO: remove this in the next major version module.exports.default = screenfull; } else { window.screenfull = screenfull; } })();
quindar/quindar-ux
public/scripts/screenfull.js
JavaScript
mit
4,129
class ExitStatus < Spinach::FeatureSteps feature "Exit status" include Integration::SpinachRunner Given "I have a feature that has no error or failure" do @feature = Integration::FeatureGenerator.success_feature end Given "I have a feature that has a failure" do @feature = Integration::FeatureGenerator.failure_feature end When "I run it" do run_feature @feature end Then "the exit status should be 0" do @last_exit_status.success?.must_equal true end Then "the exit status should be 1" do @last_exit_status.success?.must_equal false end end
alkuzad/spinach
features/steps/exit_status.rb
Ruby
mit
594
require 'rails/version' require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator' module Rails module Generators class StrongParametersControllerGenerator < ScaffoldControllerGenerator argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" source_root File.expand_path("../templates", __FILE__) if ::Rails::VERSION::STRING < '3.1' def module_namespacing yield if block_given? end end end end end
begriffs/strong_parameters
lib/generators/rails/strong_parameters_controller_generator.rb
Ruby
mit
520
/* ==================================================================== 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 org.apache.poi.hssf.usermodel; /** * Represents a simple shape such as a line, rectangle or oval. * * @author Glen Stampoultzis (glens at apache.org) */ public class HSSFSimpleShape extends HSSFShape { // The commented out ones haven't been tested yet or aren't supported // by HSSFSimpleShape. public final static short OBJECT_TYPE_LINE = 1; public final static short OBJECT_TYPE_RECTANGLE = 2; public final static short OBJECT_TYPE_OVAL = 3; // public final static short OBJECT_TYPE_ARC = 4; // public final static short OBJECT_TYPE_CHART = 5; // public final static short OBJECT_TYPE_TEXT = 6; // public final static short OBJECT_TYPE_BUTTON = 7; public final static short OBJECT_TYPE_PICTURE = 8; // public final static short OBJECT_TYPE_POLYGON = 9; // public final static short OBJECT_TYPE_CHECKBOX = 11; // public final static short OBJECT_TYPE_OPTION_BUTTON = 12; // public final static short OBJECT_TYPE_EDIT_BOX = 13; // public final static short OBJECT_TYPE_LABEL = 14; // public final static short OBJECT_TYPE_DIALOG_BOX = 15; // public final static short OBJECT_TYPE_SPINNER = 16; // public final static short OBJECT_TYPE_SCROLL_BAR = 17; // public final static short OBJECT_TYPE_LIST_BOX = 18; // public final static short OBJECT_TYPE_GROUP_BOX = 19; // public final static short OBJECT_TYPE_COMBO_BOX = 20; public final static short OBJECT_TYPE_COMMENT = 25; // public final static short OBJECT_TYPE_MICROSOFT_OFFICE_DRAWING = 30; int shapeType = OBJECT_TYPE_LINE; HSSFSimpleShape( HSSFShape parent, HSSFAnchor anchor ) { super( parent, anchor ); } /** * Gets the shape type. * @return One of the OBJECT_TYPE_* constants. * * @see #OBJECT_TYPE_LINE * @see #OBJECT_TYPE_OVAL * @see #OBJECT_TYPE_RECTANGLE * @see #OBJECT_TYPE_PICTURE * @see #OBJECT_TYPE_COMMENT */ public int getShapeType() { return shapeType; } /** * Sets the shape types. * * @param shapeType One of the OBJECT_TYPE_* constants. * * @see #OBJECT_TYPE_LINE * @see #OBJECT_TYPE_OVAL * @see #OBJECT_TYPE_RECTANGLE * @see #OBJECT_TYPE_PICTURE * @see #OBJECT_TYPE_COMMENT */ public void setShapeType( int shapeType ){ this.shapeType = shapeType; } }
tobyclemson/msci-project
vendor/poi-3.6/src/java/org/apache/poi/hssf/usermodel/HSSFSimpleShape.java
Java
mit
3,641
var stub = require('./fixtures/stub'), constants = require('./../constants'), Logger = require('./fixtures/stub_logger'), utils = require('./../utils'); // huge hack here, but plugin tests need constants constants.import(global); function _set_up(callback) { this.backup = {}; callback(); } function _tear_down(callback) { callback(); } exports.utils = { setUp : _set_up, tearDown : _tear_down, 'plain ascii should not be encoded' : function (test) { test.expect(1); test.equals(utils.encode_qp('quoted printable'), 'quoted printable'); test.done(); }, '8-bit chars should be encoded' : function (test) { test.expect(1); test.equals( utils.encode_qp( 'v\xe5re kj\xe6re norske tegn b\xf8r \xe6res' ), 'v=E5re kj=E6re norske tegn b=F8r =E6res'); test.done(); }, 'trailing space should be encoded' : function (test) { test.expect(5); test.equals(utils.encode_qp(' '), '=20=20'); test.equals(utils.encode_qp('\tt\t'), '\tt=09'); test.equals( utils.encode_qp('test \ntest\n\t \t \n'), 'test=20=20\ntest\n=09=20=09=20\n' ); test.equals(utils.encode_qp("foo \t "), "foo=20=09=20"); test.equals(utils.encode_qp("foo\t \n \t"), "foo=09=20\n=20=09"); test.done(); }, 'trailing space should be decoded unless newline' : function (test) { test.expect(2); test.deepEqual(utils.decode_qp("foo "), new Buffer("foo ")); test.deepEqual(utils.decode_qp("foo \n"), new Buffer("foo\n")); test.done(); }, '"=" is special and should be decoded' : function (test) { test.expect(2); test.equals(utils.encode_qp("=30\n"), "=3D30\n"); test.equals(utils.encode_qp("\0\xff0"), "=00=FF0"); test.done(); }, 'Very long lines should be broken' : function (test) { test.expect(1); test.equals(utils.encode_qp("The Quoted-Printable encoding is intended to represent data that largly consists of octets that correspond to printable characters in the ASCII character set."), "The Quoted-Printable encoding is intended to represent data that largly con=\nsists of octets that correspond to printable characters in the ASCII charac=\nter set."); test.done(); }, 'multiple long lines' : function (test) { test.expect(1); test.equals(utils.encode_qp("College football is a game which would be much more interesting if the faculty played instead of the students, and even more interesting if the\ntrustees played. There would be a great increase in broken arms, legs, and necks, and simultaneously an appreciable diminution in the loss to humanity. -- H. L. Mencken"), "College football is a game which would be much more interesting if the facu=\nlty played instead of the students, and even more interesting if the\ntrustees played. There would be a great increase in broken arms, legs, and=\n necks, and simultaneously an appreciable diminution in the loss to humanit=\ny. -- H. L. Mencken"); test.done(); }, "Don't break a line that's near but not over 76 chars" : function (test) { var buffer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + "xxxxxxxxxxxxxxxxxx"; test.equals(utils.encode_qp(buffer+"123"), buffer+"123"); test.equals(utils.encode_qp(buffer+"1234"), buffer+"1234"); test.equals(utils.encode_qp(buffer+"12345"), buffer+"12345"); test.equals(utils.encode_qp(buffer+"123456"), buffer+"123456"); test.equals(utils.encode_qp(buffer+"1234567"), buffer+"12345=\n67"); test.equals(utils.encode_qp(buffer+"123456="), buffer+"12345=\n6=3D"); test.equals(utils.encode_qp(buffer+"123\n"), buffer+"123\n"); test.equals(utils.encode_qp(buffer+"1234\n"), buffer+"1234\n"); test.equals(utils.encode_qp(buffer+"12345\n"), buffer+"12345\n"); test.equals(utils.encode_qp(buffer+"123456\n"), buffer+"123456\n"); test.equals(utils.encode_qp(buffer+"1234567\n"), buffer+"12345=\n67\n"); test.equals( utils.encode_qp(buffer+"123456=\n"), buffer+"12345=\n6=3D\n" ); test.done(); }, 'Not allowed to break =XX escapes using soft line break' : function (test) { test.expect(10); var buffer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + "xxxxxxxxxxxxxxxxxx"; test.equals( utils.encode_qp(buffer+"===xxxxx"), buffer+"=3D=\n=3D=3Dxxxxx" ); test.equals( utils.encode_qp(buffer+"1===xxxx"), buffer+"1=3D=\n=3D=3Dxxxx" ); test.equals( utils.encode_qp(buffer+"12===xxx"), buffer+"12=3D=\n=3D=3Dxxx" ); test.equals( utils.encode_qp(buffer+"123===xx"), buffer+"123=\n=3D=3D=3Dxx" ); test.equals( utils.encode_qp(buffer+"1234===x"), buffer+"1234=\n=3D=3D=3Dx" ); test.equals(utils.encode_qp(buffer+"12=\n"), buffer+"12=3D\n"); test.equals(utils.encode_qp(buffer+"123=\n"), buffer+"123=\n=3D\n"); test.equals(utils.encode_qp(buffer+"1234=\n"), buffer+"1234=\n=3D\n"); test.equals(utils.encode_qp(buffer+"12345=\n"), buffer+"12345=\n=3D\n"); test.equals( utils.encode_qp(buffer+"123456=\n"), buffer+"12345=\n6=3D\n" ); test.done(); }, 'some extra special cases we have had problems with' : function (test) { test.expect(2); var buffer = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + "xxxxxxxxxxxxxxxxxx"; test.equals(utils.encode_qp(buffer+"12=x=x"), buffer+"12=3D=\nx=3Dx"); test.equals( utils.encode_qp(buffer+"12345"+buffer+"12345"+buffer+"123456\n"), buffer+"12345=\n"+buffer+"12345=\n"+buffer+"123456\n" ); test.done(); }, 'regression test 01' : function (test) { test.expect(1); test.deepEqual( utils.decode_qp("foo \n\nfoo =\n\nfoo=20\n\n"), new Buffer("foo\n\nfoo \nfoo \n\n") ); test.done(); }, 'regression test 01 with CRLF' : function (test) { test.expect(1); test.deepEqual( utils.decode_qp("foo \r\n\r\nfoo =\r\n\r\nfoo=20\r\n\r\n"), new Buffer("foo\n\nfoo \nfoo \n\n") ); test.done(); }, 'regression test 02' : function (test) { test.expect(1); test.deepEqual( utils.decode_qp("foo = \t\x20\nbar\t\x20\n"), new Buffer("foo bar\n") ); test.done(); }, 'regression test 02 with CRLF' : function (test) { test.expect(1); test.deepEqual( utils.decode_qp("foo = \t\x20\r\nbar\t\x20\r\n"), new Buffer("foo bar\n") ); test.done(); }, 'regression test 03' : function (test) { test.expect(1); test.deepEqual( utils.decode_qp("foo = \t\x20\n"), new Buffer("foo ") ); test.done(); }, 'regression test 03 with CRLF' : function (test) { test.expect(1); test.deepEqual( utils.decode_qp("foo = \t\x20\r\n"), new Buffer("foo ") ); test.done(); }, 'regression test 04 from CRLF to LF' : function (test) { test.expect(1); test.deepEqual( utils.decode_qp("foo = \t\x20y\r\n"), new Buffer("foo = \t\x20y\n") ); test.done(); }, 'regression test 05 should be the same' : function (test) { test.expect(1); test.deepEqual( utils.decode_qp("foo =xy\n"), new Buffer("foo =xy\n") ); test.done(); }, 'spin encode_qp()' : function (test) { var spin = 10000; test.expect(spin); for (var i = 0; i < spin; i++) { test.equals( utils.encode_qp("quoted printable"), "quoted printable" ); } test.done(); } }; exports.valid_regexes = { setUp : _set_up, tearDown : _tear_down, 'two valid': function (test) { var re_list = ['.*\.exam.ple','.*\.example.com']; test.expect(1); test.deepEqual(re_list, utils.valid_regexes(re_list)); test.done(); }, 'one valid, one invalid': function (test) { var re_list = ['*\.exam.ple','.*\.example.com']; test.expect(1); test.deepEqual(['.*\.example.com'], utils.valid_regexes(re_list)); test.done(); }, 'one valid, two invalid': function (test) { var re_list = ['[', '*\.exam.ple','.*\.example.com']; test.expect(1); test.deepEqual(['.*\.example.com'], utils.valid_regexes(re_list)); test.done(); }, }; exports.base64 = { setUp : _set_up, tearDown : _tear_down, 'base64': function (test) { test.expect(1); test.equal(utils.base64('matt the tester'), 'bWF0dCB0aGUgdGVzdGVy'); test.done(); }, 'unbase64': function (test) { test.expect(1); test.equal(utils.unbase64('bWF0dCB0aGUgdGVzdGVy'), 'matt the tester'); test.done(); } }; exports.to_object = { setUp : _set_up, tearDown : _tear_down, 'string': function (test) { test.expect(1); test.deepEqual(utils.to_object('matt,test'), { matt: true, test: true } ); test.done(); }, 'array': function (test) { test.expect(1); test.deepEqual(utils.to_object(['matt','test']), { matt: true, test: true } ); test.done(); }, }; exports.extend = { 'copies properties from one object': function (test) { test.expect(1); var both = utils.extend({first: 'boo'}, {second: 'ger'}); test.deepEqual({first: 'boo', second: 'ger'}, both); test.done(); }, 'copies properties from multiple objects': function (test) { test.expect(1); test.deepEqual( utils.extend( {first: 'boo'}, {second: 'ger'}, {third: 'eat'} ), {first: 'boo', second: 'ger', third: 'eat'} ); test.done(); }, }; exports.node_min = { 'node is new enough': function (test) { test.expect(6); test.ok(utils.node_min('0.8.0', '0.10.0')); test.ok(utils.node_min('0.10.0', '0.10.0')); test.ok(utils.node_min('0.10.0', '0.10.1')); test.ok(utils.node_min('0.10.0', '0.12.0')); test.ok(utils.node_min('0.10.0', '1.0.0')); test.ok(utils.node_min('0.10', '1.0')); test.done(); }, 'node is too old': function (test) { test.expect(4); test.ok(!utils.node_min('0.12.0', '0.10.0')); test.ok(!utils.node_min('1.0.0', '0.8.0')); test.ok(!utils.node_min('1.0.0', '0.10.0')); test.ok(!utils.node_min('1.0.0', '0.12.0')); test.done(); }, }; exports.elapsed = { 'returns 0 decimal places': function (test) { test.expect(1); var start = new Date(); start.setTime(start.getTime() - 3517); // 3.517 seconds ago test.strictEqual(utils.elapsed(start, 0), '4'); test.done(); }, 'returns 1 decimal place': function (test) { test.expect(1); var start = new Date(); start.setTime(start.getTime() - 3517); // 3.517 seconds ago test.strictEqual(utils.elapsed(start, 1), '3.5'); test.done(); }, 'returns 2 decimal places': function (test) { test.expect(1); var start = new Date(); start.setTime(start.getTime() - 3517); // 3.517 seconds ago test.strictEqual(utils.elapsed(start, 2), '3.52'); test.done(); }, 'default N > 5 has 0 decimal places': function (test) { test.expect(1); var start = new Date(); start.setTime(start.getTime() - 13517); // 3.517 seconds ago test.strictEqual(utils.elapsed(start), '14'); test.done(); }, 'default N > 2 has 1 decimal places': function (test) { test.expect(1); var start = new Date(); start.setTime(start.getTime() - 3517); // 3.517 seconds ago test.strictEqual(utils.elapsed(start), '3.5'); test.done(); }, 'default has 2 decimal places': function (test) { test.expect(1); var start = new Date(); start.setTime(start.getTime() - 1517); // 3.517 seconds ago test.strictEqual(utils.elapsed(start), '1.52'); test.done(); }, };
jjz/Haraka
tests/utils.js
JavaScript
mit
12,700
// Generated by LiveScript 1.5.0 var onmessage, this$ = this; function addEventListener(event, cb){ return this.thread.on(event, cb); } function close(){ return this.thread.emit('close'); } function importScripts(){ var i$, len$, p, results$ = []; for (i$ = 0, len$ = (arguments).length; i$ < len$; ++i$) { p = (arguments)[i$]; results$.push(self.eval(native_fs_.readFileSync(p, 'utf8'))); } return results$; } onmessage = null; thread.on('message', function(args){ return typeof onmessage == 'function' ? onmessage(args) : void 8; });
romainmnr/chatboteseo
node_modules/webworker-threads/src/load.js
JavaScript
mit
558
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * 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@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Form * @subpackage Decorator * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\Form\Decorator\Captcha; use Zend\Form\Decorator\AbstractDecorator; /** * Word-based captcha decorator * * Adds hidden field for ID and text input field for captcha text * * @uses \Zend\Form\Decorator\AbstractDecorator * @category Zend * @package Zend_Form * @subpackage Element * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Word extends AbstractDecorator { /** * Render captcha * * @param string $content * @return string */ public function render($content) { $element = $this->getElement(); $view = $element->getView(); if (null === $view) { return $content; } $name = $element->getFullyQualifiedName(); $hiddenName = $name . '[id]'; $textName = $name . '[input]'; $label = $element->getDecorator("Label"); if($label) { $label->setOption("id", $element->getId()."-input"); } $placement = $this->getPlacement(); $separator = $this->getSeparator(); $hidden = $view->formHidden($hiddenName, $element->getValue(), $element->getAttribs()); $text = $view->formText($textName, '', $element->getAttribs()); switch ($placement) { case 'PREPEND': $content = $hidden . $separator . $text . $separator . $content; break; case 'APPEND': default: $content = $content . $separator . $hidden . $separator . $text; } return $content; } }
phphatesme/LiveTest
src/lib/Zend/Form/Decorator/Captcha/Word.php
PHP
mit
2,410
package com.laytonsmith.abstraction.entities; import com.laytonsmith.abstraction.MCEntity; import com.laytonsmith.abstraction.MCLivingEntity; public interface MCEvokerFangs extends MCEntity { MCLivingEntity getOwner(); void setOwner(MCLivingEntity owner); }
sk89q/CommandHelper
src/main/java/com/laytonsmith/abstraction/entities/MCEvokerFangs.java
Java
mit
262
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Translation\Catalogue\MergeOperation; use Symfony\Component\Translation\DataCollectorTranslator; use Symfony\Component\Translation\Extractor\ExtractorInterface; use Symfony\Component\Translation\LoggingTranslator; use Symfony\Component\Translation\MessageCatalogue; use Symfony\Component\Translation\Reader\TranslationReaderInterface; use Symfony\Component\Translation\Translator; use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Helps finding unused or missing translation messages in a given locale * and comparing them with the fallback ones. * * @author Florian Voutzinos <florian@voutzinos.com> * * @final */ class TranslationDebugCommand extends Command { const MESSAGE_MISSING = 0; const MESSAGE_UNUSED = 1; const MESSAGE_EQUALS_FALLBACK = 2; protected static $defaultName = 'debug:translation'; private $translator; private $reader; private $extractor; private $defaultTransPath; private $defaultViewsPath; private $transPaths; private $viewsPaths; /** * @param TranslatorInterface $translator */ public function __construct($translator, TranslationReaderInterface $reader, ExtractorInterface $extractor, string $defaultTransPath = null, string $defaultViewsPath = null, array $transPaths = [], array $viewsPaths = []) { if (!$translator instanceof LegacyTranslatorInterface && !$translator instanceof TranslatorInterface) { throw new \TypeError(sprintf('Argument 1 passed to %s() must be an instance of %s, %s given.', __METHOD__, TranslatorInterface::class, \is_object($translator) ? \get_class($translator) : \gettype($translator))); } parent::__construct(); $this->translator = $translator; $this->reader = $reader; $this->extractor = $extractor; $this->defaultTransPath = $defaultTransPath; $this->defaultViewsPath = $defaultViewsPath; $this->transPaths = $transPaths; $this->viewsPaths = $viewsPaths; } /** * {@inheritdoc} */ protected function configure() { $this ->setDefinition([ new InputArgument('locale', InputArgument::REQUIRED, 'The locale'), new InputArgument('bundle', InputArgument::OPTIONAL, 'The bundle name or directory where to load the messages'), new InputOption('domain', null, InputOption::VALUE_OPTIONAL, 'The messages domain'), new InputOption('only-missing', null, InputOption::VALUE_NONE, 'Displays only missing messages'), new InputOption('only-unused', null, InputOption::VALUE_NONE, 'Displays only unused messages'), new InputOption('all', null, InputOption::VALUE_NONE, 'Load messages from all registered bundles'), ]) ->setDescription('Displays translation messages information') ->setHelp(<<<'EOF' The <info>%command.name%</info> command helps finding unused or missing translation messages and comparing them with the fallback ones by inspecting the templates and translation files of a given bundle or the default translations directory. You can display information about bundle translations in a specific locale: <info>php %command.full_name% en AcmeDemoBundle</info> You can also specify a translation domain for the search: <info>php %command.full_name% --domain=messages en AcmeDemoBundle</info> You can only display missing messages: <info>php %command.full_name% --only-missing en AcmeDemoBundle</info> You can only display unused messages: <info>php %command.full_name% --only-unused en AcmeDemoBundle</info> You can display information about application translations in a specific locale: <info>php %command.full_name% en</info> You can display information about translations in all registered bundles in a specific locale: <info>php %command.full_name% --all en</info> EOF ) ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $locale = $input->getArgument('locale'); $domain = $input->getOption('domain'); /** @var KernelInterface $kernel */ $kernel = $this->getApplication()->getKernel(); $rootDir = $kernel->getContainer()->getParameter('kernel.root_dir'); // Define Root Paths $transPaths = $this->transPaths; if (is_dir($dir = $rootDir.'/Resources/translations')) { if ($dir !== $this->defaultTransPath) { $notice = sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, ', $dir); @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); } $transPaths[] = $dir; } if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } $viewsPaths = $this->viewsPaths; if (is_dir($dir = $rootDir.'/Resources/views')) { if ($dir !== $this->defaultViewsPath) { $notice = sprintf('Loading Twig templates from the "%s" directory is deprecated since Symfony 4.2, ', $dir); @trigger_error($notice.($this->defaultViewsPath ? sprintf('use the "%s" directory instead.', $this->defaultViewsPath) : 'configure and use "twig.default_path" instead.'), E_USER_DEPRECATED); } $viewsPaths[] = $dir; } if ($this->defaultViewsPath) { $viewsPaths[] = $this->defaultViewsPath; } // Override with provided Bundle info if (null !== $input->getArgument('bundle')) { try { $bundle = $kernel->getBundle($input->getArgument('bundle')); $transPaths = [$bundle->getPath().'/Resources/translations']; if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } if (is_dir($dir = sprintf('%s/Resources/%s/translations', $rootDir, $bundle->getName()))) { $transPaths[] = $dir; $notice = sprintf('Storing translations files for "%s" in the "%s" directory is deprecated since Symfony 4.2, ', $dir, $bundle->getName()); @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); } $viewsPaths = [$bundle->getPath().'/Resources/views']; if ($this->defaultViewsPath) { $viewsPaths[] = $this->defaultViewsPath; } if (is_dir($dir = sprintf('%s/Resources/%s/views', $rootDir, $bundle->getName()))) { $viewsPaths[] = $dir; $notice = sprintf('Loading Twig templates for "%s" from the "%s" directory is deprecated since Symfony 4.2, ', $bundle->getName(), $dir); @trigger_error($notice.($this->defaultViewsPath ? sprintf('use the "%s" directory instead.', $this->defaultViewsPath) : 'configure and use "twig.default_path" instead.'), E_USER_DEPRECATED); } } catch (\InvalidArgumentException $e) { // such a bundle does not exist, so treat the argument as path $path = $input->getArgument('bundle'); $transPaths = [$path.'/translations']; if (is_dir($dir = $path.'/Resources/translations')) { if ($dir !== $this->defaultTransPath) { @trigger_error(sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/translations'), E_USER_DEPRECATED); } $transPaths[] = $dir; } $viewsPaths = [$path.'/templates']; if (is_dir($dir = $path.'/Resources/views')) { if ($dir !== $this->defaultViewsPath) { @trigger_error(sprintf('Loading Twig templates from the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/templates'), E_USER_DEPRECATED); } $viewsPaths[] = $dir; } if (!is_dir($transPaths[0]) && !isset($transPaths[1])) { throw new InvalidArgumentException(sprintf('"%s" is neither an enabled bundle nor a directory.', $transPaths[0])); } } } elseif ($input->getOption('all')) { foreach ($kernel->getBundles() as $bundle) { $transPaths[] = $bundle->getPath().'/Resources/translations'; if (is_dir($deprecatedPath = sprintf('%s/Resources/%s/translations', $rootDir, $bundle->getName()))) { $transPaths[] = $deprecatedPath; $notice = sprintf('Storing translations files for "%s" in the "%s" directory is deprecated since Symfony 4.2, ', $bundle->getName(), $deprecatedPath); @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); } $viewsPaths[] = $bundle->getPath().'/Resources/views'; if (is_dir($deprecatedPath = sprintf('%s/Resources/%s/views', $rootDir, $bundle->getName()))) { $viewsPaths[] = $deprecatedPath; $notice = sprintf('Loading Twig templates for "%s" from the "%s" directory is deprecated since Symfony 4.2, ', $bundle->getName(), $deprecatedPath); @trigger_error($notice.($this->defaultViewsPath ? sprintf('use the "%s" directory instead.', $this->defaultViewsPath) : 'configure and use "twig.default_path" instead.'), E_USER_DEPRECATED); } } } // Extract used messages $extractedCatalogue = $this->extractMessages($locale, $viewsPaths); // Load defined messages $currentCatalogue = $this->loadCurrentMessages($locale, $transPaths); // Merge defined and extracted messages to get all message ids $mergeOperation = new MergeOperation($extractedCatalogue, $currentCatalogue); $allMessages = $mergeOperation->getResult()->all($domain); if (null !== $domain) { $allMessages = [$domain => $allMessages]; } // No defined or extracted messages if (empty($allMessages) || null !== $domain && empty($allMessages[$domain])) { $outputMessage = sprintf('No defined or extracted messages for locale "%s"', $locale); if (null !== $domain) { $outputMessage .= sprintf(' and domain "%s"', $domain); } $io->getErrorStyle()->warning($outputMessage); return; } // Load the fallback catalogues $fallbackCatalogues = $this->loadFallbackCatalogues($locale, $transPaths); // Display header line $headers = ['State', 'Domain', 'Id', sprintf('Message Preview (%s)', $locale)]; foreach ($fallbackCatalogues as $fallbackCatalogue) { $headers[] = sprintf('Fallback Message Preview (%s)', $fallbackCatalogue->getLocale()); } $rows = []; // Iterate all message ids and determine their state foreach ($allMessages as $domain => $messages) { foreach (array_keys($messages) as $messageId) { $value = $currentCatalogue->get($messageId, $domain); $states = []; if ($extractedCatalogue->defines($messageId, $domain)) { if (!$currentCatalogue->defines($messageId, $domain)) { $states[] = self::MESSAGE_MISSING; } } elseif ($currentCatalogue->defines($messageId, $domain)) { $states[] = self::MESSAGE_UNUSED; } if (!\in_array(self::MESSAGE_UNUSED, $states) && true === $input->getOption('only-unused') || !\in_array(self::MESSAGE_MISSING, $states) && true === $input->getOption('only-missing')) { continue; } foreach ($fallbackCatalogues as $fallbackCatalogue) { if ($fallbackCatalogue->defines($messageId, $domain) && $value === $fallbackCatalogue->get($messageId, $domain)) { $states[] = self::MESSAGE_EQUALS_FALLBACK; break; } } $row = [$this->formatStates($states), $domain, $this->formatId($messageId), $this->sanitizeString($value)]; foreach ($fallbackCatalogues as $fallbackCatalogue) { $row[] = $this->sanitizeString($fallbackCatalogue->get($messageId, $domain)); } $rows[] = $row; } } $io->table($headers, $rows); } private function formatState($state): string { if (self::MESSAGE_MISSING === $state) { return '<error> missing </error>'; } if (self::MESSAGE_UNUSED === $state) { return '<comment> unused </comment>'; } if (self::MESSAGE_EQUALS_FALLBACK === $state) { return '<info> fallback </info>'; } return $state; } private function formatStates(array $states): string { $result = []; foreach ($states as $state) { $result[] = $this->formatState($state); } return implode(' ', $result); } private function formatId(string $id): string { return sprintf('<fg=cyan;options=bold>%s</>', $id); } private function sanitizeString(string $string, int $length = 40): string { $string = trim(preg_replace('/\s+/', ' ', $string)); if (false !== $encoding = mb_detect_encoding($string, null, true)) { if (mb_strlen($string, $encoding) > $length) { return mb_substr($string, 0, $length - 3, $encoding).'...'; } } elseif (\strlen($string) > $length) { return substr($string, 0, $length - 3).'...'; } return $string; } private function extractMessages(string $locale, array $transPaths): MessageCatalogue { $extractedCatalogue = new MessageCatalogue($locale); foreach ($transPaths as $path) { if (is_dir($path) || is_file($path)) { $this->extractor->extract($path, $extractedCatalogue); } } return $extractedCatalogue; } private function loadCurrentMessages(string $locale, array $transPaths): MessageCatalogue { $currentCatalogue = new MessageCatalogue($locale); foreach ($transPaths as $path) { if (is_dir($path)) { $this->reader->read($path, $currentCatalogue); } } return $currentCatalogue; } /** * @return MessageCatalogue[] */ private function loadFallbackCatalogues(string $locale, array $transPaths): array { $fallbackCatalogues = []; if ($this->translator instanceof Translator || $this->translator instanceof DataCollectorTranslator || $this->translator instanceof LoggingTranslator) { foreach ($this->translator->getFallbackLocales() as $fallbackLocale) { if ($fallbackLocale === $locale) { continue; } $fallbackCatalogue = new MessageCatalogue($fallbackLocale); foreach ($transPaths as $path) { if (is_dir($path)) { $this->reader->read($path, $fallbackCatalogue); } } $fallbackCatalogues[] = $fallbackCatalogue; } } return $fallbackCatalogues; } }
curry684/symfony
src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php
PHP
mit
17,092
module.exports = { "env": { "browser": true }, "plugins": [ "callback-function" ], "globals": { "_": true, "$": true, "ActErr": true, "async": true, "config": true, "logger": true, "moment": true, "respondWithError": true, "sendJSONResponse": true, "util": true, "admiral": true }, "extends": "airbnb-base/legacy", "rules": { // rules to override from airbnb/legacy "object-curly-spacing": ["error", "never"], "curly": ["error", "multi", "consistent"], "no-param-reassign": ["error", { "props": false }], "no-underscore-dangle": ["error", { "allow": ["_r", "_p"] }], "quote-props": ["error", "consistent-as-needed"], // rules from airbnb that we won't be using "consistent-return": 0, "default-case": 0, "func-names": 0, "no-plusplus": 0, "no-use-before-define": 0, "vars-on-top": 0, "no-loop-func": 0, "no-underscore-dangle": 0, "no-param-reassign": 0, "one-var-declaration-per-line": 0, "one-var": 0, "no-multi-assign": 0, "global-require": 0, // extra rules not present in airbnb "max-len": ["error", 80], } };
himanshu0503/admiral
.eslintrc.js
JavaScript
mit
1,174
// // Copyright (c) 2008-2011, Kenneth Bell // // 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. // namespace DiscUtils.Vmdk { using System; using System.IO; using System.IO.Compression; /// <summary> /// Represents and extent from a sparse disk from 'hosted' software (VMware Workstation, etc). /// </summary> /// <remarks>Hosted disks and server disks (ESX, etc) are subtly different formats.</remarks> internal sealed class HostedSparseExtentStream : CommonSparseExtentStream { private HostedSparseExtentHeader _hostedHeader; public HostedSparseExtentStream(Stream file, Ownership ownsFile, long diskOffset, SparseStream parentDiskStream, Ownership ownsParentDiskStream) { _fileStream = file; _ownsFileStream = ownsFile; _diskOffset = diskOffset; _parentDiskStream = parentDiskStream; _ownsParentDiskStream = ownsParentDiskStream; file.Position = 0; byte[] headerSector = Utilities.ReadFully(file, Sizes.Sector); _hostedHeader = HostedSparseExtentHeader.Read(headerSector, 0); if (_hostedHeader.GdOffset == -1) { // Fall back to secondary copy that (should) be at the end of the stream, just before the end-of-stream sector marker file.Position = file.Length - Sizes.OneKiB; headerSector = Utilities.ReadFully(file, Sizes.Sector); _hostedHeader = HostedSparseExtentHeader.Read(headerSector, 0); if (_hostedHeader.MagicNumber != HostedSparseExtentHeader.VmdkMagicNumber) { throw new IOException("Unable to locate valid VMDK header or footer"); } } _header = _hostedHeader; if (_hostedHeader.CompressAlgorithm != 0 && _hostedHeader.CompressAlgorithm != 1) { throw new NotSupportedException("Only uncompressed and DEFLATE compressed disks supported"); } _gtCoverage = _header.NumGTEsPerGT * _header.GrainSize * Sizes.Sector; LoadGlobalDirectory(); } public override bool CanWrite { get { // No write support for streamOptimized disks return _fileStream.CanWrite && (_hostedHeader.Flags & (HostedSparseExtentFlags.CompressedGrains | HostedSparseExtentFlags.MarkersInUse)) == 0; } } public override void Write(byte[] buffer, int offset, int count) { CheckDisposed(); if (!CanWrite) { throw new InvalidOperationException("Cannot write to this stream"); } if (_position + count > Length) { throw new IOException("Attempt to write beyond end of stream"); } int totalWritten = 0; while (totalWritten < count) { int grainTable = (int)(_position / _gtCoverage); int grainTableOffset = (int)(_position - (grainTable * _gtCoverage)); LoadGrainTable(grainTable); int grainSize = (int)(_header.GrainSize * Sizes.Sector); int grain = grainTableOffset / grainSize; int grainOffset = grainTableOffset - (grain * grainSize); if (GetGrainTableEntry(grain) == 0) { AllocateGrain(grainTable, grain); } int numToWrite = Math.Min(count - totalWritten, grainSize - grainOffset); _fileStream.Position = (((long)GetGrainTableEntry(grain)) * Sizes.Sector) + grainOffset; _fileStream.Write(buffer, offset + totalWritten, numToWrite); _position += numToWrite; totalWritten += numToWrite; } _atEof = _position == Length; } protected override int ReadGrain(byte[] buffer, int bufferOffset, long grainStart, int grainOffset, int numToRead) { if ((_hostedHeader.Flags & HostedSparseExtentFlags.CompressedGrains) != 0) { _fileStream.Position = grainStart; byte[] readBuffer = Utilities.ReadFully(_fileStream, CompressedGrainHeader.Size); CompressedGrainHeader hdr = new CompressedGrainHeader(); hdr.Read(readBuffer, 0); readBuffer = Utilities.ReadFully(_fileStream, hdr.DataSize); // This is really a zlib stream, so has header and footer. We ignore this right now, but we sanity // check against expected header values... ushort header = Utilities.ToUInt16BigEndian(readBuffer, 0); if ((header % 31) != 0) { throw new IOException("Invalid ZLib header found"); } if ((header & 0x0F00) != (8 << 8)) { throw new NotSupportedException("ZLib compression not using DEFLATE algorithm"); } if ((header & 0x0020) != 0) { throw new NotSupportedException("ZLib compression using preset dictionary"); } Stream readStream = new MemoryStream(readBuffer, 2, hdr.DataSize - 2, false); DeflateStream deflateStream = new DeflateStream(readStream, CompressionMode.Decompress); // Need to skip some bytes, but DefaultStream doesn't support seeking... Utilities.ReadFully(deflateStream, grainOffset); return deflateStream.Read(buffer, bufferOffset, numToRead); } else { return base.ReadGrain(buffer, bufferOffset, grainStart, grainOffset, numToRead); } } protected override StreamExtent MapGrain(long grainStart, int grainOffset, int numToRead) { if ((_hostedHeader.Flags & HostedSparseExtentFlags.CompressedGrains) != 0) { _fileStream.Position = grainStart; byte[] readBuffer = Utilities.ReadFully(_fileStream, CompressedGrainHeader.Size); CompressedGrainHeader hdr = new CompressedGrainHeader(); hdr.Read(readBuffer, 0); return new StreamExtent(grainStart + grainOffset, CompressedGrainHeader.Size + hdr.DataSize); } else { return base.MapGrain(grainStart, grainOffset, numToRead); } } protected override void LoadGlobalDirectory() { base.LoadGlobalDirectory(); if ((_hostedHeader.Flags & HostedSparseExtentFlags.RedundantGrainTable) != 0) { int numGTs = (int)Utilities.Ceil(_header.Capacity * Sizes.Sector, _gtCoverage); _redundantGlobalDirectory = new uint[numGTs]; _fileStream.Position = _hostedHeader.RgdOffset * Sizes.Sector; byte[] gdAsBytes = Utilities.ReadFully(_fileStream, numGTs * 4); for (int i = 0; i < _globalDirectory.Length; ++i) { _redundantGlobalDirectory[i] = Utilities.ToUInt32LittleEndian(gdAsBytes, i * 4); } } } private void AllocateGrain(int grainTable, int grain) { // Calculate start pos for new grain long grainStartPos = Utilities.RoundUp(_fileStream.Length, _header.GrainSize * Sizes.Sector); // Copy-on-write semantics, read the bytes from parent and write them out to this extent. _parentDiskStream.Position = _diskOffset + ((grain + (_header.NumGTEsPerGT * (long)grainTable)) * _header.GrainSize * Sizes.Sector); byte[] content = Utilities.ReadFully(_parentDiskStream, (int)_header.GrainSize * Sizes.Sector); _fileStream.Position = grainStartPos; _fileStream.Write(content, 0, content.Length); LoadGrainTable(grainTable); SetGrainTableEntry(grain, (uint)(grainStartPos / Sizes.Sector)); WriteGrainTable(); } private void WriteGrainTable() { if (_grainTable == null) { throw new InvalidOperationException("No grain table loaded"); } _fileStream.Position = _globalDirectory[_currentGrainTable] * (long)Sizes.Sector; _fileStream.Write(_grainTable, 0, _grainTable.Length); if (_redundantGlobalDirectory != null) { _fileStream.Position = _redundantGlobalDirectory[_currentGrainTable] * (long)Sizes.Sector; _fileStream.Write(_grainTable, 0, _grainTable.Length); } } } }
breezechen/DiscUtils
src/Vmdk/HostedSparseExtentStream.cs
C#
mit
10,139
<?php return [ 'Names' => [ 'Africa/Abidjan' => 'Waktu Greenwich (Abidjan)', 'Africa/Accra' => 'Waktu Greenwich (Accra)', 'Africa/Algiers' => 'Waktu Éropa Tengah (Algiers)', 'Africa/Bamako' => 'Waktu Greenwich (Bamako)', 'Africa/Banjul' => 'Waktu Greenwich (Banjul)', 'Africa/Bissau' => 'Waktu Greenwich (Bissau)', 'Africa/Cairo' => 'Waktu Éropa Timur (Cairo)', 'Africa/Casablanca' => 'Waktu Éropa Barat (Casablanca)', 'Africa/Ceuta' => 'Waktu Éropa Tengah (Ceuta)', 'Africa/Conakry' => 'Waktu Greenwich (Conakry)', 'Africa/Dakar' => 'Waktu Greenwich (Dakar)', 'Africa/El_Aaiun' => 'Waktu Éropa Barat (El Aaiun)', 'Africa/Freetown' => 'Waktu Greenwich (Freetown)', 'Africa/Lome' => 'Waktu Greenwich (Lome)', 'Africa/Monrovia' => 'Waktu Greenwich (Monrovia)', 'Africa/Nouakchott' => 'Waktu Greenwich (Nouakchott)', 'Africa/Ouagadougou' => 'Waktu Greenwich (Ouagadougou)', 'Africa/Sao_Tome' => 'Waktu Greenwich (Sao Tome)', 'Africa/Tripoli' => 'Waktu Éropa Timur (Tripoli)', 'Africa/Tunis' => 'Waktu Éropa Tengah (Tunis)', 'America/Adak' => 'Amérika Sarikat (Adak)', 'America/Anchorage' => 'Amérika Sarikat (Anchorage)', 'America/Anguilla' => 'Waktu Atlantik (Anguilla)', 'America/Antigua' => 'Waktu Atlantik (Antigua)', 'America/Araguaina' => 'Brasil (Araguaina)', 'America/Aruba' => 'Waktu Atlantik (Aruba)', 'America/Bahia' => 'Brasil (Bahia)', 'America/Bahia_Banderas' => 'Waktu Tengah (Bahia Banderas)', 'America/Barbados' => 'Waktu Atlantik (Barbados)', 'America/Belem' => 'Brasil (Belem)', 'America/Belize' => 'Waktu Tengah (Belize)', 'America/Blanc-Sablon' => 'Waktu Atlantik (Blanc-Sablon)', 'America/Boa_Vista' => 'Brasil (Boa Vista)', 'America/Bogota' => 'Waktu Kolombia (Bogota)', 'America/Boise' => 'Waktu Pagunungan (Boise)', 'America/Cambridge_Bay' => 'Waktu Pagunungan (Cambridge Bay)', 'America/Campo_Grande' => 'Brasil (Campo Grande)', 'America/Cancun' => 'Waktu Wétan (Cancun)', 'America/Cayman' => 'Waktu Wétan (Cayman)', 'America/Chicago' => 'Waktu Tengah (Chicago)', 'America/Coral_Harbour' => 'Waktu Wétan (Atikokan)', 'America/Costa_Rica' => 'Waktu Tengah (Costa Rica)', 'America/Creston' => 'Waktu Pagunungan (Creston)', 'America/Cuiaba' => 'Brasil (Cuiaba)', 'America/Curacao' => 'Waktu Atlantik (Curacao)', 'America/Danmarkshavn' => 'Waktu Greenwich (Danmarkshavn)', 'America/Dawson' => 'Waktu Pagunungan (Dawson)', 'America/Dawson_Creek' => 'Waktu Pagunungan (Dawson Creek)', 'America/Denver' => 'Waktu Pagunungan (Denver)', 'America/Detroit' => 'Waktu Wétan (Detroit)', 'America/Dominica' => 'Waktu Atlantik (Dominica)', 'America/Edmonton' => 'Waktu Pagunungan (Edmonton)', 'America/Eirunepe' => 'Brasil (Eirunepe)', 'America/El_Salvador' => 'Waktu Tengah (El Salvador)', 'America/Fort_Nelson' => 'Waktu Pagunungan (Fort Nelson)', 'America/Fortaleza' => 'Brasil (Fortaleza)', 'America/Glace_Bay' => 'Waktu Atlantik (Glace Bay)', 'America/Goose_Bay' => 'Waktu Atlantik (Goose Bay)', 'America/Grand_Turk' => 'Waktu Wétan (Grand Turk)', 'America/Grenada' => 'Waktu Atlantik (Grenada)', 'America/Guadeloupe' => 'Waktu Atlantik (Guadeloupe)', 'America/Guatemala' => 'Waktu Tengah (Guatemala)', 'America/Halifax' => 'Waktu Atlantik (Halifax)', 'America/Indiana/Knox' => 'Waktu Tengah (Knox, Indiana)', 'America/Indiana/Marengo' => 'Waktu Wétan (Marengo, Indiana)', 'America/Indiana/Petersburg' => 'Waktu Wétan (Petersburg, Indiana)', 'America/Indiana/Tell_City' => 'Waktu Tengah (Tell City, Indiana)', 'America/Indiana/Vevay' => 'Waktu Wétan (Vevay, Indiana)', 'America/Indiana/Vincennes' => 'Waktu Wétan (Vincennes, Indiana)', 'America/Indiana/Winamac' => 'Waktu Wétan (Winamac, Indiana)', 'America/Indianapolis' => 'Waktu Wétan (Indianapolis)', 'America/Inuvik' => 'Waktu Pagunungan (Inuvik)', 'America/Iqaluit' => 'Waktu Wétan (Iqaluit)', 'America/Jamaica' => 'Waktu Wétan (Jamaica)', 'America/Juneau' => 'Amérika Sarikat (Juneau)', 'America/Kentucky/Monticello' => 'Waktu Wétan (Monticello, Kentucky)', 'America/Kralendijk' => 'Waktu Atlantik (Kralendijk)', 'America/Los_Angeles' => 'Waktu Pasifik (Los Angeles)', 'America/Louisville' => 'Waktu Wétan (Louisville)', 'America/Lower_Princes' => 'Waktu Atlantik (Lower Prince’s Quarter)', 'America/Maceio' => 'Brasil (Maceio)', 'America/Managua' => 'Waktu Tengah (Managua)', 'America/Manaus' => 'Brasil (Manaus)', 'America/Marigot' => 'Waktu Atlantik (Marigot)', 'America/Martinique' => 'Waktu Atlantik (Martinique)', 'America/Matamoros' => 'Waktu Tengah (Matamoros)', 'America/Menominee' => 'Waktu Tengah (Menominee)', 'America/Merida' => 'Waktu Tengah (Merida)', 'America/Metlakatla' => 'Amérika Sarikat (Metlakatla)', 'America/Mexico_City' => 'Waktu Tengah (Mexico City)', 'America/Moncton' => 'Waktu Atlantik (Moncton)', 'America/Monterrey' => 'Waktu Tengah (Monterrey)', 'America/Montserrat' => 'Waktu Atlantik (Montserrat)', 'America/Nassau' => 'Waktu Wétan (Nassau)', 'America/New_York' => 'Waktu Wétan (New York)', 'America/Nipigon' => 'Waktu Wétan (Nipigon)', 'America/Nome' => 'Amérika Sarikat (Nome)', 'America/Noronha' => 'Brasil (Noronha)', 'America/North_Dakota/Beulah' => 'Waktu Tengah (Beulah, North Dakota)', 'America/North_Dakota/Center' => 'Waktu Tengah (Center, North Dakota)', 'America/North_Dakota/New_Salem' => 'Waktu Tengah (New Salem, North Dakota)', 'America/Ojinaga' => 'Waktu Pagunungan (Ojinaga)', 'America/Panama' => 'Waktu Wétan (Panama)', 'America/Pangnirtung' => 'Waktu Wétan (Pangnirtung)', 'America/Phoenix' => 'Waktu Pagunungan (Phoenix)', 'America/Port-au-Prince' => 'Waktu Wétan (Port-au-Prince)', 'America/Port_of_Spain' => 'Waktu Atlantik (Port of Spain)', 'America/Porto_Velho' => 'Brasil (Porto Velho)', 'America/Puerto_Rico' => 'Waktu Atlantik (Puerto Rico)', 'America/Rainy_River' => 'Waktu Tengah (Rainy River)', 'America/Rankin_Inlet' => 'Waktu Tengah (Rankin Inlet)', 'America/Recife' => 'Brasil (Recife)', 'America/Regina' => 'Waktu Tengah (Regina)', 'America/Resolute' => 'Waktu Tengah (Resolute)', 'America/Rio_Branco' => 'Brasil (Rio Branco)', 'America/Santarem' => 'Brasil (Santarem)', 'America/Santo_Domingo' => 'Waktu Atlantik (Santo Domingo)', 'America/Sao_Paulo' => 'Brasil (Sao Paulo)', 'America/Sitka' => 'Amérika Sarikat (Sitka)', 'America/St_Barthelemy' => 'Waktu Atlantik (St. Barthelemy)', 'America/St_Kitts' => 'Waktu Atlantik (St. Kitts)', 'America/St_Lucia' => 'Waktu Atlantik (St. Lucia)', 'America/St_Thomas' => 'Waktu Atlantik (St. Thomas)', 'America/St_Vincent' => 'Waktu Atlantik (St. Vincent)', 'America/Swift_Current' => 'Waktu Tengah (Swift Current)', 'America/Tegucigalpa' => 'Waktu Tengah (Tegucigalpa)', 'America/Thule' => 'Waktu Atlantik (Thule)', 'America/Thunder_Bay' => 'Waktu Wétan (Thunder Bay)', 'America/Tijuana' => 'Waktu Pasifik (Tijuana)', 'America/Toronto' => 'Waktu Wétan (Toronto)', 'America/Tortola' => 'Waktu Atlantik (Tortola)', 'America/Vancouver' => 'Waktu Pasifik (Vancouver)', 'America/Whitehorse' => 'Waktu Pagunungan (Whitehorse)', 'America/Winnipeg' => 'Waktu Tengah (Winnipeg)', 'America/Yakutat' => 'Amérika Sarikat (Yakutat)', 'America/Yellowknife' => 'Waktu Pagunungan (Yellowknife)', 'Antarctica/Troll' => 'Waktu Greenwich (Troll)', 'Arctic/Longyearbyen' => 'Waktu Éropa Tengah (Longyearbyen)', 'Asia/Amman' => 'Waktu Éropa Timur (Amman)', 'Asia/Anadyr' => 'Rusia (Anadyr)', 'Asia/Barnaul' => 'Rusia (Barnaul)', 'Asia/Beirut' => 'Waktu Éropa Timur (Beirut)', 'Asia/Calcutta' => 'India (Kolkata)', 'Asia/Chita' => 'Rusia (Chita)', 'Asia/Damascus' => 'Waktu Éropa Timur (Damascus)', 'Asia/Famagusta' => 'Waktu Éropa Timur (Famagusta)', 'Asia/Gaza' => 'Waktu Éropa Timur (Gaza)', 'Asia/Hebron' => 'Waktu Éropa Timur (Hebron)', 'Asia/Irkutsk' => 'Rusia (Irkutsk)', 'Asia/Kamchatka' => 'Rusia (Kamchatka)', 'Asia/Khandyga' => 'Rusia (Khandyga)', 'Asia/Krasnoyarsk' => 'Rusia (Krasnoyarsk)', 'Asia/Magadan' => 'Rusia (Magadan)', 'Asia/Nicosia' => 'Waktu Éropa Timur (Nicosia)', 'Asia/Novokuznetsk' => 'Rusia (Novokuznetsk)', 'Asia/Novosibirsk' => 'Rusia (Novosibirsk)', 'Asia/Omsk' => 'Rusia (Omsk)', 'Asia/Sakhalin' => 'Rusia (Sakhalin)', 'Asia/Shanghai' => 'Tiongkok (Shanghai)', 'Asia/Srednekolymsk' => 'Rusia (Srednekolymsk)', 'Asia/Tokyo' => 'Jepang (Tokyo)', 'Asia/Tomsk' => 'Rusia (Tomsk)', 'Asia/Urumqi' => 'Tiongkok (Urumqi)', 'Asia/Ust-Nera' => 'Rusia (Ust-Nera)', 'Asia/Vladivostok' => 'Rusia (Vladivostok)', 'Asia/Yakutsk' => 'Rusia (Yakutsk)', 'Asia/Yekaterinburg' => 'Rusia (Yekaterinburg)', 'Atlantic/Bermuda' => 'Waktu Atlantik (Bermuda)', 'Atlantic/Canary' => 'Waktu Éropa Barat (Canary)', 'Atlantic/Faeroe' => 'Waktu Éropa Barat (Faroe)', 'Atlantic/Madeira' => 'Waktu Éropa Barat (Madeira)', 'Atlantic/Reykjavik' => 'Waktu Greenwich (Reykjavik)', 'Atlantic/St_Helena' => 'Waktu Greenwich (St. Helena)', 'CST6CDT' => 'Waktu Tengah', 'EST5EDT' => 'Waktu Wétan', 'Etc/GMT' => 'Waktu Greenwich', 'Etc/UTC' => 'Waktu Universal Terkoordinasi', 'Europe/Amsterdam' => 'Waktu Éropa Tengah (Amsterdam)', 'Europe/Andorra' => 'Waktu Éropa Tengah (Andorra)', 'Europe/Astrakhan' => 'Rusia (Astrakhan)', 'Europe/Athens' => 'Waktu Éropa Timur (Athens)', 'Europe/Belgrade' => 'Waktu Éropa Tengah (Belgrade)', 'Europe/Berlin' => 'Waktu Éropa Tengah (Berlin)', 'Europe/Bratislava' => 'Waktu Éropa Tengah (Bratislava)', 'Europe/Brussels' => 'Waktu Éropa Tengah (Brussels)', 'Europe/Bucharest' => 'Waktu Éropa Timur (Bucharest)', 'Europe/Budapest' => 'Waktu Éropa Tengah (Budapest)', 'Europe/Busingen' => 'Waktu Éropa Tengah (Busingen)', 'Europe/Chisinau' => 'Waktu Éropa Timur (Chisinau)', 'Europe/Copenhagen' => 'Waktu Éropa Tengah (Copenhagen)', 'Europe/Dublin' => 'Waktu Greenwich (Dublin)', 'Europe/Gibraltar' => 'Waktu Éropa Tengah (Gibraltar)', 'Europe/Guernsey' => 'Waktu Greenwich (Guernsey)', 'Europe/Helsinki' => 'Waktu Éropa Timur (Helsinki)', 'Europe/Isle_of_Man' => 'Waktu Greenwich (Isle of Man)', 'Europe/Jersey' => 'Waktu Greenwich (Jersey)', 'Europe/Kaliningrad' => 'Waktu Éropa Timur (Kaliningrad)', 'Europe/Kiev' => 'Waktu Éropa Timur (Kiev)', 'Europe/Kirov' => 'Rusia (Kirov)', 'Europe/Lisbon' => 'Waktu Éropa Barat (Lisbon)', 'Europe/Ljubljana' => 'Waktu Éropa Tengah (Ljubljana)', 'Europe/London' => 'Waktu Greenwich (London)', 'Europe/Luxembourg' => 'Waktu Éropa Tengah (Luxembourg)', 'Europe/Madrid' => 'Waktu Éropa Tengah (Madrid)', 'Europe/Malta' => 'Waktu Éropa Tengah (Malta)', 'Europe/Mariehamn' => 'Waktu Éropa Timur (Mariehamn)', 'Europe/Monaco' => 'Waktu Éropa Tengah (Monaco)', 'Europe/Moscow' => 'Rusia (Moscow)', 'Europe/Oslo' => 'Waktu Éropa Tengah (Oslo)', 'Europe/Paris' => 'Waktu Éropa Tengah (Paris)', 'Europe/Podgorica' => 'Waktu Éropa Tengah (Podgorica)', 'Europe/Prague' => 'Waktu Éropa Tengah (Prague)', 'Europe/Riga' => 'Waktu Éropa Timur (Riga)', 'Europe/Rome' => 'Waktu Éropa Tengah (Rome)', 'Europe/Samara' => 'Rusia (Samara)', 'Europe/San_Marino' => 'Waktu Éropa Tengah (San Marino)', 'Europe/Sarajevo' => 'Waktu Éropa Tengah (Sarajevo)', 'Europe/Saratov' => 'Rusia (Saratov)', 'Europe/Skopje' => 'Waktu Éropa Tengah (Skopje)', 'Europe/Sofia' => 'Waktu Éropa Timur (Sofia)', 'Europe/Stockholm' => 'Waktu Éropa Tengah (Stockholm)', 'Europe/Tallinn' => 'Waktu Éropa Timur (Tallinn)', 'Europe/Tirane' => 'Waktu Éropa Tengah (Tirane)', 'Europe/Ulyanovsk' => 'Rusia (Ulyanovsk)', 'Europe/Uzhgorod' => 'Waktu Éropa Timur (Uzhgorod)', 'Europe/Vaduz' => 'Waktu Éropa Tengah (Vaduz)', 'Europe/Vatican' => 'Waktu Éropa Tengah (Vatican)', 'Europe/Vienna' => 'Waktu Éropa Tengah (Vienna)', 'Europe/Vilnius' => 'Waktu Éropa Timur (Vilnius)', 'Europe/Volgograd' => 'Rusia (Volgograd)', 'Europe/Warsaw' => 'Waktu Éropa Tengah (Warsaw)', 'Europe/Zagreb' => 'Waktu Éropa Tengah (Zagreb)', 'Europe/Zaporozhye' => 'Waktu Éropa Timur (Zaporozhye)', 'Europe/Zurich' => 'Waktu Éropa Tengah (Zurich)', 'MST7MDT' => 'Waktu Pagunungan', 'PST8PDT' => 'Waktu Pasifik', 'Pacific/Galapagos' => 'Waktu Galapagos', 'Pacific/Honolulu' => 'Amérika Sarikat (Honolulu)', ], 'Meta' => [ ], ];
Slamdunk/symfony
src/Symfony/Component/Intl/Resources/data/timezones/su.php
PHP
mit
13,893
// textarea‚̍‚‚³‚ðƒ‰ƒCƒu’²ß‚·‚é function adjustTextareaRows(obj, org, plus) { var brlen = null; if (obj.wrap) { if (obj.wrap == 'virtual' || obj.wrap == 'soft') { brlen = obj.cols; } } var aLen = countLines(obj.value, brlen); var aRows = aLen + plus; var move = 0; var scroll = 14; if (org) { if (Math.max(aRows, obj.rows) > org) { move = Math.abs((aRows - obj.rows) * scroll); if (move) { obj.rows = Math.max(org, aRows); window.scrollBy(0, move); } } /* if (aRows > org + plus) { if (obj.rows < aRows) { move = (aRows - obj.rows) * scroll; } else if (obj.rows > aRows) { move = (aRows - obj.rows) * -scroll; } if (move != 0) { if (move < 0) { window.scrollBy(0, move); } obj.rows = aRows; if (move > 0) { window.scrollBy(0, move); } } } */ } else if (obj.rows < aRows) { move = (aRows - obj.rows) * scroll; obj.rows = aRows; window.scrollBy(0, move); } } /** * \n ‚ð‰üs‚Æ‚µ‚čs”‚𐔂¦‚é * * @param integer brlen ‰üs‚·‚é•¶Žš”B–³Žw’è‚È‚ç•¶Žš”‚ʼnüs‚µ‚È‚¢ */ function countLines(str, brlen) { var lines = str.split("\n"); var count = lines.length; var aLen = 0; for (var i = 0; i < lines.length; i++) { aLen = jstrlen(lines[i]); if (brlen) { var adjust = 1.15; // ’PŒê’PˆÊ‚̐܂è•Ô‚µ‚ɑΉž‚µ‚Ä‚¢‚È‚¢‚̂ŃAƒoƒEƒg’²® if ((aLen * adjust) > brlen) { count = count + Math.floor((aLen * adjust) / brlen); } } } return count; } // •¶Žš—ñ‚ðƒoƒCƒg”‚Ő”‚¦‚é function jstrlen(str) { var len = 0; str = escape(str); for (var i = 0; i < str.length; i++, len++) { if (str.charAt(i) == "%") { if (str.charAt(++i) == "u") { i += 3; len++; } i++; } } return len; } // (‘Ώۂªdisable‚łȂ¯‚ê‚Î) ƒtƒH[ƒJƒX‚ð‡‚í‚¹‚é function setFocus(ID){ var obj; if (obj = document.getElementById(ID)) { if (obj.disabled != true) { obj.focus(); } } } // sageƒ`ƒFƒbƒN‚ɍ‡‚킹‚āAƒ[ƒ‹—“‚Ì“à—e‚ð‘‚«Š·‚¦‚é function mailSage(){ var mailran, cbsage; if (cbsage = document.getElementById('sage')) { if (mailran = document.getElementById('mail')) { if (cbsage.checked == true) { mailran.value = "sage"; } else { if (mailran.value == "sage") { mailran.value = ""; } } } } } // ƒ[ƒ‹—“‚Ì“à—e‚ɉž‚¶‚āAsageƒ`ƒFƒbƒN‚ðON OFF‚·‚é function checkSage(){ var mailran, cbsage; if (mailran = document.getElementById('mail')) { if (cbsage = document.getElementById('sage')) { if (mailran.value == "sage") { cbsage.checked = true; } else { cbsage.checked = false; } } } } /* // Ž©“®‚œǂݍž‚Þ‚±‚Ƃɂµ‚½‚̂ŁAŽg‚í‚È‚¢ // ‘O‰ñ‚̏‘‚«ž‚Ý“à—e‚𕜋A‚·‚é function loadLastPosted(from, mail, message){ if (fromran = document.getElementById('FROM')) { fromran.value = from; } if (mailran = document.getElementById('mail')) { mailran.value = mail; } if (messageran = document.getElementById('MESSAGE')) { messageran.value = message; } checkSage(); } */ // ‘‚«ž‚݃{ƒ^ƒ“‚Ì—LŒøE–³Œø‚ðØ‚è‘Ö‚¦‚é function switchBlockSubmit(onoff) { var kakiko_submit = document.getElementById('kakiko_submit'); if (kakiko_submit) { kakiko_submit.disabled = onoff; } var submit_beres = document.getElementById('submit_beres'); if (submit_beres) { submit_beres.disabled = onoff; } } // ’èŒ^•¶‚ð‘}“ü‚·‚é function inputConstant(obj) { var msg = document.getElementById('MESSAGE'); msg.value = msg.value + obj.options[obj.selectedIndex].value; msg.focus(); obj.options[0].selected = true; } // ‘‚«ž‚Ý“à—e‚ðŒŸØ‚·‚é function validateAll(doValidateMsg, doValidateSage) { var block_submit = document.getElementById('block_submit'); if (block_submit && block_submit.checked) { alert('‘‚«ž‚݃uƒƒbƒN’†'); return false; } if (doValidateMsg && !validateMsg()) { return false; } if (doValidateSage && !validateSage()) { return false; } return true; } // –{•¶‚ª‹ó‚łȂ¢‚©ŒŸØ‚·‚é function validateMsg() { if (document.getElementById('MESSAGE').value.length == 0) { alert('–{•¶‚ª‚ ‚è‚Ü‚¹‚ñB'); return false; } return true; } // sage‚Ä‚¢‚é‚©ŒŸØ‚·‚é function validateSage() { if (document.getElementById('mail').value.indexOf('sage') == -1) { if (window.confirm('sage‚Ă܂¹‚ñ‚æH')) { return true; } else { return false; } } return true; } // ˆø”‚Étrue‚ðŽw’肵‚½‚ç–¼–³‚µ‚ŏ‘ž‚·‚é‚©‚Ç‚¤‚©Šm”F‚·‚é function confirmNanashi(doconfirmNanashi) { // ˆø”‚ªtrue‚Å–¼‘O—“‚ª0•¶Žš(–¼–³‚µ)‚È‚ç‚Î if (doconfirmNanashi && document.getElementById('FROM').value.length == 0) { if(window.confirm('‚±‚̔‚͖¼–³‚µ‚É fusianasan ‚ªŠÜ‚Ü‚ê‚Ä‚¢‚Ü‚·B\n–¼–³‚µ‚ŏ‘‚«ž‚݂܂·‚©H')) { return true; } else { return false; } } return true; } //ˆø”‚Étrue‚ðŽw’肵‚½‚ç–¼–³‚µ‚ŏ‘žo—ˆ‚È‚¢ function blockNanashi(blockNanashi) { // ˆø”‚ªtrue‚Å–¼‘O—“‚ª0•¶Žš(–¼–³‚µ)‚È‚ç‚Î if (blockNanashi && document.getElementById('FROM').value.length == 0) { alert('‚±‚̔‚͖¼–³‚µ‚̏‘‚«ž‚Ý‚ª§ŒÀ‚³‚ê‚Ä‚¢‚é‚̂Ŗ¼–³‚µ‚ŏ‘‚«ž‚Þ‚±‚Æ‚ªo—ˆ‚Ü‚¹‚ñB'); return false; } return true; }
okyada/p2-php
rep2/js/post_form.js
JavaScript
mit
4,984
using System; using System.Diagnostics; using System.Globalization; namespace Octokit { /// <summary> /// Used to filter issue comments. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class IssueCommentRequest : RequestParameters { /// <summary> /// Initializes a new instance of the <see cref="IssueCommentRequest"/> class. /// </summary> public IssueCommentRequest() { // Default arguments Sort = PullRequestReviewCommentSort.Created; Direction = SortDirection.Ascending; Since = null; } /// <summary> /// Can be either created or updated. Default: created. /// </summary> public PullRequestReviewCommentSort Sort { get; set; } /// <summary> /// Can be either asc or desc. Default: asc. /// </summary> public SortDirection Direction { get; set; } /// <summary> /// Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ. /// </summary> public DateTimeOffset? Since { get; set; } internal string DebuggerDisplay { get { return string.Format(CultureInfo.InvariantCulture, "Sort: {0}, Direction: {1}, Since: {2}", Sort, Direction, Since); } } } }
eriawan/octokit.net
Octokit/Models/Request/IssueCommentRequest.cs
C#
mit
1,391
/******************************************************************************* * Copyright (c) 2014 Salesforce.com, inc.. * 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: * Salesforce.com, inc. - initial API and implementation ******************************************************************************/ package com.salesforce.ide.ui.views.log; import static org.mockito.Mockito.mock; import java.io.File; import junit.framework.TestCase; /** * Class to unit test Logview * @author bvenkatesan * */ public class LogViewTest_unit extends TestCase { public void testCheckSpaceInLogEntryBeforeParentheses() throws Exception { String mockMessage = "Unable to get component for id"; File mockFile = mock(File.class); LogEntry mockEntry = mock(LogEntry.class); String TestMessage = new LogView(mockFile).new LogViewLabelProvider().getExceptionMessage(mockMessage, mockEntry); assertTrue(TestMessage.contains(" (Open")); } }
dipakmankumbare/idecore
com.salesforce.ide.ui.test/src/com/salesforce/ide/ui/views/log/LogViewTest_unit.java
Java
epl-1.0
1,175
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * 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.openhab.binding.satel.internal.command; import org.apache.commons.lang.StringUtils; import org.openhab.binding.satel.internal.protocol.SatelMessage; /** * Base class for all commands that return result code in the response. * * @author Krzysztof Goworek - Initial contribution * @since 1.9.0 */ public abstract class ControlCommand extends SatelCommandBase { /** * Creates new command class instance. * * @param commandCode * command code * @param payload */ public ControlCommand(byte commandCode, byte[] payload) { super(commandCode, payload); } @Override protected boolean isResponseValid(SatelMessage response) { return true; } protected static byte[] userCodeToBytes(String userCode) { if (StringUtils.isEmpty(userCode)) { throw new IllegalArgumentException("User code is empty"); } if (userCode.length() > 8) { throw new IllegalArgumentException("User code too long"); } byte[] bytes = new byte[8]; int digitsNbr = 2 * bytes.length; for (int i = 0; i < digitsNbr; ++i) { if (i < userCode.length()) { char digit = userCode.charAt(i); if (!Character.isDigit(digit)) { throw new IllegalArgumentException("User code must contain digits only"); } if (i % 2 == 0) { bytes[i / 2] = (byte) ((digit - '0') << 4); } else { bytes[i / 2] |= (byte) (digit - '0'); } } else if (i % 2 == 0) { bytes[i / 2] = (byte) 0xff; } else if (i == userCode.length()) { bytes[i / 2] |= 0x0f; } } return bytes; } }
johannrichard/openhab2-addons
addons/binding/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/command/ControlCommand.java
Java
epl-1.0
2,159
/******************************************************************************* * Copyright (c) 2013, 2014 UT-Battelle, LLC. * 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: * Initial API and implementation and/or initial documentation - Jay Jay Billings, * Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson, * Claire Saunders, Matthew Wang, Anna Wojtowicz *******************************************************************************/ package org.eclipse.ice.reactor.sfr.core.assembly; import org.eclipse.ice.reactor.sfr.base.ISFRComponentVisitor; import org.eclipse.ice.reactor.sfr.base.SFRComposite; import org.eclipse.ice.reactor.sfr.core.AssemblyType; /** * <p> * Class representing the assembly structure of a SFR. The SFR assembly is * housed in a hexagonal structure called the wrapper tube (or duct), and * contains a lattice of either pins or rods. * </p> * * @author Anna Wojtowicz */ public class SFRAssembly extends SFRComposite { /** * <p> * Size of a SFRAssembly. Size represents number of pins in a fuel or * control assembly, and rods in a reflector assembly. * </p> * */ private int size; /** * <p> * The type of SFR assembly represented, either fuel, control or reflector. * </p> * */ protected AssemblyType assemblyType; /** * <p> * Thickness of the assembly duct wall. * </p> * */ private double ductThickness; /** * <p> * Parameterized constructor with assemble size specified. Size represents * number of pins in a fuel or control assembly, and rods in a reflector * assembly. * </p> * * @param size * Size of the assembly. */ public SFRAssembly(int size) { // Set the size if positive, otherwise default to 1. this.size = (size > 0 ? size : 1); // Set the default name, description, and ID. setName("SFR Assembly 1"); setDescription("SFR Assembly 1's Description"); setId(1); // Default the assembly type to Fuel. assemblyType = AssemblyType.Fuel; // Initialize ductThickness. ductThickness = 0.0; return; } /** * <p> * Parameterized constructor with assembly name, type and size specified. * Size represents number of pins in a fuel or control assembly, and rods in * a reflector assembly. * </p> * * @param name * The name of the assembly. * @param type * The assembly type (fuel, control or reflector). * @param size * The size of the assembly. */ public SFRAssembly(String name, AssemblyType type, int size) { // Call the basic constructor first. this(size); // Set the name. setName(name); // Set the assembly type if possible. If null, the other constructor has // already set the type to the default (Fuel). if (type != null) { assemblyType = type; } return; } /** * <p> * Returns the assembly size. Size represents number of pins in a fuel or * control assembly, and rods in a reflector assembly. * </p> * * @return The size of the assembly. */ public int getSize() { return size; } /** * <p> * Returns the assembly type (fuel, control or reflector). * </p> * * @return The assembly type. */ public AssemblyType getAssemblyType() { return assemblyType; } /** * <p> * Sets the thickness of the assembly duct wall. * </p> * * @param thickness * The duct thickness. Must be non-negative. */ public void setDuctThickness(double thickness) { // Only set the duct thickness if it is 0 or larger. if (thickness >= 0.0) { ductThickness = thickness; } return; } /** * <p> * Returns the duct wall thickness of an assembly as a double. * </p> * * @return The duct thickness. */ public double getDuctThickness() { return ductThickness; } /** * <p> * Overrides the equals operation to check the attributes on this object * with another object of the same type. Returns true if the objects are * equal. False otherwise. * </p> * * @param otherObject * The object to be compared. * @return True if otherObject is equal. False otherwise. */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof SFRAssembly) { // We can now cast the other object. SFRAssembly assembly = (SFRAssembly) otherObject; // Compare the values between the two objects. equals = (super.equals(otherObject) && size == assembly.size && assemblyType == assembly.assemblyType && ductThickness == assembly.ductThickness); } return equals; } /** * <p> * Returns the hashCode of the object. * </p> * * @return <p> * The hash of the object. * </p> */ @Override public int hashCode() { // Hash based on super's hashCode. int hash = super.hashCode(); // Add local hashes. hash += 31 * size; hash += 31 * assemblyType.hashCode(); hash += 31 * ductThickness; return hash; } /** * <p> * Deep copies the contents of the object from another object. * </p> * * @param otherObject * <p> * The object to be copied from. * </p> */ public void copy(SFRAssembly otherObject) { // Check the parameters. if (otherObject == null) { return; } // Copy the super's values. super.copy(otherObject); // Copy the local values. size = otherObject.size; assemblyType = otherObject.assemblyType; ductThickness = otherObject.ductThickness; return; } /** * <p> * Deep copies and returns a newly instantiated object. * </p> * * @return <p> * The newly instantiated copied object. * </p> */ @Override public Object clone() { // Initialize a new object. SFRAssembly object = new SFRAssembly(size); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * Overrides the default behavior (ignore) from SFRComponent and implements * the accept operation for this SFRComponent's type. */ @Override public void accept(ISFRComponentVisitor visitor) { if (visitor != null) { visitor.visit(this); } return; } }
gorindn/ice
src/org.eclipse.ice.reactor.sfr/src/org/eclipse/ice/reactor/sfr/core/assembly/SFRAssembly.java
Java
epl-1.0
6,609
<?php /** * Test Generated example demonstrating the GroupNesting.delete API. * * @return array * API result array */ function group_nesting_delete_example() { $params = [ 'id' => 1, ]; try{ $result = civicrm_api3('GroupNesting', 'delete', $params); } catch (CiviCRM_API3_Exception $e) { // Handle error here. $errorMessage = $e->getMessage(); $errorCode = $e->getErrorCode(); $errorData = $e->getExtraParams(); return [ 'is_error' => 1, 'error_message' => $errorMessage, 'error_code' => $errorCode, 'error_data' => $errorData, ]; } return $result; } /** * Function returns array of result expected from previous function. * * @return array * API result array */ function group_nesting_delete_expectedresult() { $expectedResult = [ 'is_error' => 0, 'version' => 3, 'count' => 1, 'values' => 1, ]; return $expectedResult; } /* * This example has been generated from the API test suite. * The test that created it is called "testDelete" * and can be found at: * https://github.com/civicrm/civicrm-core/blob/master/tests/phpunit/api/v3/GroupNestingTest.php * * You can see the outcome of the API tests at * https://test.civicrm.org/job/CiviCRM-Core-Matrix/ * * To Learn about the API read * https://docs.civicrm.org/dev/en/latest/api/ * * Browse the API on your own site with the API Explorer. It is in the main * CiviCRM menu, under: Support > Development > API Explorer. * * Read more about testing here * https://docs.civicrm.org/dev/en/latest/testing/ * * API Standards documentation: * https://docs.civicrm.org/dev/en/latest/framework/api-architecture/ */
kreynen/civicrm-starterkit-drops-7
profiles/civicrm_starterkit/modules/civicrm/api/v3/examples/GroupNesting/Delete.ex.php
PHP
gpl-2.0
1,670
/** * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. * * @author ralf57 * @author luciorota (lucio.rota@gmail.com) * @author dugris (dugris@frxoops.fr) */ tinyMCEPopup.requireLangPack(); var XoopsimagemanagerDialog = { preInit : function() { var url; if (url = tinyMCEPopup.getParam("external_image_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function(ed) { var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode(); tinyMCEPopup.resizeToInnerSize(); this.fillClassList('class_list'); this.fillFileList('src_list', 'tinyMCEImageList'); this.fillFileList('over_list', 'tinyMCEImageList'); this.fillFileList('out_list', 'tinyMCEImageList'); if (n.nodeName == 'IMG') { nl.src.value = dom.getAttrib(n, 'src'); nl.width.value = dom.getAttrib(n, 'width'); nl.height.value = dom.getAttrib(n, 'height'); nl.alt.value = dom.getAttrib(n, 'alt'); nl.title.value = dom.getAttrib(n, 'title'); nl.vspace.value = this.getAttrib(n, 'vspace'); nl.hspace.value = this.getAttrib(n, 'hspace'); nl.border.value = this.getAttrib(n, 'border'); selectByValue(f, 'align', this.getAttrib(n, 'align')); selectByValue(f, 'class_list', dom.getAttrib(n, 'class')); nl.style.value = dom.getAttrib(n, 'style'); nl.id.value = dom.getAttrib(n, 'id'); nl.dir.value = dom.getAttrib(n, 'dir'); nl.lang.value = dom.getAttrib(n, 'lang'); nl.usemap.value = dom.getAttrib(n, 'usemap'); nl.longdesc.value = dom.getAttrib(n, 'longdesc'); nl.insert.value = ed.getLang('update'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseover'))) nl.onmouseoversrc.value = dom.getAttrib(n, 'onmouseover').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseout'))) nl.onmouseoutsrc.value = dom.getAttrib(n, 'onmouseout').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (ed.settings.inline_styles) { // Move attribs to styles if (dom.getAttrib(n, 'align')) this.updateStyle('align'); if (dom.getAttrib(n, 'hspace')) this.updateStyle('hspace'); if (dom.getAttrib(n, 'border')) this.updateStyle('border'); if (dom.getAttrib(n, 'vspace')) this.updateStyle('vspace'); } } // Setup browse button document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); if (isVisible('srcbrowser')) document.getElementById('src').style.width = '260px'; // Setup browse button document.getElementById('onmouseoversrccontainer').innerHTML = getBrowserHTML('overbrowser','onmouseoversrc','image','theme_advanced_image'); if (isVisible('overbrowser')) document.getElementById('onmouseoversrc').style.width = '260px'; // Setup browse button document.getElementById('onmouseoutsrccontainer').innerHTML = getBrowserHTML('outbrowser','onmouseoutsrc','image','theme_advanced_image'); if (isVisible('outbrowser')) document.getElementById('onmouseoutsrc').style.width = '260px'; // If option enabled default contrain proportions to checked if (ed.getParam("xoopsimagemanager_constrain_proportions", true)) f.constrain.checked = true; // Check swap image if valid data if (nl.onmouseoversrc.value || nl.onmouseoutsrc.value) this.setSwapImage(true); else this.setSwapImage(false); this.changeAppearance(); this.showPreviewImage(nl.src.value, 1); }, insert : function(file, title) { var ed = tinyMCEPopup.editor, t = this, f = document.forms[0]; if (f.src.value === '') { if (ed.selection.getNode().nodeName == 'IMG') { ed.dom.remove(ed.selection.getNode()); ed.execCommand('mceRepaint'); } tinyMCEPopup.close(); return; } if (tinyMCEPopup.getParam("accessibility_warnings", 1)) { if (!f.alt.value) { tinyMCEPopup.editor.windowManager.confirm(tinyMCEPopup.getLang('xoopsimagemanager_dlg.missing_alt'), function(s) { if (s) t.insertAndClose(); }); return; } } t.insertAndClose(); }, insertAndClose : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], nl = f.elements, v, args = {}, el; tinyMCEPopup.restoreSelection(); // Fixes crash in Safari if (tinymce.isWebKit) ed.getWin().focus(); if (!ed.settings.inline_styles) { args = { vspace : nl.vspace.value, hspace : nl.hspace.value, border : nl.border.value, align : getSelectValue(f, 'align') }; } else { // Remove deprecated values args = { vspace : '', hspace : '', border : '', align : '' }; } tinymce.extend(args, { src : nl.src.value, width : nl.width.value, height : nl.height.value, alt : nl.alt.value, title : nl.title.value, 'class' : getSelectValue(f, 'class_list'), style : nl.style.value, id : nl.id.value, dir : nl.dir.value, lang : nl.lang.value, usemap : nl.usemap.value, longdesc : nl.longdesc.value }); args.onmouseover = args.onmouseout = ''; if (f.onmousemovecheck.checked) { if (nl.onmouseoversrc.value) args.onmouseover = "this.src='" + nl.onmouseoversrc.value + "';"; if (nl.onmouseoutsrc.value) args.onmouseout = "this.src='" + nl.onmouseoutsrc.value + "';"; } el = ed.selection.getNode(); if (el && el.nodeName == 'IMG') { ed.dom.setAttribs(el, args); } else { ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp" src="javascript:;" />', {skip_undo : 1}); ed.dom.setAttribs('__mce_tmp', args); ed.dom.setAttrib('__mce_tmp', 'id', ''); ed.undoManager.add(); } tinyMCEPopup.close(); }, getAttrib : function(e, at) { var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2; if (ed.settings.inline_styles) { switch (at) { case 'align': if (v = dom.getStyle(e, 'float')) return v; if (v = dom.getStyle(e, 'vertical-align')) return v; break; case 'hspace': v = dom.getStyle(e, 'margin-left') v2 = dom.getStyle(e, 'margin-right'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'vspace': v = dom.getStyle(e, 'margin-top') v2 = dom.getStyle(e, 'margin-bottom'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'border': v = 0; tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) { sv = dom.getStyle(e, 'border-' + sv + '-width'); // False or not the same as prev if (!sv || (sv != v && v !== 0)) { v = 0; return false; } if (sv) v = sv; }); if (v) return parseInt(v.replace(/[^0-9]/g, '')); break; } } if (v = dom.getAttrib(e, at)) return v; return ''; }, setSwapImage : function(st) { var f = document.forms[0]; f.onmousemovecheck.checked = st; setBrowserDisabled('overbrowser', !st); setBrowserDisabled('outbrowser', !st); if (f.over_list) f.over_list.disabled = !st; if (f.out_list) f.out_list.disabled = !st; f.onmouseoversrc.disabled = !st; f.onmouseoutsrc.disabled = !st; }, fillClassList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { cl = []; tinymce.each(v.split(';'), function(v) { var p = v.split('='); cl.push({'title' : p[0], 'class' : p[1]}); }); } else cl = tinyMCEPopup.editor.dom.getClasses(); if (cl.length > 0) { lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); tinymce.each(cl, function(o) { lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = window[l]; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, resetImageData : function() { var f = document.forms[0]; f.elements.width.value = f.elements.height.value = ''; }, updateImageData : function(img, st) { var f = document.forms[0]; if (!st) { f.elements.width.value = img.width; f.elements.height.value = img.height; } this.preloadImg = img; }, changeAppearance : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], img = document.getElementById('alignSampleImg'); if (img) { if (ed.getParam('inline_styles')) { ed.dom.setAttrib(img, 'style', f.style.value); } else { img.align = f.align.value; img.border = f.border.value; img.hspace = f.hspace.value; img.vspace = f.vspace.value; } } }, changeHeight : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.width.value) / parseInt(t.preloadImg.width)) * t.preloadImg.height; f.height.value = tp.toFixed(0); }, changeWidth : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.height.value) / parseInt(t.preloadImg.height)) * t.preloadImg.width; f.width.value = tp.toFixed(0); }, updateStyle : function(ty) { var dom = tinyMCEPopup.dom, st, v, f = document.forms[0], img = dom.create('img', {style : dom.get('style').value}); if (tinyMCEPopup.editor.settings.inline_styles) { // Handle align if (ty == 'align') { dom.setStyle(img, 'float', ''); dom.setStyle(img, 'vertical-align', ''); v = getSelectValue(f, 'align'); if (v) { if (v == 'left' || v == 'right') dom.setStyle(img, 'float', v); else img.style.verticalAlign = v; } } // Handle border if (ty == 'border') { dom.setStyle(img, 'border', ''); v = f.border.value; if (v || v == '0') { if (v == '0') img.style.border = ''; else img.style.border = v + 'px solid black'; } } // Handle hspace if (ty == 'hspace') { dom.setStyle(img, 'marginLeft', ''); dom.setStyle(img, 'marginRight', ''); v = f.hspace.value; if (v) { img.style.marginLeft = v + 'px'; img.style.marginRight = v + 'px'; } } // Handle vspace if (ty == 'vspace') { dom.setStyle(img, 'marginTop', ''); dom.setStyle(img, 'marginBottom', ''); v = f.vspace.value; if (v) { img.style.marginTop = v + 'px'; img.style.marginBottom = v + 'px'; } } // Merge dom.get('style').value = dom.serializeStyle(dom.parseStyle(img.style.cssText)); } }, changeMouseMove : function() { }, showPreviewImage : function(u, st) { if (!u) { tinyMCEPopup.dom.setHTML('prev', ''); return; } if (!st && tinyMCEPopup.getParam("xoopsimagemanager_update_dimensions_onchange", true)) this.resetImageData(); u = tinyMCEPopup.editor.documentBaseURI.toAbsolute(u); if (!st) tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="XoopsimagemanagerDialog.updateImageData(this);" onerror="XoopsimagemanagerDialog.resetImageData();" />'); else tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="XoopsimagemanagerDialog.updateImageData(this, 1);" />'); } }; XoopsimagemanagerDialog.preInit(); tinyMCEPopup.onInit.add(XoopsimagemanagerDialog.init, XoopsimagemanagerDialog); function XoopsImageBrowser( input ) { var url = "xoopsimagebrowser.php?target=src"; var type = "image"; var win = window.self; var cmsURL = window.location.href; // script URL var cmsURL = cmsURL.substring( 0, cmsURL.lastIndexOf("/") + 1 ); var searchString = window.location.search; // possible parameters if (searchString.length < 1) { // add "?" to the URL to include parameters (in other words: create a search string because there wasn't one before) searchString = "?"; } tinyMCE.activeEditor.windowManager.open({ file : cmsURL + url + searchString + "&type=" + type, title : 'Xoops Image Manager', width : 650, height : 440, resizable : "yes", scrollbars : "yes", inline : "yes", // This parameter only has an effect if you use the inlinepopups plugin! close_previous : "no" }, { window : win, input_src : input, input_title : "title", input_alt : "alt", input_align : "align" }); return false; }
mambax7/XoopsCore25
htdocs/class/xoopseditor/tinymce/tinymce/jscripts/tiny_mce/plugins/xoopsimagemanager/js/xoopsimagemanager.js
JavaScript
gpl-2.0
16,092
<?php /** * @file * Contains \Drupal\Core\Utility\UnroutedUrlAssembler. */ namespace Drupal\Core\Utility; use Drupal\Component\Utility\SafeMarkup; use Drupal\Component\Utility\UrlHelper; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\GeneratedUrl; use Drupal\Core\PathProcessor\OutboundPathProcessorInterface; use Symfony\Component\HttpFoundation\RequestStack; /** * Provides a way to build external or non Drupal local domain URLs. * * It takes into account configured safe HTTP protocols. */ class UnroutedUrlAssembler implements UnroutedUrlAssemblerInterface { /** * A request stack object. * * @var \Symfony\Component\HttpFoundation\RequestStack */ protected $requestStack; /** * The outbound path processor. * * @var \Drupal\Core\PathProcessor\OutboundPathProcessorInterface */ protected $pathProcessor; /** * Constructs a new unroutedUrlAssembler object. * * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack * A request stack object. * @param \Drupal\Core\Config\ConfigFactoryInterface $config * The config factory. * @param \Drupal\Core\PathProcessor\OutboundPathProcessorInterface $path_processor * The output path processor. */ public function __construct(RequestStack $request_stack, ConfigFactoryInterface $config, OutboundPathProcessorInterface $path_processor) { $allowed_protocols = $config->get('system.filter')->get('protocols') ?: ['http', 'https']; UrlHelper::setAllowedProtocols($allowed_protocols); $this->requestStack = $request_stack; $this->pathProcessor = $path_processor; } /** * {@inheritdoc} * * This is a helper function that calls buildExternalUrl() or buildLocalUrl() * based on a check of whether the path is a valid external URL. */ public function assemble($uri, array $options = [], $collect_cacheability_metadata = FALSE) { // Note that UrlHelper::isExternal will return FALSE if the $uri has a // disallowed protocol. This is later made safe since we always add at // least a leading slash. if (parse_url($uri, PHP_URL_SCHEME) === 'base') { return $this->buildLocalUrl($uri, $options, $collect_cacheability_metadata); } elseif (UrlHelper::isExternal($uri)) { // UrlHelper::isExternal() only returns true for safe protocols. return $this->buildExternalUrl($uri, $options, $collect_cacheability_metadata); } throw new \InvalidArgumentException(SafeMarkup::format('The URI "@uri" is invalid. You must use a valid URI scheme. Use base: for a path, e.g., to a Drupal file that needs the base path. Do not use this for internal paths controlled by Drupal.', ['@uri' => $uri])); } /** * {@inheritdoc} */ protected function buildExternalUrl($uri, array $options = [], $collect_cacheability_metadata = FALSE) { $this->addOptionDefaults($options); // Split off the fragment. if (strpos($uri, '#') !== FALSE) { list($uri, $old_fragment) = explode('#', $uri, 2); // If $options contains no fragment, take it over from the path. if (isset($old_fragment) && !$options['fragment']) { $options['fragment'] = '#' . $old_fragment; } } if (isset($options['https'])) { if ($options['https'] === TRUE) { $uri = str_replace('http://', 'https://', $uri); } elseif ($options['https'] === FALSE) { $uri = str_replace('https://', 'http://', $uri); } } // Append the query. if ($options['query']) { $uri .= (strpos($uri, '?') !== FALSE ? '&' : '?') . UrlHelper::buildQuery($options['query']); } // Reassemble. $url = $uri . $options['fragment']; return $collect_cacheability_metadata ? (new GeneratedUrl())->setGeneratedUrl($url) : $url; } /** * {@inheritdoc} */ protected function buildLocalUrl($uri, array $options = [], $collect_cacheability_metadata = FALSE) { $generated_url = $collect_cacheability_metadata ? new GeneratedUrl() : NULL; $this->addOptionDefaults($options); $request = $this->requestStack->getCurrentRequest(); // Remove the base: scheme. // @todo Consider using a class constant for this in // https://www.drupal.org/node/2417459 $uri = substr($uri, 5); // Strip leading slashes from internal paths to prevent them becoming // external URLs without protocol. /example.com should not be turned into // //example.com. $uri = ltrim($uri, '/'); // Allow (outbound) path processing, if needed. A valid use case is the path // alias overview form: // @see \Drupal\path\Controller\PathController::adminOverview(). if (!empty($options['path_processing'])) { // Do not pass the request, since this is a special case and we do not // want to include e.g. the request language in the processing. $uri = $this->pathProcessor->processOutbound($uri, $options, NULL, $generated_url); } // Add any subdirectory where Drupal is installed. $current_base_path = $request->getBasePath() . '/'; if ($options['absolute']) { $current_base_url = $request->getSchemeAndHttpHost() . $current_base_path; if (isset($options['https'])) { if (!empty($options['https'])) { $base = str_replace('http://', 'https://', $current_base_url); $options['absolute'] = TRUE; } else { $base = str_replace('https://', 'http://', $current_base_url); $options['absolute'] = TRUE; } } else { $base = $current_base_url; } if ($collect_cacheability_metadata) { $generated_url->addCacheContexts(['url.site']); } } else { $base = $current_base_path; } $prefix = empty($uri) ? rtrim($options['prefix'], '/') : $options['prefix']; $uri = str_replace('%2F', '/', rawurlencode($prefix . $uri)); $query = $options['query'] ? ('?' . UrlHelper::buildQuery($options['query'])) : ''; $url = $base . $options['script'] . $uri . $query . $options['fragment']; return $collect_cacheability_metadata ? $generated_url->setGeneratedUrl($url) : $url; } /** * Merges in default defaults * * @param array $options * The options to merge in the defaults. */ protected function addOptionDefaults(array &$options) { $request = $this->requestStack->getCurrentRequest(); $current_base_path = $request->getBasePath() . '/'; $current_script_path = ''; $base_path_with_script = $request->getBaseUrl(); // If the current request was made with the script name (eg, index.php) in // it, then extract it, making sure the leading / is gone, and a trailing / // is added, to allow simple string concatenation with other parts. This // mirrors code from UrlGenerator::generateFromPath(). if (!empty($base_path_with_script)) { $script_name = $request->getScriptName(); if (strpos($base_path_with_script, $script_name) !== FALSE) { $current_script_path = ltrim(substr($script_name, strlen($current_base_path)), '/') . '/'; } } // Merge in defaults. $options += [ 'fragment' => '', 'query' => [], 'absolute' => FALSE, 'prefix' => '', 'script' => $current_script_path, ]; if (isset($options['fragment']) && $options['fragment'] !== '') { $options['fragment'] = '#' . $options['fragment']; } } }
cpjobling/proman-d8
proman.swan.ac.uk/core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php
PHP
gpl-2.0
7,426
<?php /** * DmSetting filter form base class. * * @package retest * @subpackage filter * @author Your name here * @version SVN: $Id: sfDoctrineFormFilterGeneratedTemplate.php 24171 2009-11-19 16:37:50Z Kris.Wallsmith $ */ abstract class BaseDmSettingFormFilter extends BaseFormFilterDoctrine { public function setup() { if($this->needsWidget('id')){ $this->setWidget('id', new sfWidgetFormDmFilterInput()); $this->setValidator('id', new sfValidatorDoctrineChoice(array('required' => false, 'model' => 'DmSetting', 'column' => 'id'))); } if($this->needsWidget('name')){ $this->setWidget('name', new sfWidgetFormDmFilterInput()); $this->setValidator('name', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } if($this->needsWidget('type')){ $this->setWidget('type', new sfWidgetFormChoice(array('multiple' => true, 'choices' => array('' => '', 'text' => 'text', 'boolean' => 'boolean', 'select' => 'select', 'textarea' => 'textarea', 'number' => 'number', 'datetime' => 'datetime')))); $this->setValidator('type', new sfValidatorChoice(array('required' => false, 'multiple' => true , 'choices' => array('text' => 'text', 'boolean' => 'boolean', 'select' => 'select', 'textarea' => 'textarea', 'number' => 'number', 'datetime' => 'datetime')))); } if($this->needsWidget('params')){ $this->setWidget('params', new sfWidgetFormDmFilterInput()); $this->setValidator('params', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } if($this->needsWidget('group_name')){ $this->setWidget('group_name', new sfWidgetFormDmFilterInput()); $this->setValidator('group_name', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } if($this->needsWidget('credentials')){ $this->setWidget('credentials', new sfWidgetFormDmFilterInput()); $this->setValidator('credentials', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } $this->mergeI18nForm(); $this->widgetSchema->setNameFormat('dm_setting_filters[%s]'); $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema); $this->setupInheritance(); parent::setup(); } public function getModelName() { return 'DmSetting'; } public function getFields() { return array( 'id' => 'Number', 'name' => 'Text', 'type' => 'Enum', 'params' => 'Text', 'group_name' => 'Text', 'credentials' => 'Text', 'id' => 'Number', 'description' => 'Text', 'value' => 'Text', 'default_value' => 'Text', 'lang' => 'Text', ); } }
Teplitsa/bquest.ru
lib/vendor/diem/dmCorePlugin/test/project/lib/filter/doctrine/dmCorePlugin/base/BaseDmSettingFormFilter.class.php
PHP
gpl-2.0
2,784
/* * Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/> * * 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 "Field.h" Field::Field() { data.value = NULL; data.type = MYSQL_TYPE_NULL; data.length = 0; data.raw = false; } Field::~Field() { CleanUp(); } void Field::SetByteValue(const void* newValue, const size_t newSize, enum_field_types newType, uint32 length) { if (data.value) CleanUp(); // This value stores raw bytes that have to be explicitly cast later if (newValue) { data.value = new char[newSize]; memcpy(data.value, newValue, newSize); data.length = length; } data.type = newType; data.raw = true; } void Field::SetStructuredValue(char* newValue, enum_field_types newType) { if (data.value) CleanUp(); // This value stores somewhat structured data that needs function style casting if (newValue) { size_t size = strlen(newValue); data.value = new char [size+1]; strcpy((char*)data.value, newValue); data.length = size; } data.type = newType; data.raw = false; }
ironhead123/DeathCore_3.3.5
src/server/shared/Database/Field.cpp
C++
gpl-2.0
1,759
<?php /** * @package JCE * @copyright Copyright (c)2016 Ryan Demmer * @license GNU General Public License version 2, or later */ defined('_JEXEC') or die; /** * Handle commercial extension update authorization * * @package Joomla.Plugin * @subpackage Installer.Jce * @since 2.6 */ class plgInstallerJce extends JPlugin { /** * Handle adding credentials to package download request * * @param string $url url from which package is going to be downloaded * @param array $headers headers to be sent along the download request (key => value format) * * @return boolean true if credentials have been added to request or not our business, false otherwise (credentials not set by user) * * @since 3.0 */ public function onInstallerBeforePackageDownload(&$url, &$headers) { $app = JFactory::getApplication(); $uri = JUri::getInstance($url); $host = $uri->getHost(); if ($host !== 'www.joomlacontenteditor.net') { return true; } // Get the subscription key JLoader::import('joomla.application.component.helper'); $component = JComponentHelper::getComponent('com_jce'); $key = $component->params->get('updates_key', ''); if (empty($key)) { $language = JFactory::getLanguage(); $language->load('plg_installer_jce', JPATH_ADMINISTRATOR); $app->enqueueMessage(JText::_('PLG_INSTALLER_JCE_KEY_WARNING'), 'notice'); } // Append the subscription key to the download URL $uri->setVar('key', $key); $url = $uri->toString(); return true; } }
khuongdang/dongtrungtruongsinh
plugins/installer/jce/jce.php
PHP
gpl-2.0
1,570
var express = require('express'); var leaderRouter = express.Router(); leaderRouter.route('/') .all(function(req, res, next) { res.writeHead(200, { 'Content-Type': 'text/plain' }); next(); }) .get(function(req, res, next){ res.end('Will send all the leaders to you!'); }) .post(function(req, res, next){ res.end('Will add the leader: ' + req.body.name + ' with details: ' + req.body.description); }) .delete(function(req, res, next){ res.end('Deleting all leaders'); }); leaderRouter.route('/:leaderId') .all(function(req, res, next) { res.writeHead(200, { 'Content-Type': 'text/plain' }); next(); }) .get(function(req, res, next){ res.end('Will send details of the leader: ' + req.params.leaderId +' to you!'); }) .put(function(req, res, next){ res.write('Updating the leader: ' + req.params.leaderId + '\n'); res.end('Will update the leader: ' + req.body.name + ' with details: ' + req.body.description); }) .delete(function(req, res, next){ res.end('Deleting the leader: ' + req.params.leaderId); }); module.exports = leaderRouter;
mikedanylov/full-stack-dev
NodeJS/week3/rest-server/routes/leaderRouter.js
JavaScript
gpl-2.0
1,220
# postgresql/pypostgresql.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: postgresql+pypostgresql :name: py-postgresql :dbapi: pypostgresql :connectstring: postgresql+pypostgresql://user:password@host:port/dbname[?key=value&key=value...] :url: http://python.projects.pgfoundry.org/ .. note:: The pypostgresql dialect is **not tested as part of SQLAlchemy's continuous integration** and may have unresolved issues. The recommended PostgreSQL driver is psycopg2. """ # noqa from .base import PGDialect from .base import PGExecutionContext from ... import processors from ... import types as sqltypes from ... import util class PGNumeric(sqltypes.Numeric): def bind_processor(self, dialect): return processors.to_str def result_processor(self, dialect, coltype): if self.asdecimal: return None else: return processors.to_float class PGExecutionContext_pypostgresql(PGExecutionContext): pass class PGDialect_pypostgresql(PGDialect): driver = "pypostgresql" supports_unicode_statements = True supports_unicode_binds = True description_encoding = None default_paramstyle = "pyformat" # requires trunk version to support sane rowcounts # TODO: use dbapi version information to set this flag appropriately supports_sane_rowcount = True supports_sane_multi_rowcount = False execution_ctx_cls = PGExecutionContext_pypostgresql colspecs = util.update_copy( PGDialect.colspecs, { sqltypes.Numeric: PGNumeric, # prevents PGNumeric from being used sqltypes.Float: sqltypes.Float, }, ) @classmethod def dbapi(cls): from postgresql.driver import dbapi20 return dbapi20 _DBAPI_ERROR_NAMES = [ "Error", "InterfaceError", "DatabaseError", "DataError", "OperationalError", "IntegrityError", "InternalError", "ProgrammingError", "NotSupportedError", ] @util.memoized_property def dbapi_exception_translation_map(self): if self.dbapi is None: return {} return dict( (getattr(self.dbapi, name).__name__, name) for name in self._DBAPI_ERROR_NAMES ) def create_connect_args(self, url): opts = url.translate_connect_args(username="user") if "port" in opts: opts["port"] = int(opts["port"]) else: opts["port"] = 5432 opts.update(url.query) return ([], opts) def is_disconnect(self, e, connection, cursor): return "connection is closed" in str(e) dialect = PGDialect_pypostgresql
gltn/stdm
stdm/third_party/sqlalchemy/dialects/postgresql/pypostgresql.py
Python
gpl-2.0
2,915
<?php /** * @package Joomla.UnitTest * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ jimport('joomla.filesystem.folder'); require_once __DIR__ . '/JLanguageInspector.php'; require_once __DIR__ . '/data/language/en-GB/en-GB.localise.php'; /** * Test class for JLanguage. * Generated by PHPUnit on 2012-03-21 at 21:29:28. * * @package Joomla.UnitTest * @subpackage Language * @since 11.1 */ class JLanguageTest extends PHPUnit_Framework_TestCase { /** * @var JLanguage */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @return void */ protected function setUp() { parent::setUp(); $path = JPATH_BASE . '/language'; if (is_dir($path)) { JFolder::delete($path); } JFolder::copy(__DIR__ . '/data/language', $path); $this->object = new JLanguage; $this->inspector = new JLanguageInspector('', true); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void */ protected function tearDown() { JFolder::delete(JPATH_BASE . '/language'); } /** * Test... * * @covers JLanguage::getInstance * * @return void */ public function testGetInstance() { $instance = JLanguage::getInstance(null); $this->assertInstanceOf('JLanguage', $instance); } /** * Test... * * @covers JLanguage::__construct * * @return void */ public function testConstruct() { // @codingStandardsIgnoreStart // @todo check the instanciating new classes without brackets sniff $instance = new JLanguage(null, true); // @codingStandardsIgnoreEnd $this->assertInstanceOf('JLanguage', $instance); $this->assertTrue($instance->getDebug()); // @codingStandardsIgnoreStart // @todo check the instanciating new classes without brackets sniff $instance = new JLanguage(null, false); // @codingStandardsIgnoreEnd $this->assertInstanceOf('JLanguage', $instance); $this->assertFalse($instance->getDebug()); } /** * Test... * * @covers JLanguage::_ * * @return void */ public function test_() { $string1 = 'delete'; $string2 = "delete's"; $this->assertEquals( 'delete', $this->object->_($string1, false), 'Line: ' . __LINE__ . ' Exact case should match when javascript safe is false ' ); $this->assertNotEquals( 'Delete', $this->object->_($string1, false), 'Line: ' . __LINE__ . ' Should be case sensitive when javascript safe is false' ); $this->assertEquals( 'delete', $this->object->_($string1, true), 'Line: ' . __LINE__ . ' Exact case match should work when javascript safe is true' ); $this->assertNotEquals( 'Delete', $this->object->_($string1, true), 'Line: ' . __LINE__ . ' Should be case sensitive when javascript safe is true' ); $this->assertEquals( 'delete\'s', $this->object->_($string2, false), 'Line: ' . __LINE__ . ' Exact case should match when javascript safe is false ' ); $this->assertNotEquals( 'Delete\'s', $this->object->_($string2, false), 'Line: ' . __LINE__ . ' Should be case sensitive when javascript safe is false' ); $this->assertEquals( "delete\'s", $this->object->_($string2, true), 'Line: ' . __LINE__ . ' Exact case should match when javascript safe is true, also it calls addslashes (\' => \\\') ' ); $this->assertNotEquals( "Delete\'s", $this->object->_($string2, true), 'Line: ' . __LINE__ . ' Should be case sensitive when javascript safe is true,, also it calls addslashes (\' => \\\') ' ); } /** * Test... * * @covers JLanguage::transliterate * * @return void */ public function testTransliterate() { $string1 = 'Así'; $string2 = 'EÑE'; $this->assertEquals( 'asi', $this->object->transliterate($string1), 'Line: ' . __LINE__ ); $this->assertNotEquals( 'Asi', $this->object->transliterate($string1), 'Line: ' . __LINE__ ); $this->assertNotEquals( 'Así', $this->object->transliterate($string1), 'Line: ' . __LINE__ ); $this->assertEquals( 'ene', $this->object->transliterate($string2), 'Line: ' . __LINE__ ); $this->assertNotEquals( 'ENE', $this->object->transliterate($string2), 'Line: ' . __LINE__ ); $this->assertNotEquals( 'EÑE', $this->object->transliterate($string2), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getTransliterator * * @return void */ public function testGetTransliterator() { $lang = new JLanguage(''); // The first time you run the method returns NULL // Only if there is an setTransliterator, this test is wrong $this->assertNull( $lang->getTransliterator() ); } /** * Test... * * @covers JLanguage::setTransliterator * @todo Implement testSetTransliterator(). * * @return void */ public function testSetTransliterator() { $function1 = 'phpinfo'; $function2 = 'print'; $lang = new JLanguage(''); // Note: set -> $funtion1: set returns NULL and get returns $function1 $this->assertNull( $lang->setTransliterator($function1) ); $get = $lang->getTransliterator(); $this->assertEquals( $function1, $get, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $get, 'Line: ' . __LINE__ ); // Note: set -> $function2: set returns $function1 and get retuns $function2 $set = $lang->setTransliterator($function2); $this->assertEquals( $function1, $set, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $set, 'Line: ' . __LINE__ ); $this->assertEquals( $function2, $lang->getTransliterator(), 'Line: ' . __LINE__ ); $this->assertNotEquals( $function1, $lang->getTransliterator(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getPluralSuffixes * * @return void */ public function testGetPluralSuffixes() { $this->assertEquals( array('0'), $this->object->getPluralSuffixes(0), 'Line: ' . __LINE__ ); $this->assertEquals( array('1'), $this->object->getPluralSuffixes(1), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getPluralSuffixesCallback * * @return void */ public function testGetPluralSuffixesCallback() { $lang = new JLanguage(''); $this->assertTrue( is_callable($lang->getPluralSuffixesCallback()) ); } /** * Test... * * @covers JLanguage::setPluralSuffixesCallback * @covers JLanguage::getPluralSuffixesCallback * * @return void */ public function testSetPluralSuffixesCallback() { $function1 = 'phpinfo'; $function2 = 'print'; $lang = new JLanguage(''); $this->assertTrue( is_callable($lang->getPluralSuffixesCallback()) ); $this->assertTrue( is_callable($lang->setPluralSuffixesCallback($function1)) ); $get = $lang->getPluralSuffixesCallback(); $this->assertEquals( $function1, $get, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $get, 'Line: ' . __LINE__ ); // Note: set -> $function2: set returns $function1 and get retuns $function2 $set = $lang->setPluralSuffixesCallback($function2); $this->assertEquals( $function1, $set, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $set, 'Line: ' . __LINE__ ); $this->assertEquals( $function2, $lang->getPluralSuffixesCallback(), 'Line: ' . __LINE__ ); $this->assertNotEquals( $function1, $lang->getPluralSuffixesCallback(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getIgnoredSearchWords * * @return void */ public function testGetIgnoredSearchWords() { $lang = new JLanguage(''); $this->assertEquals( array('and', 'in', 'on'), $lang->getIgnoredSearchWords(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getIgnoredSearchWordsCallback * * @return void */ public function testGetIgnoredSearchWordsCallback() { $lang = new JLanguage(''); $this->assertTrue( is_callable($lang->getIgnoredSearchWordsCallback()) ); } /** * Test... * * @covers JLanguage::setIgnoredSearchWordsCallback * @covers JLanguage::getIgnoredSearchWordsCallback * * @return void */ public function testSetIgnoredSearchWordsCallback() { $function1 = 'phpinfo'; $function2 = 'print'; $lang = new JLanguage(''); $this->assertTrue( is_callable($lang->getIgnoredSearchWordsCallback()) ); // Note: set -> $funtion1: set returns NULL and get returns $function1 $this->assertTrue( is_callable($lang->setIgnoredSearchWordsCallback($function1)) ); $get = $lang->getIgnoredSearchWordsCallback(); $this->assertEquals( $function1, $get, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $get, 'Line: ' . __LINE__ ); // Note: set -> $function2: set returns $function1 and get retuns $function2 $set = $lang->setIgnoredSearchWordsCallback($function2); $this->assertEquals( $function1, $set, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $set, 'Line: ' . __LINE__ ); $this->assertEquals( $function2, $lang->getIgnoredSearchWordsCallback(), 'Line: ' . __LINE__ ); $this->assertNotEquals( $function1, $lang->getIgnoredSearchWordsCallback(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getLowerLimitSearchWord * * @return void */ public function testGetLowerLimitSearchWord() { $lang = new JLanguage(''); $this->assertEquals( 3, $lang->getLowerLimitSearchWord(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getLowerLimitSearchWordCallback * * @return void */ public function testGetLowerLimitSearchWordCallback() { $lang = new JLanguage(''); $this->assertTrue( is_callable($lang->getLowerLimitSearchWordCallback()) ); } /** * Test... * * @covers JLanguage::setLowerLimitSearchWordCallback * @covers JLanguage::getLowerLimitSearchWordCallback * * @return void */ public function testSetLowerLimitSearchWordCallback() { $function1 = 'phpinfo'; $function2 = 'print'; $lang = new JLanguage(''); $this->assertTrue( is_callable($lang->getLowerLimitSearchWordCallback()) ); // Note: set -> $funtion1: set returns NULL and get returns $function1 $this->assertTrue( is_callable($lang->setLowerLimitSearchWordCallback($function1)) ); $get = $lang->getLowerLimitSearchWordCallback(); $this->assertEquals( $function1, $get, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $get, 'Line: ' . __LINE__ ); // Note: set -> $function2: set returns $function1 and get retuns $function2 $set = $lang->setLowerLimitSearchWordCallback($function2); $this->assertEquals( $function1, $set, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $set, 'Line: ' . __LINE__ ); $this->assertEquals( $function2, $lang->getLowerLimitSearchWordCallback(), 'Line: ' . __LINE__ ); $this->assertNotEquals( $function1, $lang->getLowerLimitSearchWordCallback(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getUpperLimitSearchWord * * @return void */ public function testGetUpperLimitSearchWord() { $lang = new JLanguage(''); $this->assertEquals( 20, $lang->getUpperLimitSearchWord(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getUpperLimitSearchWordCallback * * @return void */ public function testGetUpperLimitSearchWordCallback() { $lang = new JLanguage(''); $this->assertTrue( is_callable($lang->getUpperLimitSearchWordCallback()) ); } /** * Test... * * @covers JLanguage::setUpperLimitSearchWordCallback * @covers JLanguage::getUpperLimitSearchWordCallback * * @return void */ public function testSetUpperLimitSearchWordCallback() { $function1 = 'phpinfo'; $function2 = 'print'; $lang = new JLanguage(''); $this->assertTrue( is_callable($lang->getUpperLimitSearchWordCallback()) ); // Note: set -> $funtion1: set returns NULL and get returns $function1 $this->assertTrue( is_callable($lang->setUpperLimitSearchWordCallback($function1)) ); $get = $lang->getUpperLimitSearchWordCallback(); $this->assertEquals( $function1, $get, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $get, 'Line: ' . __LINE__ ); // Note: set -> $function2: set returns $function1 and get retuns $function2 $set = $lang->setUpperLimitSearchWordCallback($function2); $this->assertEquals( $function1, $set, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $set, 'Line: ' . __LINE__ ); $this->assertEquals( $function2, $lang->getUpperLimitSearchWordCallback(), 'Line: ' . __LINE__ ); $this->assertNotEquals( $function1, $lang->getUpperLimitSearchWordCallback(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getSearchDisplayedCharactersNumber * * @return void */ public function testGetSearchDisplayedCharactersNumber() { $lang = new JLanguage(''); $this->assertEquals( 200, $lang->getSearchDisplayedCharactersNumber(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getSearchDisplayedCharactersNumberCallback * * @return void */ public function testGetSearchDisplayedCharactersNumberCallback() { $lang = new JLanguage(''); $this->assertTrue( is_callable($lang->getSearchDisplayedCharactersNumberCallback()) ); } /** * Test... * * @covers JLanguage::setSearchDisplayedCharactersNumberCallback * @covers JLanguage::getSearchDisplayedCharactersNumberCallback * * @return void */ public function testSetSearchDisplayedCharactersNumberCallback() { $function1 = 'phpinfo'; $function2 = 'print'; $lang = new JLanguage(''); $this->assertTrue( is_callable($lang->getSearchDisplayedCharactersNumberCallback()) ); // Note: set -> $funtion1: set returns NULL and get returns $function1 $this->assertTrue( is_callable($lang->setSearchDisplayedCharactersNumberCallback($function1)) ); $get = $lang->getSearchDisplayedCharactersNumberCallback(); $this->assertEquals( $function1, $get, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $get, 'Line: ' . __LINE__ ); // Note: set -> $function2: set returns $function1 and get retuns $function2 $set = $lang->setSearchDisplayedCharactersNumberCallback($function2); $this->assertEquals( $function1, $set, 'Line: ' . __LINE__ ); $this->assertNotEquals( $function2, $set, 'Line: ' . __LINE__ ); $this->assertEquals( $function2, $lang->getSearchDisplayedCharactersNumberCallback(), 'Line: ' . __LINE__ ); $this->assertNotEquals( $function1, $lang->getSearchDisplayedCharactersNumberCallback(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::exists * @todo Implement testExists(). * * @return void */ public function testExists() { $this->assertFalse( $this->object->exists(null) ); $basePath = __DIR__ . '/data'; $this->assertTrue( $this->object->exists('en-GB', $basePath) ); $this->assertFalse( $this->object->exists('es-ES', $basePath) ); } /** * Test... * * @covers JLanguage::load * @todo Implement testLoad(). * * @return void */ public function testLoad() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::parse * * @return void */ public function testParse() { $strings = $this->inspector->parse(__DIR__ . '/data/good.ini'); $this->assertThat( $strings, $this->logicalNot($this->equalTo(array())), 'Line: ' . __LINE__ . ' good ini file should load properly.' ); $this->assertEquals( $strings, array('FOO' => 'Bar'), 'Line: ' . __LINE__ . ' test that the strings were parsed correctly.' ); $strings = $this->inspector->parse(__DIR__ . '/data/bad.ini'); $this->assertEquals( $strings, array(), 'Line: ' . __LINE__ . ' bad ini file should not load properly.' ); } /** * Test... * * @covers JLanguage::get * @todo Implement testGet(). * * @return void */ public function testGet() { $this->assertNull( $this->object->get('noExist') ); $this->assertEquals( 'abc', $this->object->get('noExist', 'abc') ); // Note: property = tag, returns en-GB (default language) $this->assertEquals( 'en-GB', $this->object->get('tag') ); // Note: property = name, returns English (United Kingdom) (default language) $this->assertEquals( 'English (United Kingdom)', $this->object->get('name') ); // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::getName * @todo Implement testGetName(). * * @return void */ public function testGetName() { $this->assertEquals( 'English (United Kingdom)', $this->object->getName() ); // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::getPaths * @todo Implement testGetPaths(). * * @return void */ public function testGetPaths() { // Without extension, retuns NULL $this->assertNull( $this->object->getPaths('') ); // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::getErrorFiles * @todo Implement testGetErrorFiles(). * * @return void */ public function testGetErrorFiles() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::getTag * @todo Implement testGetTag(). * * @return void */ public function testGetTag() { $this->assertEquals( 'en-GB', $this->object->getTag() ); // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::isRTL * @todo Implement testIsRTL(). * * @return void */ public function testIsRTL() { $this->assertFalse( $this->object->isRTL() ); // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::setDebug * @covers JLanguage::getDebug * * @return void */ public function testGetSetDebug() { $current = $this->object->getDebug(); $this->assertEquals( $current, $this->object->setDebug(true), 'Line: ' . __LINE__ ); $this->object->setDebug(false); $this->assertFalse( $this->object->getDebug(), 'Line: ' . __LINE__ ); $this->object->setDebug(true); $this->assertTrue( $this->object->getDebug(), 'Line: ' . __LINE__ ); $this->object->setDebug(0); $this->assertFalse( $this->object->getDebug(), 'Line: ' . __LINE__ ); $this->object->setDebug(1); $this->assertTrue( $this->object->getDebug(), 'Line: ' . __LINE__ ); $this->object->setDebug(''); $this->assertFalse( $this->object->getDebug(), 'Line: ' . __LINE__ ); $this->object->setDebug('test'); $this->assertTrue( $this->object->getDebug(), 'Line: ' . __LINE__ ); $this->object->setDebug('0'); $this->assertFalse( $this->object->getDebug(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getDefault * * @return void */ public function testGetDefault() { $this->assertEquals( 'en-GB', $this->object->getDefault(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::setDefault * * @return void */ public function testSetDefault() { $this->object->setDefault('de-DE'); $this->assertEquals( 'de-DE', $this->object->getDefault(), 'Line: ' . __LINE__ ); $this->object->setDefault('en-GB'); } /** * Test... * * @covers JLanguage::getOrphans * @todo Implement testGetOrphans(). * * @return void */ public function testGetOrphans() { $this->assertEquals( array(), $this->object->getOrphans(), 'Line: ' . __LINE__ ); // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::getUsed * @todo Implement testGetUsed(). * * @return void */ public function testGetUsed() { $this->assertEquals( array(), $this->object->getUsed(), 'Line: ' . __LINE__ ); // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::hasKey * @todo Implement testHasKey(). * * @return void */ public function testHasKey() { // Key doesn't exist, returns false $this->assertFalse( $this->object->hasKey('com_admin.key') ); // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::getMetadata * @todo Implement testGetMetadata(). * * @return void */ public function testGetMetadata() { // Language doesn't exist, retun NULL $this->assertNull( $this->inspector->getMetadata('es-ES') ); $localeString = 'en_GB.utf8, en_GB.UTF-8, en_GB, eng_GB, en, english, english-uk, uk, gbr, britain, england, great britain, ' . 'uk, united kingdom, united-kingdom'; // In this case, returns array with default language // - same operation of get method with metadata property $options = array( 'name' => 'English (United Kingdom)', 'tag' => 'en-GB', 'rtl' => '0', 'locale' => $localeString, 'firstDay' => '0' ); // Language exists, returns array with values $this->assertEquals( $options, $this->inspector->getMetadata('en-GB') ); } /** * Test... * * @covers JLanguage::getKnownLanguages * * @return void */ public function testGetKnownLanguages() { // This method returns a list of known languages $basePath = __DIR__ . '/data'; $localeString = 'en_GB.utf8, en_GB.UTF-8, en_GB, eng_GB, en, english, english-uk, uk, gbr, britain, england, great britain,' . ' uk, united kingdom, united-kingdom'; $option1 = array( 'name' => 'English (United Kingdom)', 'tag' => 'en-GB', 'rtl' => '0', 'locale' => $localeString, 'firstDay' => '0' ); $listCompareEqual1 = array( 'en-GB' => $option1, ); $list = JLanguage::getKnownLanguages($basePath); $this->assertEquals( $listCompareEqual1, $list, 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getLanguagePath * * @return void */ public function testGetLanguagePath() { $basePath = 'test'; // $language = null, returns language directory $this->assertEquals( 'test/language', JLanguage::getLanguagePath($basePath, null), 'Line: ' . __LINE__ ); // $language = value (en-GB, for example), returns en-GB language directory $this->assertEquals( 'test/language/en-GB', JLanguage::getLanguagePath($basePath, 'en-GB'), 'Line: ' . __LINE__ ); // With no argument JPATH_BASE should be returned $this->assertEquals( JPATH_BASE . '/language', JLanguage::getLanguagePath(), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::setLanguage * * @return void */ public function testSetLanguage() { $this->assertEquals( 'en-GB', $this->object->setLanguage('es-ES'), 'Line: ' . __LINE__ ); $this->assertEquals( 'es-ES', $this->object->setLanguage('en-GB'), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::getLocale * @todo Implement testGetLocale(). * * @return void */ public function testGetLocale() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::getFirstDay * @todo Implement testGetFirstDay(). * * @return void */ public function testGetFirstDay() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @covers JLanguage::parseLanguageFiles * * @return void */ public function testParseLanguageFiles() { $dir = __DIR__ . '/data/language'; $option = array( 'name' => 'English (United Kingdom)', 'tag' => 'en-GB', 'rtl' => '0', 'locale' => 'en_GB.utf8, en_GB.UTF-8, en_GB, eng_GB, en, english, english-uk, uk, gbr, britain, england,' . ' great britain, uk, united kingdom, united-kingdom', 'firstDay' => '0' ); $expected = array( 'en-GB' => $option ); $result = JLanguage::parseLanguageFiles($dir); $this->assertEquals( $expected, $result, 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::parseXMLLanguageFile * * @return void */ public function testParseXMLLanguageFile() { $option = array( 'name' => 'English (United Kingdom)', 'tag' => 'en-GB', 'rtl' => '0', 'locale' => 'en_GB.utf8, en_GB.UTF-8, en_GB, eng_GB, en, english, english-uk, uk, gbr, britain, england, great britain,' . ' uk, united kingdom, united-kingdom', 'firstDay' => '0' ); $path = __DIR__ . '/data/language/en-GB/en-GB.xml'; $this->assertEquals( $option, JLanguage::parseXMLLanguageFile($path), 'Line: ' . __LINE__ ); $path2 = __DIR__ . '/data/language/es-ES/es-ES.xml'; $this->assertEquals( $option, JLanguage::parseXMLLanguageFile($path), 'Line: ' . __LINE__ ); } /** * Test... * * @covers JLanguage::parseXMLLanguageFile * @expectedException RuntimeException * * @return void */ public function testParseXMLLanguageFileException() { $path = __DIR__ . '/data/language/es-ES/es-ES.xml'; JLanguage::parseXMLLanguageFile($path); } }
songxiafeng/joomla-platform
tests/suites/unit/joomla/language/JLanguageTest.php
PHP
gpl-2.0
26,706
<?php /** * Joomla! 1.5 component irbtools * * @version $Id: view.html.php 2010-10-13 07:12:40 svn $ * @author IRB Barcelona * @package Joomla * @subpackage irbtools * @license GNU/GPL * * IRB Barcelona Tools * * This component file was created using the Joomla Component Creator by Not Web Design * http://www.notwebdesign.com/joomla_component_creator/ * */ // no direct access defined('_JEXEC') or die('Restricted access'); // Import Joomla! libraries jimport( 'joomla.application.component.view'); class IrbtoolsViewDefault extends JView { function display($tpl = null) { parent::display($tpl); } } ?>
rbartolomeirb/joomlaatirb
tools/com_irbtools/build/administrator/components/com_irbtools/views/default/view.html.php
PHP
gpl-2.0
663
// $Id: Dynamic_Service_Dependency.cpp 96985 2013-04-11 15:50:32Z huangh $ #include "ace/ACE.h" #include "ace/DLL_Manager.h" #include "ace/Dynamic_Service_Dependency.h" #include "ace/Service_Config.h" #include "ace/Log_Category.h" ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_Dynamic_Service_Dependency::ACE_Dynamic_Service_Dependency (const ACE_TCHAR *principal) { this->init (ACE_Service_Config::current (), principal); } ACE_Dynamic_Service_Dependency::ACE_Dynamic_Service_Dependency (const ACE_Service_Gestalt *cfg, const ACE_TCHAR *principal) { this->init (cfg, principal); } ACE_Dynamic_Service_Dependency::~ACE_Dynamic_Service_Dependency (void) { if (ACE::debug ()) ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) DSD, this=%@ - destroying\n"), this)); } void ACE_Dynamic_Service_Dependency::init (const ACE_Service_Gestalt *cfg, const ACE_TCHAR *principal) { const ACE_Service_Type* st = ACE_Dynamic_Service_Base::find_i (cfg, principal,false); if (ACE::debug ()) { ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) DSD, this=%@ - creating dependency on "), this)); st->dump (); } this->tracker_ = st->dll (); } ACE_END_VERSIONED_NAMESPACE_DECL
xIchigox/ArkCORE-NG
dep/acelite/ace/Dynamic_Service_Dependency.cpp
C++
gpl-2.0
1,326
<?php /** * @Project NUKEVIET 4.x * @Author VINADES.,JSC (contact@vinades.vn) * @Copyright (C) 2016 VINADES.,JSC. All rights reserved * @Language Français * @License CC BY-SA (http://creativecommons.org/licenses/by-sa/4.0/) * @Createdate Jul 31, 2015, 09:30:00 AM */ if (! defined('NV_ADMIN') or ! defined('NV_MAINFILE')) { die( 'Stop!!!' ); } $lang_translator['author'] = 'Nguyễn Phú Thành'; $lang_translator['createdate'] = '31/07/2015, 16:30'; $lang_translator['copyright'] = 'phuthanh.nguyen215@gmail.com'; $lang_translator['info'] = ''; $lang_translator['langtype'] = 'lang_block'; $lang_block['catid'] = 'Sujet'; $lang_block['numrow'] = 'Nombre d\'articles affichés'; $lang_block['type'] = 'Méthode d\'affichage'; $lang_block['showtooltip'] = 'Affichage de tooltip'; $lang_block['tooltip_position'] = 'Position'; $lang_block['tooltip_position_top'] = 'Au dessus'; $lang_block['tooltip_position_bottom'] = 'Au dessous'; $lang_block['tooltip_position_left'] = 'A gauche'; $lang_block['tooltip_position_right'] = 'A droite'; $lang_block['tooltip_length'] = 'Numero';
nhatnhatnet/nukecms
modules/news/language/block.global.block_news_cat_fr.php
PHP
gpl-2.0
1,084
/* java.lang.Number Copyright (C) 1998, 2001 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.lang; import java.io.Serializable; /** ** Number is a generic superclass of all the numeric classes, namely ** <code>Byte</code>, <code>Short</code>, <code>Integer</code>, ** <code>Long</code>, <code>Float</code>, and <code>Double</code>. ** ** It provides ways to convert from any one value to any other. ** ** @author Paul Fisher ** @author John Keiser ** @author Warren Levy ** @since JDK1.0 **/ public abstract class Number implements Serializable { /** Return the value of this <code>Number</code> as a <code>byte</code>. ** @return the value of this <code>Number</code> as a <code>byte</code>. **/ public byte byteValue() { return (byte) intValue(); } /** Return the value of this <code>Number</code> as a <code>short</code>. ** @return the value of this <code>Number</code> as a <code>short</code>. **/ public short shortValue() { return (short) intValue(); } /** Return the value of this <code>Number</code> as an <code>int</code>. ** @return the value of this <code>Number</code> as an <code>int</code>. **/ public abstract int intValue(); /** Return the value of this <code>Number</code> as a <code>long</code>. ** @return the value of this <code>Number</code> as a <code>long</code>. **/ public abstract long longValue(); /** Return the value of this <code>Number</code> as a <code>float</code>. ** @return the value of this <code>Number</code> as a <code>float</code>. **/ public abstract float floatValue(); /** Return the value of this <code>Number</code> as a <code>float</code>. ** @return the value of this <code>Number</code> as a <code>float</code>. **/ public abstract double doubleValue(); private static final long serialVersionUID = -8742448824652078965L; }
aosm/gcc3
libjava/java/lang/Number.java
Java
gpl-2.0
3,524
<?php require(__DATAGEN_META_CONTROLS__ . '/AssetModelCustomFieldHelperMetaControlGen.class.php'); /** * This is a MetaControl customizable subclass, providing a QForm or QPanel access to event handlers * and QControls to perform the Create, Edit, and Delete functionality of the * AssetModelCustomFieldHelper class. This code-generated class extends from * the generated MetaControl class, which contains all the basic elements to help a QPanel or QForm * display an HTML form that can manipulate a single AssetModelCustomFieldHelper object. * * To take advantage of some (or all) of these control objects, you * must create a new QForm or QPanel which instantiates a AssetModelCustomFieldHelperMetaControl * class. * * This file is intended to be modified. Subsequent code regenerations will NOT modify * or overwrite this file. * * @package My Application * @subpackage MetaControls */ class AssetModelCustomFieldHelperMetaControl extends AssetModelCustomFieldHelperMetaControlGen { } ?>
mmuir-ca/tracmor
includes/data_meta_controls/AssetModelCustomFieldHelperMetaControl.class.php
PHP
gpl-2.0
1,030
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Various table operations * * @package PhpMyAdmin */ use PMA\libraries\Partition; use PMA\libraries\Table; use PMA\libraries\Response; /** * */ require_once 'libraries/common.inc.php'; /** * functions implementation for this script */ require_once 'libraries/check_user_privileges.lib.php'; require_once 'libraries/operations.lib.php'; $pma_table = new Table($GLOBALS['table'], $GLOBALS['db']); /** * Load JavaScript files */ $response = Response::getInstance(); $header = $response->getHeader(); $scripts = $header->getScripts(); $scripts->addFile('tbl_operations.js'); /** * Runs common work */ require 'libraries/tbl_common.inc.php'; $url_query .= '&amp;goto=tbl_operations.php&amp;back=tbl_operations.php'; $url_params['goto'] = $url_params['back'] = 'tbl_operations.php'; /** * Gets relation settings */ $cfgRelation = PMA_getRelationsParam(); // reselect current db (needed in some cases probably due to // the calling of relation.lib.php) $GLOBALS['dbi']->selectDb($GLOBALS['db']); /** * Gets tables information */ $pma_table = $GLOBALS['dbi']->getTable( $GLOBALS['db'], $GLOBALS['table'] ); $reread_info = $pma_table->getStatusInfo(null, false); $GLOBALS['showtable'] = $pma_table->getStatusInfo(null, (isset($reread_info) && $reread_info ? true : false)); if ($pma_table->isView()) { $tbl_is_view = true; $tbl_storage_engine = __('View'); $show_comment = null; } else { $tbl_is_view = false; $tbl_storage_engine = $pma_table->getStorageEngine(); $show_comment = $pma_table->getComment(); } $tbl_collation = $pma_table->getCollation(); $table_info_num_rows = $pma_table->getNumRows(); $row_format = $pma_table->getRowFormat(); $auto_increment = $pma_table->getAutoIncrement(); $create_options = $pma_table->getCreateOptions(); // set initial value of these variables, based on the current table engine if ($pma_table->isEngine('ARIA')) { // the value for transactional can be implicit // (no create option found, in this case it means 1) // or explicit (option found with a value of 0 or 1) // ($create_options['transactional'] may have been set by Table class, // from the $create_options) $create_options['transactional'] = (isset($create_options['transactional']) && $create_options['transactional'] == '0') ? '0' : '1'; $create_options['page_checksum'] = (isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : ''; } $pma_table = $GLOBALS['dbi']->getTable( $GLOBALS['db'], $GLOBALS['table'] ); $reread_info = false; $table_alters = array(); /** * If the table has to be moved to some other database */ if (isset($_REQUEST['submit_move']) || isset($_REQUEST['submit_copy'])) { //$_message = ''; PMA_moveOrCopyTable($db, $table); // This was ended in an Ajax call exit; } /** * If the table has to be maintained */ if (isset($_REQUEST['table_maintenance'])) { include_once 'sql.php'; unset($result); } /** * Updates table comment, type and options if required */ if (isset($_REQUEST['submitoptions'])) { $_message = ''; $warning_messages = array(); if (isset($_REQUEST['new_name'])) { // Get original names before rename operation $oldTable = $pma_table->getName(); $oldDb = $pma_table->getDbName(); if ($pma_table->rename($_REQUEST['new_name'])) { if (isset($_REQUEST['adjust_privileges']) && ! empty($_REQUEST['adjust_privileges']) ) { PMA_AdjustPrivileges_renameOrMoveTable( $oldDb, $oldTable, $_REQUEST['db'], $_REQUEST['new_name'] ); } // Reselect the original DB $GLOBALS['db'] = $oldDb; $GLOBALS['dbi']->selectDb($oldDb); $_message .= $pma_table->getLastMessage(); $result = true; $GLOBALS['table'] = $pma_table->getName(); $reread_info = true; $reload = true; } else { $_message .= $pma_table->getLastError(); $result = false; } } if (! empty($_REQUEST['new_tbl_storage_engine']) && mb_strtoupper($_REQUEST['new_tbl_storage_engine']) !== $tbl_storage_engine ) { $new_tbl_storage_engine = mb_strtoupper($_REQUEST['new_tbl_storage_engine']); if ($pma_table->isEngine('ARIA')) { $create_options['transactional'] = (isset($create_options['transactional']) && $create_options['transactional'] == '0') ? '0' : '1'; $create_options['page_checksum'] = (isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : ''; } } else { $new_tbl_storage_engine = ''; } $row_format = (isset($create_options['row_format'])) ? $create_options['row_format'] : $pma_table->getRowFormat(); $table_alters = PMA_getTableAltersArray( $pma_table, $create_options['pack_keys'], (empty($create_options['checksum']) ? '0' : '1'), ((isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : ''), (empty($create_options['delay_key_write']) ? '0' : '1'), $row_format, $new_tbl_storage_engine, ((isset($create_options['transactional']) && $create_options['transactional'] == '0') ? '0' : '1'), $tbl_collation ); if (count($table_alters) > 0) { $sql_query = 'ALTER TABLE ' . PMA\libraries\Util::backquote($GLOBALS['table']); $sql_query .= "\r\n" . implode("\r\n", $table_alters); $sql_query .= ';'; $result .= $GLOBALS['dbi']->query($sql_query) ? true : false; $reread_info = true; unset($table_alters); $warning_messages = PMA_getWarningMessagesArray(); } if (isset($_REQUEST['tbl_collation']) && ! empty($_REQUEST['tbl_collation']) && isset($_REQUEST['change_all_collations']) && ! empty($_REQUEST['change_all_collations']) ) { PMA_changeAllColumnsCollation( $GLOBALS['db'], $GLOBALS['table'], $_REQUEST['tbl_collation'] ); } } /** * Reordering the table has been requested by the user */ if (isset($_REQUEST['submitorderby']) && ! empty($_REQUEST['order_field'])) { list($sql_query, $result) = PMA_getQueryAndResultForReorderingTable(); } // end if /** * A partition operation has been requested by the user */ if (isset($_REQUEST['submit_partition']) && ! empty($_REQUEST['partition_operation']) ) { list($sql_query, $result) = PMA_getQueryAndResultForPartition(); } // end if if ($reread_info) { // to avoid showing the old value (for example the AUTO_INCREMENT) after // a change, clear the cache $GLOBALS['dbi']->clearTableCache(); $GLOBALS['dbi']->selectDb($GLOBALS['db']); $GLOBALS['showtable'] = $pma_table->getStatusInfo(null, true); if ($pma_table->isView()) { $tbl_is_view = true; $tbl_storage_engine = __('View'); $show_comment = null; } else { $tbl_is_view = false; $tbl_storage_engine = $pma_table->getStorageEngine(); $show_comment = $pma_table->getComment(); } $tbl_collation = $pma_table->getCollation(); $table_info_num_rows = $pma_table->getNumRows(); $row_format = $pma_table->getRowFormat(); $auto_increment = $pma_table->getAutoIncrement(); $create_options = $pma_table->getCreateOptions(); } unset($reread_info); if (isset($result) && empty($message_to_show)) { if (empty($_message)) { if (empty($sql_query)) { $_message = PMA\libraries\Message::success(__('No change')); } else { $_message = $result ? PMA\libraries\Message::success() : PMA\libraries\Message::error(); } if ($response->isAjax()) { $response->setRequestStatus($_message->isSuccess()); $response->addJSON('message', $_message); if (!empty($sql_query)) { $response->addJSON( 'sql_query', PMA\libraries\Util::getMessage(null, $sql_query) ); } exit; } } else { $_message = $result ? PMA\libraries\Message::success($_message) : PMA\libraries\Message::error($_message); } if (! empty($warning_messages)) { $_message = new PMA\libraries\Message; $_message->addMessagesString($warning_messages); $_message->isError(true); if ($response->isAjax()) { $response->setRequestStatus(false); $response->addJSON('message', $_message); if (!empty($sql_query)) { $response->addJSON( 'sql_query', PMA\libraries\Util::getMessage(null, $sql_query) ); } exit; } unset($warning_messages); } if (empty($sql_query)) { $response->addHTML( $_message->getDisplay() ); } else { $response->addHTML( PMA\libraries\Util::getMessage($_message, $sql_query) ); } unset($_message); } $url_params['goto'] = $url_params['back'] = 'tbl_operations.php'; /** * Get columns names */ $columns = $GLOBALS['dbi']->getColumns($GLOBALS['db'], $GLOBALS['table']); /** * Displays the page */ $response->addHTML('<div id="boxContainer" data-box-width="300">'); /** * Order the table */ $hideOrderTable = false; // `ALTER TABLE ORDER BY` does not make sense for InnoDB tables that contain // a user-defined clustered index (PRIMARY KEY or NOT NULL UNIQUE index). // InnoDB always orders table rows according to such an index if one is present. if ($tbl_storage_engine == 'INNODB') { $indexes = PMA\libraries\Index::getFromTable($GLOBALS['table'], $GLOBALS['db']); foreach ($indexes as $name => $idx) { if ($name == 'PRIMARY') { $hideOrderTable = true; break; } elseif (! $idx->getNonUnique()) { $notNull = true; foreach ($idx->getColumns() as $column) { if ($column->getNull()) { $notNull = false; break; } } if ($notNull) { $hideOrderTable = true; break; } } } } if (! $hideOrderTable) { $response->addHTML(PMA_getHtmlForOrderTheTable($columns)); } /** * Move table */ $response->addHTML(PMA_getHtmlForMoveTable()); if (mb_strstr($show_comment, '; InnoDB free') === false) { if (mb_strstr($show_comment, 'InnoDB free') === false) { // only user entered comment $comment = $show_comment; } else { // here we have just InnoDB generated part $comment = ''; } } else { // remove InnoDB comment from end, just the minimal part (*? is non greedy) $comment = preg_replace('@; InnoDB free:.*?$@', '', $show_comment); } // PACK_KEYS: MyISAM or ISAM // DELAY_KEY_WRITE, CHECKSUM, : MyISAM only // AUTO_INCREMENT: MyISAM and InnoDB since 5.0.3, PBXT // Here should be version check for InnoDB, however it is supported // in >5.0.4, >4.1.12 and >4.0.11, so I decided not to // check for version $response->addHTML( PMA_getTableOptionDiv( $pma_table, $comment, $tbl_collation, $tbl_storage_engine, $create_options['pack_keys'], $auto_increment, (empty($create_options['delay_key_write']) ? '0' : '1'), ((isset($create_options['transactional']) && $create_options['transactional'] == '0') ? '0' : '1'), ((isset($create_options['page_checksum'])) ? $create_options['page_checksum'] : ''), (empty($create_options['checksum']) ? '0' : '1') ) ); /** * Copy table */ $response->addHTML(PMA_getHtmlForCopytable()); /** * Table maintenance */ $response->addHTML( PMA_getHtmlForTableMaintenance($pma_table, $url_params) ); if (! (isset($db_is_system_schema) && $db_is_system_schema)) { $truncate_table_url_params = array(); $drop_table_url_params = array(); if (! $tbl_is_view && ! (isset($db_is_system_schema) && $db_is_system_schema) ) { $this_sql_query = 'TRUNCATE TABLE ' . PMA\libraries\Util::backquote($GLOBALS['table']); $truncate_table_url_params = array_merge( $url_params, array( 'sql_query' => $this_sql_query, 'goto' => 'tbl_structure.php', 'reload' => '1', 'message_to_show' => sprintf( __('Table %s has been emptied.'), htmlspecialchars($table) ), ) ); } if (! (isset($db_is_system_schema) && $db_is_system_schema)) { $this_sql_query = 'DROP TABLE ' . PMA\libraries\Util::backquote($GLOBALS['table']); $drop_table_url_params = array_merge( $url_params, array( 'sql_query' => $this_sql_query, 'goto' => 'db_operations.php', 'reload' => '1', 'purge' => '1', 'message_to_show' => sprintf( ($tbl_is_view ? __('View %s has been dropped.') : __('Table %s has been dropped.') ), htmlspecialchars($table) ), // table name is needed to avoid running // PMA_relationsCleanupDatabase() on the whole db later 'table' => $GLOBALS['table'], ) ); } $response->addHTML( PMA_getHtmlForDeleteDataOrTable( $truncate_table_url_params, $drop_table_url_params ) ); } if (Partition::havePartitioning()) { $partition_names = Partition::getPartitionNames($db, $table); // show the Partition maintenance section only if we detect a partition if (! is_null($partition_names[0])) { $response->addHTML( PMA_getHtmlForPartitionMaintenance($partition_names, $url_params) ); } // end if } // end if unset($partition_names); // Referential integrity check // The Referential integrity check was intended for the non-InnoDB // tables for which the relations are defined in pmadb // so I assume that if the current table is InnoDB, I don't display // this choice (InnoDB maintains integrity by itself) if ($cfgRelation['relwork'] && ! $pma_table->isEngine("INNODB")) { $GLOBALS['dbi']->selectDb($GLOBALS['db']); $foreign = PMA_getForeigners($GLOBALS['db'], $GLOBALS['table'], '', 'internal'); if (! empty($foreign)) { $response->addHTML( PMA_getHtmlForReferentialIntegrityCheck($foreign, $url_params) ); } // end if ($foreign) } // end if (!empty($cfg['Server']['relation'])) $response->addHTML('</div>');
ragnerok/phpmyadmin
tbl_operations.php
PHP
gpl-2.0
15,012
<?php /** * @file * Contains \Drupal\config_translation\Tests\ConfigMapperManagerTest. */ namespace Drupal\config_translation\Tests; use Drupal\config_translation\ConfigMapperManager; use Drupal\Core\Language\Language; use Drupal\Core\Language\LanguageInterface; use Drupal\Core\TypedData\TypedDataInterface; use Drupal\Tests\UnitTestCase; use Drupal\Core\TypedData\DataDefinition; use Drupal\Core\TypedData\DataDefinitionInterface; /** * Tests the functionality provided by configuration translation mapper manager. * * @group config_translation */ class ConfigMapperManagerTest extends UnitTestCase { /** * The configuration mapper manager to test. * * @var \Drupal\config_translation\ConfigMapperManager */ protected $configMapperManager; /** * The typed configuration manager used for testing. * * @var \Drupal\Core\Config\TypedConfigManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $typedConfigManager; public function setUp() { $language = new Language(array('id' => 'en')); $language_manager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface'); $language_manager->expects($this->once()) ->method('getCurrentLanguage') ->with(LanguageInterface::TYPE_INTERFACE) ->will($this->returnValue($language)); $this->typedConfigManager = $this->getMockBuilder('Drupal\Core\Config\TypedConfigManagerInterface') ->getMock(); $module_handler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface'); $module_handler->expects($this->once()) ->method('getModuleList') ->with() ->will($this->returnValue(array())); $theme_handler = $this->getMock('Drupal\Core\Extension\ThemeHandlerInterface'); $theme_handler->expects($this->any()) ->method('listInfo') ->will($this->returnValue(array())); $this->configMapperManager = new ConfigMapperManager( $this->getMock('Drupal\Core\Cache\CacheBackendInterface'), $language_manager, $module_handler, $this->typedConfigManager, $theme_handler ); } /** * Tests ConfigMapperManager::hasTranslatable(). * * @param \Drupal\Core\TypedData\TypedDataInterface $element * The schema element to test. * @param bool $expected * The expected return value of ConfigMapperManager::hasTranslatable(). * * @dataProvider providerTestHasTranslatable */ public function testHasTranslatable(TypedDataInterface $element, $expected) { $this->typedConfigManager ->expects($this->once()) ->method('get') ->with('test') ->will($this->returnValue($element)); $result = $this->configMapperManager->hasTranslatable('test'); $this->assertSame($expected, $result); } /** * Provides data for ConfigMapperManager::testHasTranslatable() * * @return array * An array of arrays, where each inner array contains the schema element * to test as the first key and the expected result of * ConfigMapperManager::hasTranslatable() as the second key. */ public function providerTestHasTranslatable() { return array( array($this->getElement(array()), FALSE), array($this->getElement(array('aaa' => 'bbb')), FALSE), array($this->getElement(array('translatable' => FALSE)), FALSE), array($this->getElement(array('translatable' => TRUE)), TRUE), array($this->getNestedElement(array( $this->getElement(array()), )), FALSE), array($this->getNestedElement(array( $this->getElement(array('translatable' => TRUE)), )), TRUE), array($this->getNestedElement(array( $this->getElement(array('aaa' => 'bbb')), $this->getElement(array('ccc' => 'ddd')), $this->getElement(array('eee' => 'fff')), )), FALSE), array($this->getNestedElement(array( $this->getElement(array('aaa' => 'bbb')), $this->getElement(array('ccc' => 'ddd')), $this->getElement(array('translatable' => TRUE)), )), TRUE), array($this->getNestedElement(array( $this->getElement(array('aaa' => 'bbb')), $this->getNestedElement(array( $this->getElement(array('ccc' => 'ddd')), $this->getElement(array('eee' => 'fff')), )), $this->getNestedElement(array( $this->getElement(array('ggg' => 'hhh')), $this->getElement(array('iii' => 'jjj')), )), )), FALSE), array($this->getNestedElement(array( $this->getElement(array('aaa' => 'bbb')), $this->getNestedElement(array( $this->getElement(array('ccc' => 'ddd')), $this->getElement(array('eee' => 'fff')), )), $this->getNestedElement(array( $this->getElement(array('ggg' => 'hhh')), $this->getElement(array('translatable' => TRUE)), )), )), TRUE), ); } /** * Returns a mocked schema element. * * @param array $definition * The definition of the schema element. * * @return \Drupal\Core\Config\Schema\Element * The mocked schema element. */ protected function getElement(array $definition) { $data_definition = new DataDefinition($definition); $element = $this->getMock('Drupal\Core\TypedData\TypedDataInterface'); $element->expects($this->any()) ->method('getDataDefinition') ->will($this->returnValue($data_definition)); return $element; } /** * Returns a mocked nested schema element. * * @param array $elements * An array of simple schema elements. * * @return \Drupal\Core\Config\Schema\Mapping * A nested schema element, containing the passed-in elements. */ protected function getNestedElement(array $elements) { // ConfigMapperManager::findTranslatable() checks for the abstract class // \Drupal\Core\Config\Schema\ArrayElement, but mocking that directly does // not work. $nested_element = $this->getMockBuilder('Drupal\Core\Config\Schema\Mapping') ->disableOriginalConstructor() ->getMock(); $nested_element->expects($this->once()) ->method('getIterator') ->will($this->returnValue(new \ArrayIterator($elements))); return $nested_element; } }
fleeboy/tatt2tatt
core/modules/config_translation/tests/src/ConfigMapperManagerTest.php
PHP
gpl-2.0
6,236
//===--- Diagnostics.cpp - Helper class for error diagnostics -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/ASTMatchers/Dynamic/Diagnostics.h" namespace clang { namespace ast_matchers { namespace dynamic { Diagnostics::ArgStream Diagnostics::pushContextFrame(ContextType Type, SourceRange Range) { ContextStack.emplace_back(); ContextFrame& data = ContextStack.back(); data.Type = Type; data.Range = Range; return ArgStream(&data.Args); } Diagnostics::Context::Context(ConstructMatcherEnum, Diagnostics *Error, StringRef MatcherName, const SourceRange &MatcherRange) : Error(Error) { Error->pushContextFrame(CT_MatcherConstruct, MatcherRange) << MatcherName; } Diagnostics::Context::Context(MatcherArgEnum, Diagnostics *Error, StringRef MatcherName, const SourceRange &MatcherRange, unsigned ArgNumber) : Error(Error) { Error->pushContextFrame(CT_MatcherArg, MatcherRange) << ArgNumber << MatcherName; } Diagnostics::Context::~Context() { Error->ContextStack.pop_back(); } Diagnostics::OverloadContext::OverloadContext(Diagnostics *Error) : Error(Error), BeginIndex(Error->Errors.size()) {} Diagnostics::OverloadContext::~OverloadContext() { // Merge all errors that happened while in this context. if (BeginIndex < Error->Errors.size()) { Diagnostics::ErrorContent &Dest = Error->Errors[BeginIndex]; for (size_t i = BeginIndex + 1, e = Error->Errors.size(); i < e; ++i) { Dest.Messages.push_back(Error->Errors[i].Messages[0]); } Error->Errors.resize(BeginIndex + 1); } } void Diagnostics::OverloadContext::revertErrors() { // Revert the errors. Error->Errors.resize(BeginIndex); } Diagnostics::ArgStream &Diagnostics::ArgStream::operator<<(const Twine &Arg) { Out->push_back(Arg.str()); return *this; } Diagnostics::ArgStream Diagnostics::addError(const SourceRange &Range, ErrorType Error) { Errors.emplace_back(); ErrorContent &Last = Errors.back(); Last.ContextStack = ContextStack; Last.Messages.emplace_back(); Last.Messages.back().Range = Range; Last.Messages.back().Type = Error; return ArgStream(&Last.Messages.back().Args); } static StringRef contextTypeToFormatString(Diagnostics::ContextType Type) { switch (Type) { case Diagnostics::CT_MatcherConstruct: return "Error building matcher $0."; case Diagnostics::CT_MatcherArg: return "Error parsing argument $0 for matcher $1."; } llvm_unreachable("Unknown ContextType value."); } static StringRef errorTypeToFormatString(Diagnostics::ErrorType Type) { switch (Type) { case Diagnostics::ET_RegistryMatcherNotFound: return "Matcher not found: $0"; case Diagnostics::ET_RegistryWrongArgCount: return "Incorrect argument count. (Expected = $0) != (Actual = $1)"; case Diagnostics::ET_RegistryWrongArgType: return "Incorrect type for arg $0. (Expected = $1) != (Actual = $2)"; case Diagnostics::ET_RegistryNotBindable: return "Matcher does not support binding."; case Diagnostics::ET_RegistryAmbiguousOverload: // TODO: Add type info about the overload error. return "Ambiguous matcher overload."; case Diagnostics::ET_RegistryValueNotFound: return "Value not found: $0"; case Diagnostics::ET_ParserStringError: return "Error parsing string token: <$0>"; case Diagnostics::ET_ParserNoOpenParen: return "Error parsing matcher. Found token <$0> while looking for '('."; case Diagnostics::ET_ParserNoCloseParen: return "Error parsing matcher. Found end-of-code while looking for ')'."; case Diagnostics::ET_ParserNoComma: return "Error parsing matcher. Found token <$0> while looking for ','."; case Diagnostics::ET_ParserNoCode: return "End of code found while looking for token."; case Diagnostics::ET_ParserNotAMatcher: return "Input value is not a matcher expression."; case Diagnostics::ET_ParserInvalidToken: return "Invalid token <$0> found when looking for a value."; case Diagnostics::ET_ParserMalformedBindExpr: return "Malformed bind() expression."; case Diagnostics::ET_ParserTrailingCode: return "Expected end of code."; case Diagnostics::ET_ParserUnsignedError: return "Error parsing unsigned token: <$0>"; case Diagnostics::ET_ParserOverloadedType: return "Input value has unresolved overloaded type: $0"; case Diagnostics::ET_None: return "<N/A>"; } llvm_unreachable("Unknown ErrorType value."); } static void formatErrorString(StringRef FormatString, ArrayRef<std::string> Args, llvm::raw_ostream &OS) { while (!FormatString.empty()) { std::pair<StringRef, StringRef> Pieces = FormatString.split("$"); OS << Pieces.first.str(); if (Pieces.second.empty()) break; const char Next = Pieces.second.front(); FormatString = Pieces.second.drop_front(); if (Next >= '0' && Next <= '9') { const unsigned Index = Next - '0'; if (Index < Args.size()) { OS << Args[Index]; } else { OS << "<Argument_Not_Provided>"; } } } } static void maybeAddLineAndColumn(const SourceRange &Range, llvm::raw_ostream &OS) { if (Range.Start.Line > 0 && Range.Start.Column > 0) { OS << Range.Start.Line << ":" << Range.Start.Column << ": "; } } static void printContextFrameToStream(const Diagnostics::ContextFrame &Frame, llvm::raw_ostream &OS) { maybeAddLineAndColumn(Frame.Range, OS); formatErrorString(contextTypeToFormatString(Frame.Type), Frame.Args, OS); } static void printMessageToStream(const Diagnostics::ErrorContent::Message &Message, const Twine Prefix, llvm::raw_ostream &OS) { maybeAddLineAndColumn(Message.Range, OS); OS << Prefix; formatErrorString(errorTypeToFormatString(Message.Type), Message.Args, OS); } static void printErrorContentToStream(const Diagnostics::ErrorContent &Content, llvm::raw_ostream &OS) { if (Content.Messages.size() == 1) { printMessageToStream(Content.Messages[0], "", OS); } else { for (size_t i = 0, e = Content.Messages.size(); i != e; ++i) { if (i != 0) OS << "\n"; printMessageToStream(Content.Messages[i], "Candidate " + Twine(i + 1) + ": ", OS); } } } void Diagnostics::printToStream(llvm::raw_ostream &OS) const { for (size_t i = 0, e = Errors.size(); i != e; ++i) { if (i != 0) OS << "\n"; printErrorContentToStream(Errors[i], OS); } } std::string Diagnostics::toString() const { std::string S; llvm::raw_string_ostream OS(S); printToStream(OS); return OS.str(); } void Diagnostics::printToStreamFull(llvm::raw_ostream &OS) const { for (size_t i = 0, e = Errors.size(); i != e; ++i) { if (i != 0) OS << "\n"; const ErrorContent &Error = Errors[i]; for (size_t i = 0, e = Error.ContextStack.size(); i != e; ++i) { printContextFrameToStream(Error.ContextStack[i], OS); OS << "\n"; } printErrorContentToStream(Error, OS); } } std::string Diagnostics::toStringFull() const { std::string S; llvm::raw_string_ostream OS(S); printToStreamFull(OS); return OS.str(); } } // namespace dynamic } // namespace ast_matchers } // namespace clang
rutgers-apl/Atomicity-Violation-Detector
tdebug-llvm/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
C++
gpl-2.0
7,830
<?php /** *@file * Corp theme's implementation to display a single drupal page. */ global $base_url; $header_style = ''; //$header_bg_file = theme_get_setting('header_bg_file'); //if ($header_bg_file) { // $header_style .= 'filter:;background: url(' . $header_bg_file . ') repeat '; //} $header_bg_file = theme_get_setting('header_bg_file'); if ($header_bg_file) { $header_style .= 'filter:;background: url(' . $header_bg_file . ') repeat '; $header_style .= theme_get_setting('header_bg_alignment') . ';'; } ?> <div id="page" class="<?php print $classes; ?>"<?php print $attributes; ?>> <!-- ______________________ HEADER _______________________ --> <header id="header" style="<?php //echo $header_style; ?>> <?php if ($logo): ?> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo"> <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>"/> </a> <?php endif; ?> <?php if ($site_name || $site_slogan): ?> <hgroup id="name-and-slogan"> <?php if ($site_name): ?> <?php if ($title): ?> <div id="site-name"> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><?php print $site_name; ?></a> </div> <?php else: /* Use h1 when the content title is empty */ ?> <h1 id="site-name"> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><?php print $site_name; ?></a> </h1> <?php endif; ?> <?php endif; ?> <?php if ($site_slogan): ?> <div id="site-slogan"><?php print $site_slogan; ?></div> <?php endif; ?> </hgroup> <?php endif; ?> <?php if ($page['header']): ?> <div id="header-region"> <?php print render($page['header']); ?> </div> <?php endif; ?> <!-- customize social links code --> <?php if (theme_get_setting('socialicon_display', 'corp')): ?> <?php $twitter_url = check_plain(theme_get_setting('twitter_url', 'corp')); $facebook_url = check_plain(theme_get_setting('facebook_url', 'corp')); $linkedin_url = check_plain(theme_get_setting('linkedin_url', 'corp')); $theme_path_social = base_path() . drupal_get_path('theme', 'corp'); ?> <div id="socialbar"> <ul class="social"> <?php if ($facebook_url): ?><li> <a href="<?php print $facebook_url; ?>" target="_blank"> <img src="<?php print $theme_path_social; ?>/images/facebook.png"> </a> </li> <?php endif; ?> <?php if ($twitter_url): ?><li> <a href="<?php print $twitter_url; ?>" target="_blank"> <img src="<?php print $theme_path_social; ?>/images/twitter.png"> </a> </li> <?php endif; ?> <?php if ($linkedin_url): ?><li> <a href="<?php print $linkedin_url; ?>" target="_blank"> <img src="<?php print $theme_path_social; ?>/images/in.png"> </a> </li> <?php endif; ?> <li> <a href="<?php print $front_page; ?>rss.xml"> <img src="<?php print $theme_path_social; ?>/images/rss.png"> </a> </li> </ul> </div> <?php endif; ?> <!-- customize social links code --> <div style="clear:both;"></div> </header> <!-- /header --> <?php if ($main_menu || $secondary_menu): ?> <nav id="navigation" class="menu <?php if (!empty($main_menu)) {print "with-primary";} if (!empty($secondary_menu)) {print " with-secondary";} ?>"> <?php print theme('links', array('links' => $main_menu, 'attributes' => array('id' => 'primary', 'class' => array('links', 'clearfix', 'main-menu')))); ?> <?php print theme('links', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary', 'class' => array('links', 'clearfix', 'sub-menu')))); ?> </nav> <!-- /navigation --> <?php endif; ?> <!--code to print the image in region--> <div id="banner_img" style="<?php echo $header_style; ?>"></div> <!-- ______________________ MAIN _______________________ --> <div id="main" class="clearfix"> <section id="content"> <?php if ($breadcrumb || $title|| $messages || $tabs || $action_links): ?> <div id="content-header"> <?php print $breadcrumb; ?> <?php if ($page['highlighted']): ?> <div id="highlighted"><?php print render($page['highlighted']) ?></div> <?php endif; ?> <?php print render($title_prefix); ?> <?php if ($title): ?> <h1 class="title"><?php print $title; ?></h1> <?php endif; ?> <?php print render($title_suffix); ?> <?php print $messages; ?> <?php print render($page['help']); ?> <?php if ($tabs): ?> <div class="tabs"><?php print render($tabs); ?></div> <?php endif; ?> <?php if ($action_links): ?> <ul class="action-links"><?php print render($action_links); ?></ul> <?php endif; ?> </div> <!-- /#content-header --> <?php endif; ?> <div id="content-area"> <?php print render($page['content']) ?> </div> <?php print $feed_icons; ?> </section> <!-- /content-inner /content --> <?php if ($page['sidebar_first']): ?> <aside id="sidebar-first" class="column sidebar first"> <?php print render($page['sidebar_first']); ?> </aside> <?php endif; ?> <!-- /sidebar-first --> <?php if ($page['sidebar_second']): ?> <aside id="sidebar-second" class="column sidebar second"> <?php print render($page['sidebar_second']); ?> </aside> <?php endif; ?> <!-- /sidebar-second --> </div> <!-- /main --> <!-- ______________________ PAGE BOTTOM _______________________ --> <div style="clear:both"></div> <?php if ($page['content_bottom']): ?> <div id="content-bottom"> <?php print render($page['content_bottom']); ?> </div> <!-- /footer --> <?php endif; ?> <!--Custom Bottom Columns--> <?php if ($page['bottom_column_first'] | $page['bottom_column_second'] | $page['bottom_column_third'] ) { ?> <div id="bottom-columns"> <?php print corp_build_columns( array( render($page['bottom_column_first']), render($page['bottom_column_second']), render($page['bottom_column_third']), )); ?> </div> <!--/bottom-columns --> <?php } ?> <!-- ______________________ FOOTER _______________________ --> <?php if ($page['footer']): ?> <footer id="footer"> <?php print render($page['footer']); ?> </footer> <!-- /footer --> <?php endif; ?> </div> <!-- /page -->
billmagee/bottomline
sites/all/themes/corp/templates/page.tpl.php
PHP
gpl-2.0
6,771
/** * \file Author.cpp * This file is part of LyX, the document processor. * Licence details can be found in the file COPYING. * * \author John Levon * * Full author contact details are available in file CREDITS. */ #include <config.h> #include "Author.h" #include "support/lassert.h" #include "support/lstrings.h" #include <algorithm> #include <istream> using namespace std; using namespace lyx::support; namespace lyx { static int computeHash(docstring const & name, docstring const & email) { string const full_author_string = to_utf8(name + email); // Bernstein's hash function unsigned int hash = 5381; for (unsigned int i = 0; i < full_author_string.length(); ++i) hash = ((hash << 5) + hash) + (unsigned int)(full_author_string[i]); return int(hash); } Author::Author(docstring const & name, docstring const & email) : name_(name), email_(email), used_(true) { buffer_id_ = computeHash(name_, email_); } bool operator==(Author const & l, Author const & r) { return l.name() == r.name() && l.email() == r.email(); } ostream & operator<<(ostream & os, Author const & a) { // FIXME UNICODE os << a.buffer_id_ << " \"" << to_utf8(a.name_) << "\" " << to_utf8(a.email_); return os; } istream & operator>>(istream & is, Author & a) { string s; is >> a.buffer_id_; getline(is, s); // FIXME UNICODE a.name_ = from_utf8(trim(token(s, '\"', 1))); a.email_ = from_utf8(trim(token(s, '\"', 2))); return is; } bool author_smaller(Author const & lhs, Author const & rhs) { return lhs.bufferId() < rhs.bufferId(); } AuthorList::AuthorList() : last_id_(0) {} int AuthorList::record(Author const & a) { // If we record an author which equals the current // author, we copy the buffer_id, so that it will // keep the same id in the file. if (!authors_.empty() && a == authors_[0]) authors_[0].setBufferId(a.bufferId()); Authors::const_iterator it(authors_.begin()); Authors::const_iterator itend(authors_.end()); for (int i = 0; it != itend; ++it, ++i) { if (*it == a) return i; } authors_.push_back(a); return last_id_++; } void AuthorList::record(int id, Author const & a) { LBUFERR(unsigned(id) < authors_.size()); authors_[id] = a; } void AuthorList::recordCurrentAuthor(Author const & a) { // current author has id 0 record(0, a); } Author const & AuthorList::get(int id) const { LASSERT(id < (int)authors_.size() , return authors_[0]); return authors_[id]; } AuthorList::Authors::const_iterator AuthorList::begin() const { return authors_.begin(); } AuthorList::Authors::const_iterator AuthorList::end() const { return authors_.end(); } void AuthorList::sort() { std::sort(authors_.begin(), authors_.end(), author_smaller); } ostream & operator<<(ostream & os, AuthorList const & a) { // Copy the authorlist, because we don't want to sort the original AuthorList sorted = a; sorted.sort(); AuthorList::Authors::const_iterator a_it = sorted.begin(); AuthorList::Authors::const_iterator a_end = sorted.end(); for (a_it = sorted.begin(); a_it != a_end; ++a_it) { if (a_it->used()) os << "\\author " << *a_it << "\n"; } return os; } } // namespace lyx
bpiwowar/lyx
src/Author.cpp
C++
gpl-2.0
3,160
//@tag dom,core //@define Ext-more //@require Ext.EventManager /** * @class Ext * * Ext is the global namespace for the whole Sencha Touch framework. Every class, function and configuration for the * whole framework exists under this single global variable. The Ext singleton itself contains a set of useful helper * functions (like {@link #apply}, {@link #min} and others), but most of the framework that you use day to day exists * in specialized classes (for example {@link Ext.Panel}, {@link Ext.Carousel} and others). * * If you are new to Sencha Touch we recommend starting with the [Getting Started Guide][getting_started] to * get a feel for how the framework operates. After that, use the more focused guides on subjects like panels, forms and data * to broaden your understanding. The MVC guides take you through the process of building full applications using the * framework, and detail how to deploy them to production. * * The functions listed below are mostly utility functions used internally by many of the classes shipped in the * framework, but also often useful in your own apps. * * A method that is crucial to beginning your application is {@link #setup Ext.setup}. Please refer to it's documentation, or the * [Getting Started Guide][getting_started] as a reference on beginning your application. * * Ext.setup({ * onReady: function() { * Ext.Viewport.add({ * xtype: 'component', * html: 'Hello world!' * }); * } * }); * * [getting_started]: #!/guide/getting_started */ Ext.setVersion('touch', '2.1.0'); Ext.apply(Ext, { /** * The version of the framework * @type String */ version: Ext.getVersion('touch'), /** * @private */ idSeed: 0, /** * Repaints the whole page. This fixes frequently encountered painting issues in mobile Safari. */ repaint: function() { var mask = Ext.getBody().createChild({ cls: Ext.baseCSSPrefix + 'mask ' + Ext.baseCSSPrefix + 'mask-transparent' }); setTimeout(function() { mask.destroy(); }, 0); }, /** * Generates unique ids. If the element already has an `id`, it is unchanged. * @param {Mixed} el (optional) The element to generate an id for. * @param {String} [prefix=ext-gen] (optional) The `id` prefix. * @return {String} The generated `id`. */ id: function(el, prefix) { if (el && el.id) { return el.id; } el = Ext.getDom(el) || {}; if (el === document || el === document.documentElement) { el.id = 'ext-application'; } else if (el === document.body) { el.id = 'ext-viewport'; } else if (el === window) { el.id = 'ext-window'; } el.id = el.id || ((prefix || 'ext-element-') + (++Ext.idSeed)); return el.id; }, /** * Returns the current document body as an {@link Ext.Element}. * @return {Ext.Element} The document body. */ getBody: function() { if (!Ext.documentBodyElement) { if (!document.body) { throw new Error("[Ext.getBody] document.body does not exist at this point"); } Ext.documentBodyElement = Ext.get(document.body); } return Ext.documentBodyElement; }, /** * Returns the current document head as an {@link Ext.Element}. * @return {Ext.Element} The document head. */ getHead: function() { if (!Ext.documentHeadElement) { Ext.documentHeadElement = Ext.get(document.head || document.getElementsByTagName('head')[0]); } return Ext.documentHeadElement; }, /** * Returns the current HTML document object as an {@link Ext.Element}. * @return {Ext.Element} The document. */ getDoc: function() { if (!Ext.documentElement) { Ext.documentElement = Ext.get(document); } return Ext.documentElement; }, /** * This is shorthand reference to {@link Ext.ComponentMgr#get}. * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#getId id} * @param {String} id The component {@link Ext.Component#getId id} * @return {Ext.Component} The Component, `undefined` if not found, or `null` if a * Class was found. */ getCmp: function(id) { return Ext.ComponentMgr.get(id); }, /** * Copies a set of named properties from the source object to the destination object. * * Example: * * ImageComponent = Ext.extend(Ext.Component, { * initComponent: function() { * this.autoEl = { tag: 'img' }; * MyComponent.superclass.initComponent.apply(this, arguments); * this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height'); * } * }); * * Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead. * * @param {Object} dest The destination object. * @param {Object} source The source object. * @param {String/String[]} names Either an Array of property names, or a comma-delimited list * of property names to copy. * @param {Boolean} [usePrototypeKeys=false] (optional) Pass `true` to copy keys off of the prototype as well as the instance. * @return {Object} The modified object. */ copyTo : function(dest, source, names, usePrototypeKeys) { if (typeof names == 'string') { names = names.split(/[,;\s]/); } Ext.each (names, function(name) { if (usePrototypeKeys || source.hasOwnProperty(name)) { dest[name] = source[name]; } }, this); return dest; }, /** * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the * DOM (if applicable) and calling their destroy functions (if available). This method is primarily * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}. * Any number of elements and/or components can be passed into this function in a single * call as separate arguments. * @param {Mixed...} args An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy. */ destroy: function() { var args = arguments, ln = args.length, i, item; for (i = 0; i < ln; i++) { item = args[i]; if (item) { if (Ext.isArray(item)) { this.destroy.apply(this, item); } else if (Ext.isFunction(item.destroy)) { item.destroy(); } } } }, /** * Return the dom node for the passed String (id), dom node, or Ext.Element. * Here are some examples: * * // gets dom node based on id * var elDom = Ext.getDom('elId'); * * // gets dom node based on the dom node * var elDom1 = Ext.getDom(elDom); * * // If we don't know if we are working with an * // Ext.Element or a dom node use Ext.getDom * function(el){ * var dom = Ext.getDom(el); * // do something with the dom node * } * * __Note:__ the dom node to be found actually needs to exist (be rendered, etc) * when this method is called to be successful. * @param {Mixed} el * @return {HTMLElement} */ getDom: function(el) { if (!el || !document) { return null; } return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el); }, /** * Removes this element from the document, removes all DOM event listeners, and deletes the cache reference. * All DOM event listeners are removed from this element. * @param {HTMLElement} node The node to remove. */ removeNode: function(node) { if (node && node.parentNode && node.tagName != 'BODY') { Ext.get(node).clearListeners(); node.parentNode.removeChild(node); delete Ext.cache[node.id]; } }, /** * @private */ defaultSetupConfig: { eventPublishers: { dom: { xclass: 'Ext.event.publisher.Dom' }, touchGesture: { xclass: 'Ext.event.publisher.TouchGesture', recognizers: { drag: { xclass: 'Ext.event.recognizer.Drag' }, tap: { xclass: 'Ext.event.recognizer.Tap' }, doubleTap: { xclass: 'Ext.event.recognizer.DoubleTap' }, longPress: { xclass: 'Ext.event.recognizer.LongPress' }, swipe: { xclass: 'Ext.event.recognizer.HorizontalSwipe' }, pinch: { xclass: 'Ext.event.recognizer.Pinch' }, rotate: { xclass: 'Ext.event.recognizer.Rotate' } } }, componentDelegation: { xclass: 'Ext.event.publisher.ComponentDelegation' }, componentPaint: { xclass: 'Ext.event.publisher.ComponentPaint' }, // componentSize: { // xclass: 'Ext.event.publisher.ComponentSize' // }, elementPaint: { xclass: 'Ext.event.publisher.ElementPaint' }, elementSize: { xclass: 'Ext.event.publisher.ElementSize' } }, //<feature logger> logger: { enabled: true, xclass: 'Ext.log.Logger', minPriority: 'deprecate', writers: { console: { xclass: 'Ext.log.writer.Console', throwOnErrors: true, formatter: { xclass: 'Ext.log.formatter.Default' } } } }, //</feature> animator: { xclass: 'Ext.fx.Runner' }, viewport: { xclass: 'Ext.viewport.Viewport' } }, /** * @private */ isSetup: false, /** * This indicate the start timestamp of current cycle. * It is only reliable during dom-event-initiated cycles and * {@link Ext.draw.Animator} initiated cycles. */ frameStartTime: +new Date(), /** * @private */ setupListeners: [], /** * @private */ onSetup: function(fn, scope) { if (Ext.isSetup) { fn.call(scope); } else { Ext.setupListeners.push({ fn: fn, scope: scope }); } }, /** * Ext.setup() is the entry-point to initialize a Sencha Touch application. Note that if your application makes * use of MVC architecture, use {@link Ext#application} instead. * * This method accepts one single argument in object format. The most basic use of Ext.setup() is as follows: * * Ext.setup({ * onReady: function() { * // ... * } * }); * * This sets up the viewport, initializes the event system, instantiates a default animation runner, and a default * logger (during development). When all of that is ready, it invokes the callback function given to the `onReady` key. * * The default scope (`this`) of `onReady` is the main viewport. By default the viewport instance is stored in * {@link Ext.Viewport}. For example, this snippet adds a 'Hello World' button that is centered on the screen: * * Ext.setup({ * onReady: function() { * this.add({ * xtype: 'button', * centered: true, * text: 'Hello world!' * }); // Equivalent to Ext.Viewport.add(...) * } * }); * * @param {Object} config An object with the following config options: * * @param {Function} config.onReady * A function to be called when the application is ready. Your application logic should be here. * * @param {Object} config.viewport * A custom config object to be used when creating the global {@link Ext.Viewport} instance. Please refer to the * {@link Ext.Viewport} documentation for more information. * * Ext.setup({ * viewport: { * width: 500, * height: 500 * }, * onReady: function() { * // ... * } * }); * * @param {String/Object} config.icon * Specifies a set of URLs to the application icon for different device form factors. This icon is displayed * when the application is added to the device's Home Screen. * * Ext.setup({ * icon: { * 57: 'resources/icons/Icon.png', * 72: 'resources/icons/Icon~ipad.png', * 114: 'resources/icons/Icon@2x.png', * 144: 'resources/icons/Icon~ipad@2x.png' * }, * onReady: function() { * // ... * } * }); * * Each key represents the dimension of the icon as a square shape. For example: '57' is the key for a 57 x 57 * icon image. Here is the breakdown of each dimension and its device target: * * - 57: Non-retina iPhone, iPod touch, and all Android devices * - 72: Retina iPhone and iPod touch * - 114: Non-retina iPad (first and second generation) * - 144: Retina iPad (third generation) * * Note that the dimensions of the icon images must be exactly 57x57, 72x72, 114x114 and 144x144 respectively. * * It is highly recommended that you provide all these different sizes to accommodate a full range of * devices currently available. However if you only have one icon in one size, make it 57x57 in size and * specify it as a string value. This same icon will be used on all supported devices. * * Ext.setup({ * icon: 'resources/icons/Icon.png', * onReady: function() { * // ... * } * }); * * @param {Object} config.startupImage * Specifies a set of URLs to the application startup images for different device form factors. This image is * displayed when the application is being launched from the Home Screen icon. Note that this currently only applies * to iOS devices. * * Ext.setup({ * startupImage: { * '320x460': 'resources/startup/320x460.jpg', * '640x920': 'resources/startup/640x920.png', * '640x1096': 'resources/startup/640x1096.png', * '768x1004': 'resources/startup/768x1004.png', * '748x1024': 'resources/startup/748x1024.png', * '1536x2008': 'resources/startup/1536x2008.png', * '1496x2048': 'resources/startup/1496x2048.png' * }, * onReady: function() { * // ... * } * }); * * Each key represents the dimension of the image. For example: '320x460' is the key for a 320px x 460px image. * Here is the breakdown of each dimension and its device target: * * - 320x460: Non-retina iPhone, iPod touch, and all Android devices * - 640x920: Retina iPhone and iPod touch * - 640x1096: iPhone 5 and iPod touch (fifth generation) * - 768x1004: Non-retina iPad (first and second generation) in portrait orientation * - 748x1024: Non-retina iPad (first and second generation) in landscape orientation * - 1536x2008: Retina iPad (third generation) in portrait orientation * - 1496x2048: Retina iPad (third generation) in landscape orientation * * Please note that there's no automatic fallback mechanism for the startup images. In other words, if you don't specify * a valid image for a certain device, nothing will be displayed while the application is being launched on that device. * * @param {Boolean} isIconPrecomposed * True to not having a glossy effect added to the icon by the OS, which will preserve its exact look. This currently * only applies to iOS devices. * * @param {String} statusBarStyle * The style of status bar to be shown on applications added to the iOS home screen. Valid options are: * * * `default` * * `black` * * `black-translucent` * * @param {String[]} config.requires * An array of required classes for your application which will be automatically loaded before `onReady` is invoked. * Please refer to {@link Ext.Loader} and {@link Ext.Loader#require} for more information. * * Ext.setup({ * requires: ['Ext.Button', 'Ext.tab.Panel'], * onReady: function() { * // ... * } * }); * * @param {Object} config.eventPublishers * Sencha Touch, by default, includes various {@link Ext.event.recognizer.Recognizer} subclasses to recognize events fired * in your application. The list of default recognizers can be found in the documentation for * {@link Ext.event.recognizer.Recognizer}. * * To change the default recognizers, you can use the following syntax: * * Ext.setup({ * eventPublishers: { * touchGesture: { * recognizers: { * swipe: { * // this will include both vertical and horizontal swipe recognizers * xclass: 'Ext.event.recognizer.Swipe' * } * } * } * }, * onReady: function() { * // ... * } * }); * * You can also disable recognizers using this syntax: * * Ext.setup({ * eventPublishers: { * touchGesture: { * recognizers: { * swipe: null, * pinch: null, * rotate: null * } * } * }, * onReady: function() { * // ... * } * }); */ setup: function(config) { var defaultSetupConfig = Ext.defaultSetupConfig, emptyFn = Ext.emptyFn, onReady = config.onReady || emptyFn, onUpdated = config.onUpdated || emptyFn, scope = config.scope, requires = Ext.Array.from(config.requires), extOnReady = Ext.onReady, head = Ext.getHead(), callback, viewport, precomposed; Ext.setup = function() { throw new Error("Ext.setup has already been called before"); }; delete config.requires; delete config.onReady; delete config.onUpdated; delete config.scope; Ext.require(['Ext.event.Dispatcher']); callback = function() { var listeners = Ext.setupListeners, ln = listeners.length, i, listener; delete Ext.setupListeners; Ext.isSetup = true; for (i = 0; i < ln; i++) { listener = listeners[i]; listener.fn.call(listener.scope); } Ext.onReady = extOnReady; Ext.onReady(onReady, scope); }; Ext.onUpdated = onUpdated; Ext.onReady = function(fn, scope) { var origin = onReady; onReady = function() { origin(); Ext.onReady(fn, scope); }; }; config = Ext.merge({}, defaultSetupConfig, config); Ext.onDocumentReady(function() { Ext.factoryConfig(config, function(data) { Ext.event.Dispatcher.getInstance().setPublishers(data.eventPublishers); if (data.logger) { Ext.Logger = data.logger; } if (data.animator) { Ext.Animator = data.animator; } if (data.viewport) { Ext.Viewport = viewport = data.viewport; if (!scope) { scope = viewport; } Ext.require(requires, function() { Ext.Viewport.on('ready', callback, null, {single: true}); }); } else { Ext.require(requires, callback); } }); }); function addMeta(name, content) { var meta = document.createElement('meta'); meta.setAttribute('name', name); meta.setAttribute('content', content); head.append(meta); } function addIcon(href, sizes, precomposed) { var link = document.createElement('link'); link.setAttribute('rel', 'apple-touch-icon' + (precomposed ? '-precomposed' : '')); link.setAttribute('href', href); if (sizes) { link.setAttribute('sizes', sizes); } head.append(link); } function addStartupImage(href, media) { var link = document.createElement('link'); link.setAttribute('rel', 'apple-touch-startup-image'); link.setAttribute('href', href); if (media) { link.setAttribute('media', media); } head.append(link); } var icon = config.icon, isIconPrecomposed = Boolean(config.isIconPrecomposed), startupImage = config.startupImage || {}, statusBarStyle = config.statusBarStyle, devicePixelRatio = window.devicePixelRatio || 1; if (navigator.standalone) { addMeta('viewport', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'); } else { addMeta('viewport', 'initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'); } addMeta('apple-mobile-web-app-capable', 'yes'); addMeta('apple-touch-fullscreen', 'yes'); // status bar style if (statusBarStyle) { addMeta('apple-mobile-web-app-status-bar-style', statusBarStyle); } if (Ext.isString(icon)) { icon = { 57: icon, 72: icon, 114: icon, 144: icon }; } else if (!icon) { icon = {}; } //<deprecated product=touch since=2.0.1> if ('phoneStartupScreen' in config) { //<debug warn> Ext.Logger.deprecate("[Ext.setup()] 'phoneStartupScreen' config is deprecated, please use 'startupImage' " + "config instead. Refer to the latest API docs for more details"); //</debug> config['320x460'] = config.phoneStartupScreen; } if ('tabletStartupScreen' in config) { //<debug warn> Ext.Logger.deprecate("[Ext.setup()] 'tabletStartupScreen' config is deprecated, please use 'startupImage' " + "config instead. Refer to the latest API docs for more details"); //</debug> config['768x1004'] = config.tabletStartupScreen; } if ('glossOnIcon' in config) { //<debug warn> Ext.Logger.deprecate("[Ext.setup()] 'glossOnIcon' config is deprecated, please use 'isIconPrecomposed' " + "config instead. Refer to the latest API docs for more details"); //</debug> isIconPrecomposed = Boolean(config.glossOnIcon); } //</deprecated> if (Ext.os.is.iPad) { if (devicePixelRatio >= 2) { // Retina iPad - Landscape if ('1496x2048' in startupImage) { addStartupImage(startupImage['1496x2048'], '(orientation: landscape)'); } // Retina iPad - Portrait if ('1536x2008' in startupImage) { addStartupImage(startupImage['1536x2008'], '(orientation: portrait)'); } // Retina iPad if ('144' in icon) { addIcon(icon['144'], '144x144', isIconPrecomposed); } } else { // Non-Retina iPad - Landscape if ('748x1024' in startupImage) { addStartupImage(startupImage['748x1024'], '(orientation: landscape)'); } // Non-Retina iPad - Portrait if ('768x1004' in startupImage) { addStartupImage(startupImage['768x1004'], '(orientation: portrait)'); } // Non-Retina iPad if ('72' in icon) { addIcon(icon['72'], '72x72', isIconPrecomposed); } } } else { // Retina iPhone, iPod touch with iOS version >= 4.3 if (devicePixelRatio >= 2 && Ext.os.version.gtEq('4.3')) { if (Ext.os.is.iPhone5) { addStartupImage(startupImage['640x1096']); } else { addStartupImage(startupImage['640x920']); } // Retina iPhone and iPod touch if ('114' in icon) { addIcon(icon['114'], '114x114', isIconPrecomposed); } } else { addStartupImage(startupImage['320x460']); // Non-Retina iPhone, iPod touch, and Android devices if ('57' in icon) { addIcon(icon['57'], null, isIconPrecomposed); } } } }, /** * @member Ext * @method application * * Loads Ext.app.Application class and starts it up with given configuration after the page is ready. * * Ext.application({ * launch: function() { * alert('Application launched!'); * } * }); * * See {@link Ext.app.Application} for details. * * @param {Object} config An object with the following config options: * * @param {Function} config.launch * A function to be called when the application is ready. Your application logic should be here. Please see {@link Ext.app.Application} * for details. * * @param {Object} config.viewport * An object to be used when creating the global {@link Ext.Viewport} instance. Please refer to the {@link Ext.Viewport} * documentation for more information. * * Ext.application({ * viewport: { * layout: 'vbox' * }, * launch: function() { * Ext.Viewport.add({ * flex: 1, * html: 'top (flex: 1)' * }); * * Ext.Viewport.add({ * flex: 4, * html: 'bottom (flex: 4)' * }); * } * }); * * @param {String/Object} config.icon * Specifies a set of URLs to the application icon for different device form factors. This icon is displayed * when the application is added to the device's Home Screen. * * Ext.application({ * icon: { * 57: 'resources/icons/Icon.png', * 72: 'resources/icons/Icon~ipad.png', * 114: 'resources/icons/Icon@2x.png', * 144: 'resources/icons/Icon~ipad@2x.png' * }, * launch: function() { * // ... * } * }); * * Each key represents the dimension of the icon as a square shape. For example: '57' is the key for a 57 x 57 * icon image. Here is the breakdown of each dimension and its device target: * * - 57: Non-retina iPhone, iPod touch, and all Android devices * - 72: Retina iPhone and iPod touch * - 114: Non-retina iPad (first and second generation) * - 144: Retina iPad (third generation) * * Note that the dimensions of the icon images must be exactly 57x57, 72x72, 114x114 and 144x144 respectively. * * It is highly recommended that you provide all these different sizes to accommodate a full range of * devices currently available. However if you only have one icon in one size, make it 57x57 in size and * specify it as a string value. This same icon will be used on all supported devices. * * Ext.setup({ * icon: 'resources/icons/Icon.png', * onReady: function() { * // ... * } * }); * * @param {Object} config.startupImage * Specifies a set of URLs to the application startup images for different device form factors. This image is * displayed when the application is being launched from the Home Screen icon. Note that this currently only applies * to iOS devices. * * Ext.application({ * startupImage: { * '320x460': 'resources/startup/320x460.jpg', * '640x920': 'resources/startup/640x920.png', * '640x1096': 'resources/startup/640x1096.png', * '768x1004': 'resources/startup/768x1004.png', * '748x1024': 'resources/startup/748x1024.png', * '1536x2008': 'resources/startup/1536x2008.png', * '1496x2048': 'resources/startup/1496x2048.png' * }, * launch: function() { * // ... * } * }); * * Each key represents the dimension of the image. For example: '320x460' is the key for a 320px x 460px image. * Here is the breakdown of each dimension and its device target: * * - 320x460: Non-retina iPhone, iPod touch, and all Android devices * - 640x920: Retina iPhone and iPod touch * - 640x1096: iPhone 5 and iPod touch (fifth generation) * - 768x1004: Non-retina iPad (first and second generation) in portrait orientation * - 748x1024: Non-retina iPad (first and second generation) in landscape orientation * - 1536x2008: Retina iPad (third generation) in portrait orientation * - 1496x2048: Retina iPad (third generation) in landscape orientation * * Please note that there's no automatic fallback mechanism for the startup images. In other words, if you don't specify * a valid image for a certain device, nothing will be displayed while the application is being launched on that device. * * @param {Boolean} config.isIconPrecomposed * True to not having a glossy effect added to the icon by the OS, which will preserve its exact look. This currently * only applies to iOS devices. * * @param {String} config.statusBarStyle * The style of status bar to be shown on applications added to the iOS home screen. Valid options are: * * * `default` * * `black` * * `black-translucent` * * @param {String[]} config.requires * An array of required classes for your application which will be automatically loaded if {@link Ext.Loader#enabled} is set * to `true`. Please refer to {@link Ext.Loader} and {@link Ext.Loader#require} for more information. * * Ext.application({ * requires: ['Ext.Button', 'Ext.tab.Panel'], * launch: function() { * // ... * } * }); * * @param {Object} config.eventPublishers * Sencha Touch, by default, includes various {@link Ext.event.recognizer.Recognizer} subclasses to recognize events fired * in your application. The list of default recognizers can be found in the documentation for {@link Ext.event.recognizer.Recognizer}. * * To change the default recognizers, you can use the following syntax: * * Ext.application({ * eventPublishers: { * touchGesture: { * recognizers: { * swipe: { * // this will include both vertical and horizontal swipe recognizers * xclass: 'Ext.event.recognizer.Swipe' * } * } * } * }, * launch: function() { * // ... * } * }); * * You can also disable recognizers using this syntax: * * Ext.application({ * eventPublishers: { * touchGesture: { * recognizers: { * swipe: null, * pinch: null, * rotate: null * } * } * }, * launch: function() { * // ... * } * }); */ application: function(config) { var appName = config.name, onReady, scope, requires; if (!config) { config = {}; } if (!Ext.Loader.config.paths[appName]) { Ext.Loader.setPath(appName, config.appFolder || 'app'); } requires = Ext.Array.from(config.requires); config.requires = ['Ext.app.Application']; onReady = config.onReady; scope = config.scope; config.onReady = function() { config.requires = requires; new Ext.app.Application(config); if (onReady) { onReady.call(scope); } }; Ext.setup(config); }, /** * @private * @param config * @param callback * @member Ext */ factoryConfig: function(config, callback) { var isSimpleObject = Ext.isSimpleObject(config); if (isSimpleObject && config.xclass) { var className = config.xclass; delete config.xclass; Ext.require(className, function() { Ext.factoryConfig(config, function(cfg) { callback(Ext.create(className, cfg)); }); }); return; } var isArray = Ext.isArray(config), keys = [], key, value, i, ln; if (isSimpleObject || isArray) { if (isSimpleObject) { for (key in config) { if (config.hasOwnProperty(key)) { value = config[key]; if (Ext.isSimpleObject(value) || Ext.isArray(value)) { keys.push(key); } } } } else { for (i = 0,ln = config.length; i < ln; i++) { value = config[i]; if (Ext.isSimpleObject(value) || Ext.isArray(value)) { keys.push(i); } } } i = 0; ln = keys.length; if (ln === 0) { callback(config); return; } function fn(value) { config[key] = value; i++; factory(); } function factory() { if (i >= ln) { callback(config); return; } key = keys[i]; value = config[key]; Ext.factoryConfig(value, fn); } factory(); return; } callback(config); }, /** * A global factory method to instantiate a class from a config object. For example, these two calls are equivalent: * * Ext.factory({ text: 'My Button' }, 'Ext.Button'); * Ext.create('Ext.Button', { text: 'My Button' }); * * If an existing instance is also specified, it will be updated with the supplied config object. This is useful * if you need to either create or update an object, depending on if an instance already exists. For example: * * var button; * button = Ext.factory({ text: 'New Button' }, 'Ext.Button', button); // Button created * button = Ext.factory({ text: 'Updated Button' }, 'Ext.Button', button); // Button updated * * @param {Object} config The config object to instantiate or update an instance with. * @param {String} classReference The class to instantiate from. * @param {Object} [instance] The instance to update. * @param [aliasNamespace] * @member Ext */ factory: function(config, classReference, instance, aliasNamespace) { var manager = Ext.ClassManager, newInstance; // If config is falsy or a valid instance, destroy the current instance // (if it exists) and replace with the new one if (!config || config.isInstance) { if (instance && instance !== config) { instance.destroy(); } return config; } if (aliasNamespace) { // If config is a string value, treat it as an alias if (typeof config == 'string') { return manager.instantiateByAlias(aliasNamespace + '.' + config); } // Same if 'type' is given in config else if (Ext.isObject(config) && 'type' in config) { return manager.instantiateByAlias(aliasNamespace + '.' + config.type, config); } } if (config === true) { return instance || manager.instantiate(classReference); } //<debug error> if (!Ext.isObject(config)) { Ext.Logger.error("Invalid config, must be a valid config object"); } //</debug> if ('xtype' in config) { newInstance = manager.instantiateByAlias('widget.' + config.xtype, config); } else if ('xclass' in config) { newInstance = manager.instantiate(config.xclass, config); } if (newInstance) { if (instance) { instance.destroy(); } return newInstance; } if (instance) { return instance.setConfig(config); } return manager.instantiate(classReference, config); }, /** * @private * @member Ext */ deprecateClassMember: function(cls, oldName, newName, message) { return this.deprecateProperty(cls.prototype, oldName, newName, message); }, /** * @private * @member Ext */ deprecateClassMembers: function(cls, members) { var prototype = cls.prototype, oldName, newName; for (oldName in members) { if (members.hasOwnProperty(oldName)) { newName = members[oldName]; this.deprecateProperty(prototype, oldName, newName); } } }, /** * @private * @member Ext */ deprecateProperty: function(object, oldName, newName, message) { if (!message) { message = "'" + oldName + "' is deprecated"; } if (newName) { message += ", please use '" + newName + "' instead"; } if (newName) { Ext.Object.defineProperty(object, oldName, { get: function() { //<debug warn> Ext.Logger.deprecate(message, 1); //</debug> return this[newName]; }, set: function(value) { //<debug warn> Ext.Logger.deprecate(message, 1); //</debug> this[newName] = value; }, configurable: true }); } }, /** * @private * @member Ext */ deprecatePropertyValue: function(object, name, value, message) { Ext.Object.defineProperty(object, name, { get: function() { //<debug warn> Ext.Logger.deprecate(message, 1); //</debug> return value; }, configurable: true }); }, /** * @private * @member Ext */ deprecateMethod: function(object, name, method, message) { object[name] = function() { //<debug warn> Ext.Logger.deprecate(message, 2); //</debug> if (method) { return method.apply(this, arguments); } }; }, /** * @private * @member Ext */ deprecateClassMethod: function(cls, name, method, message) { if (typeof name != 'string') { var from, to; for (from in name) { if (name.hasOwnProperty(from)) { to = name[from]; Ext.deprecateClassMethod(cls, from, to); } } return; } var isLateBinding = typeof method == 'string', member; if (!message) { message = "'" + name + "()' is deprecated, please use '" + (isLateBinding ? method : method.name) + "()' instead"; } if (isLateBinding) { member = function() { //<debug warn> Ext.Logger.deprecate(message, this); //</debug> return this[method].apply(this, arguments); }; } else { member = function() { //<debug warn> Ext.Logger.deprecate(message, this); //</debug> return method.apply(this, arguments); }; } if (name in cls.prototype) { Ext.Object.defineProperty(cls.prototype, name, { value: null, writable: true, configurable: true }); } cls.addMember(name, member); }, //<debug> /** * Useful snippet to show an exact, narrowed-down list of top-level Components that are not yet destroyed. * @private */ showLeaks: function() { var map = Ext.ComponentManager.all.map, leaks = [], parent; Ext.Object.each(map, function(id, component) { while ((parent = component.getParent()) && map.hasOwnProperty(parent.getId())) { component = parent; } if (leaks.indexOf(component) === -1) { leaks.push(component); } }); console.log(leaks); }, //</debug> /** * True when the document is fully initialized and ready for action * @type Boolean * @member Ext * @private */ isReady : false, /** * @private * @member Ext */ readyListeners: [], /** * @private * @member Ext */ triggerReady: function() { var listeners = Ext.readyListeners, i, ln, listener; if (!Ext.isReady) { Ext.isReady = true; for (i = 0,ln = listeners.length; i < ln; i++) { listener = listeners[i]; listener.fn.call(listener.scope); } delete Ext.readyListeners; } }, /** * @private * @member Ext */ onDocumentReady: function(fn, scope) { if (Ext.isReady) { fn.call(scope); } else { var triggerFn = Ext.triggerReady; Ext.readyListeners.push({ fn: fn, scope: scope }); if (Ext.browser.is.PhoneGap && !Ext.os.is.Desktop) { if (!Ext.readyListenerAttached) { Ext.readyListenerAttached = true; document.addEventListener('deviceready', triggerFn, false); } } else { if (document.readyState.match(/interactive|complete|loaded/) !== null) { triggerFn(); } else if (!Ext.readyListenerAttached) { Ext.readyListenerAttached = true; window.addEventListener('DOMContentLoaded', triggerFn, false); } } } }, /** * Calls function after specified delay, or right away when delay == 0. * @param {Function} callback The callback to execute. * @param {Object} scope (optional) The scope to execute in. * @param {Array} args (optional) The arguments to pass to the function. * @param {Number} delay (optional) Pass a number to delay the call by a number of milliseconds. * @member Ext */ callback: function(callback, scope, args, delay) { if (Ext.isFunction(callback)) { args = args || []; scope = scope || window; if (delay) { Ext.defer(callback, delay, scope, args); } else { callback.apply(scope, args); } } } }); //<debug> Ext.Object.defineProperty(Ext, 'Msg', { get: function() { Ext.Logger.error("Using Ext.Msg without requiring Ext.MessageBox"); return null; }, set: function(value) { Ext.Object.defineProperty(Ext, 'Msg', { value: value }); return value; }, configurable: true }); //</debug> //<deprecated product=touch since=2.0> Ext.deprecateMethod(Ext, 'getOrientation', function() { return Ext.Viewport.getOrientation(); }, "Ext.getOrientation() is deprecated, use Ext.Viewport.getOrientation() instead"); Ext.deprecateMethod(Ext, 'log', function(message) { return Ext.Logger.log(message); }, "Ext.log() is deprecated, please use Ext.Logger.log() instead"); /** * @member Ext.Function * @method createDelegate * @inheritdoc Ext.Function#bind * @deprecated 2.0.0 * Please use {@link Ext.Function#bind bind} instead */ Ext.deprecateMethod(Ext.Function, 'createDelegate', Ext.Function.bind, "Ext.createDelegate() is deprecated, please use Ext.Function.bind() instead"); /** * @member Ext * @method createInterceptor * @inheritdoc Ext.Function#createInterceptor * @deprecated 2.0.0 * Please use {@link Ext.Function#createInterceptor createInterceptor} instead */ Ext.deprecateMethod(Ext, 'createInterceptor', Ext.Function.createInterceptor, "Ext.createInterceptor() is deprecated, " + "please use Ext.Function.createInterceptor() instead"); /** * @member Ext * @property {Boolean} SSL_SECURE_URL * URL to a blank file used by Ext JS when in secure mode for iframe src and onReady * src to prevent the IE insecure content warning. * @removed 2.0.0 */ Ext.deprecateProperty(Ext, 'SSL_SECURE_URL', null, "Ext.SSL_SECURE_URL has been removed"); /** * @member Ext * @property {Boolean} enableGarbageCollector * `true` to automatically un-cache orphaned Ext.Elements periodically. * @removed 2.0.0 */ Ext.deprecateProperty(Ext, 'enableGarbageCollector', null, "Ext.enableGarbageCollector has been removed"); /** * @member Ext * @property {Boolean} enableListenerCollection * True to automatically purge event listeners during garbageCollection. * @removed 2.0.0 */ Ext.deprecateProperty(Ext, 'enableListenerCollection', null, "Ext.enableListenerCollection has been removed"); /** * @member Ext * @property {Boolean} isSecure * True if the page is running over SSL. * @removed 2.0.0 Please use {@link Ext.env.Browser#isSecure} instead */ Ext.deprecateProperty(Ext, 'isSecure', null, "Ext.enableListenerCollection has been removed, please use Ext.env.Browser.isSecure instead"); /** * @member Ext * @method dispatch * Dispatches a request to a controller action. * @removed 2.0.0 Please use {@link Ext.app.Application#dispatch} instead */ Ext.deprecateMethod(Ext, 'dispatch', null, "Ext.dispatch() is deprecated, please use Ext.app.Application.dispatch() instead"); /** * @member Ext * @method getOrientation * Returns the current orientation of the mobile device. * @removed 2.0.0 * Please use {@link Ext.Viewport#getOrientation getOrientation} instead */ Ext.deprecateMethod(Ext, 'getOrientation', null, "Ext.getOrientation() has been removed, " + "please use Ext.Viewport.getOrientation() instead"); /** * @member Ext * @method reg * Registers a new xtype. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'reg', null, "Ext.reg() has been removed"); /** * @member Ext * @method preg * Registers a new ptype. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'preg', null, "Ext.preg() has been removed"); /** * @member Ext * @method redirect * Dispatches a request to a controller action, adding to the History stack * and updating the page url as necessary. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'redirect', null, "Ext.redirect() has been removed"); /** * @member Ext * @method regApplication * Creates a new Application class from the specified config object. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'regApplication', null, "Ext.regApplication() has been removed"); /** * @member Ext * @method regController * Creates a new Controller class from the specified config object. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'regController', null, "Ext.regController() has been removed"); /** * @member Ext * @method regLayout * Registers new layout type. * @removed 2.0.0 */ Ext.deprecateMethod(Ext, 'regLayout', null, "Ext.regLayout() has been removed"); //</deprecated>
hackathon-3d/team-gryffindor-repo
www/touch/src/core/Ext-more.js
JavaScript
gpl-2.0
50,756
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "threads/SystemClock.h" #include "system.h" #include "GUIWindowFullScreen.h" #include "Application.h" #include "messaging/ApplicationMessenger.h" #ifdef HAS_VIDEO_PLAYBACK #include "cores/VideoRenderers/RenderManager.h" #endif #include "GUIInfoManager.h" #include "guilib/GUIProgressControl.h" #include "guilib/GUILabelControl.h" #include "video/dialogs/GUIDialogVideoOSD.h" #include "guilib/GUIWindowManager.h" #include "input/Key.h" #include "video/dialogs/GUIDialogFullScreenInfo.h" #include "settings/DisplaySettings.h" #include "settings/MediaSettings.h" #include "settings/Settings.h" #include "FileItem.h" #include "video/VideoReferenceClock.h" #include "utils/CPUInfo.h" #include "guilib/LocalizeStrings.h" #include "threads/SingleLock.h" #include "utils/StringUtils.h" #include "XBDateTime.h" #include "input/ButtonTranslator.h" #include "windowing/WindowingFactory.h" #include "cores/IPlayer.h" #include "guiinfo/GUIInfoLabels.h" #include <stdio.h> #include <algorithm> #if defined(TARGET_DARWIN) #include "linux/LinuxResourceCounter.h" #endif using namespace KODI::MESSAGING; #define BLUE_BAR 0 #define LABEL_ROW1 10 #define LABEL_ROW2 11 #define LABEL_ROW3 12 //Displays current position, visible after seek or when forced //Alt, use conditional visibility Player.DisplayAfterSeek #define LABEL_CURRENT_TIME 22 //Displays when video is rebuffering //Alt, use conditional visibility Player.IsCaching #define LABEL_BUFFERING 24 //Progressbar used for buffering status and after seeking #define CONTROL_PROGRESS 23 #if defined(TARGET_DARWIN) static CLinuxResourceCounter m_resourceCounter; #endif CGUIWindowFullScreen::CGUIWindowFullScreen(void) : CGUIWindow(WINDOW_FULLSCREEN_VIDEO, "VideoFullScreen.xml") { m_timeCodeStamp[0] = 0; m_timeCodePosition = 0; m_timeCodeShow = false; m_timeCodeTimeout = 0; m_bShowViewModeInfo = false; m_dwShowViewModeTimeout = 0; m_bShowCurrentTime = false; m_loadType = KEEP_IN_MEMORY; // audio // - language // - volume // - stream // video // - Create Bookmark (294) // - Cycle bookmarks (295) // - Clear bookmarks (296) // - jump to specific time // - slider // - av delay // subtitles // - delay // - language } CGUIWindowFullScreen::~CGUIWindowFullScreen(void) {} bool CGUIWindowFullScreen::OnAction(const CAction &action) { if (m_timeCodePosition > 0 && action.GetButtonCode()) { // check whether we have a mapping in our virtual videotimeseek "window" and have a select action CKey key(action.GetButtonCode()); CAction timeSeek = CButtonTranslator::GetInstance().GetAction(WINDOW_VIDEO_TIME_SEEK, key, false); if (timeSeek.GetID() == ACTION_SELECT_ITEM) { SeekToTimeCodeStamp(SEEK_ABSOLUTE); return true; } } switch (action.GetID()) { case ACTION_SHOW_OSD: ToggleOSD(); return true; case ACTION_TRIGGER_OSD: TriggerOSD(); return true; case ACTION_SHOW_GUI: { // switch back to the menu g_windowManager.PreviousWindow(); return true; } break; case ACTION_PLAYER_PLAY: case ACTION_PAUSE: if (m_timeCodePosition > 0) { SeekToTimeCodeStamp(SEEK_ABSOLUTE); return true; } break; case ACTION_SMALL_STEP_BACK: case ACTION_STEP_BACK: case ACTION_BIG_STEP_BACK: case ACTION_CHAPTER_OR_BIG_STEP_BACK: if (m_timeCodePosition > 0) { SeekToTimeCodeStamp(SEEK_RELATIVE, SEEK_BACKWARD); return true; } break; case ACTION_STEP_FORWARD: case ACTION_BIG_STEP_FORWARD: case ACTION_CHAPTER_OR_BIG_STEP_FORWARD: if (m_timeCodePosition > 0) { SeekToTimeCodeStamp(SEEK_RELATIVE, SEEK_FORWARD); return true; } break; case ACTION_SHOW_OSD_TIME: m_bShowCurrentTime = !m_bShowCurrentTime; if(!m_bShowCurrentTime) g_infoManager.SetDisplayAfterSeek(0); //Force display off g_infoManager.SetShowTime(m_bShowCurrentTime); return true; break; case ACTION_SHOW_INFO: { CGUIDialogFullScreenInfo* pDialog = (CGUIDialogFullScreenInfo*)g_windowManager.GetWindow(WINDOW_DIALOG_FULLSCREEN_INFO); if (pDialog) { CFileItem item(g_application.CurrentFileItem()); pDialog->Open(); return true; } break; } case REMOTE_0: case REMOTE_1: case REMOTE_2: case REMOTE_3: case REMOTE_4: case REMOTE_5: case REMOTE_6: case REMOTE_7: case REMOTE_8: case REMOTE_9: { if (!g_application.CurrentFileItem().IsLiveTV()) { ChangetheTimeCode(action.GetID()); return true; } } break; case ACTION_ASPECT_RATIO: { // toggle the aspect ratio mode (only if the info is onscreen) if (m_bShowViewModeInfo) { #ifdef HAS_VIDEO_PLAYBACK g_renderManager.SetViewMode(++CMediaSettings::Get().GetCurrentVideoSettings().m_ViewMode); #endif } m_bShowViewModeInfo = true; m_dwShowViewModeTimeout = XbmcThreads::SystemClockMillis(); } return true; break; case ACTION_SHOW_PLAYLIST: { CFileItem item(g_application.CurrentFileItem()); if (item.HasPVRChannelInfoTag()) g_windowManager.ActivateWindow(WINDOW_DIALOG_PVR_OSD_CHANNELS); else if (item.HasVideoInfoTag()) g_windowManager.ActivateWindow(WINDOW_VIDEO_PLAYLIST); else if (item.HasMusicInfoTag()) g_windowManager.ActivateWindow(WINDOW_MUSIC_PLAYLIST); } return true; break; default: break; } return CGUIWindow::OnAction(action); } void CGUIWindowFullScreen::ClearBackground() { if (g_renderManager.IsVideoLayer()) #ifdef HAS_IMXVPU g_graphicsContext.Clear((16 << 16)|(8 << 8)|16); #else g_graphicsContext.Clear(0); #endif } void CGUIWindowFullScreen::OnWindowLoaded() { CGUIWindow::OnWindowLoaded(); // override the clear colour - we must never clear fullscreen m_clearBackground = 0; CGUIProgressControl* pProgress = dynamic_cast<CGUIProgressControl*>(GetControl(CONTROL_PROGRESS)); if(pProgress) { if( pProgress->GetInfo() == 0 || !pProgress->HasVisibleCondition()) { pProgress->SetInfo(PLAYER_PROGRESS); pProgress->SetVisibleCondition("player.displayafterseek"); pProgress->SetVisible(true); } } CGUILabelControl* pLabel = dynamic_cast<CGUILabelControl*>(GetControl(LABEL_BUFFERING)); if(pLabel && !pLabel->HasVisibleCondition()) { pLabel->SetVisibleCondition("player.caching"); pLabel->SetVisible(true); } pLabel = dynamic_cast<CGUILabelControl*>(GetControl(LABEL_CURRENT_TIME)); if(pLabel && !pLabel->HasVisibleCondition()) { pLabel->SetVisibleCondition("player.displayafterseek"); pLabel->SetVisible(true); pLabel->SetLabel("$INFO(VIDEOPLAYER.TIME) / $INFO(VIDEOPLAYER.DURATION)"); } m_showCodec.Parse("player.showcodec", GetID()); } bool CGUIWindowFullScreen::OnMessage(CGUIMessage& message) { switch (message.GetMessage()) { case GUI_MSG_WINDOW_INIT: { // check whether we've come back here from a window during which time we've actually // stopped playing videos if (message.GetParam1() == WINDOW_INVALID && !g_application.m_pPlayer->IsPlayingVideo()) { // why are we here if nothing is playing??? g_windowManager.PreviousWindow(); return true; } g_infoManager.SetShowInfo(false); g_infoManager.SetShowCodec(false); m_bShowCurrentTime = false; g_infoManager.SetDisplayAfterSeek(0); // Make sure display after seek is off. // switch resolution g_graphicsContext.SetFullScreenVideo(true); #ifdef HAS_VIDEO_PLAYBACK // make sure renderer is uptospeed g_renderManager.Update(); #endif // now call the base class to load our windows CGUIWindow::OnMessage(message); m_bShowViewModeInfo = false; return true; } case GUI_MSG_WINDOW_DEINIT: { // close all active modal dialogs g_windowManager.CloseInternalModalDialogs(true); CGUIWindow::OnMessage(message); CSettings::Get().Save(); CSingleLock lock (g_graphicsContext); g_graphicsContext.SetFullScreenVideo(false); lock.Leave(); #ifdef HAS_VIDEO_PLAYBACK // make sure renderer is uptospeed g_renderManager.Update(); g_renderManager.FrameFinish(); #endif return true; } case GUI_MSG_SETFOCUS: case GUI_MSG_LOSTFOCUS: if (message.GetSenderId() != WINDOW_FULLSCREEN_VIDEO) return true; break; } return CGUIWindow::OnMessage(message); } EVENT_RESULT CGUIWindowFullScreen::OnMouseEvent(const CPoint &point, const CMouseEvent &event) { if (event.m_id == ACTION_MOUSE_RIGHT_CLICK) { // no control found to absorb this click - go back to GUI OnAction(CAction(ACTION_SHOW_GUI)); return EVENT_RESULT_HANDLED; } if (event.m_id == ACTION_MOUSE_WHEEL_UP) { return g_application.OnAction(CAction(ACTION_ANALOG_SEEK_FORWARD, 0.5f)) ? EVENT_RESULT_HANDLED : EVENT_RESULT_UNHANDLED; } if (event.m_id == ACTION_MOUSE_WHEEL_DOWN) { return g_application.OnAction(CAction(ACTION_ANALOG_SEEK_BACK, 0.5f)) ? EVENT_RESULT_HANDLED : EVENT_RESULT_UNHANDLED; } if (event.m_id >= ACTION_GESTURE_NOTIFY && event.m_id <= ACTION_GESTURE_END) // gestures return EVENT_RESULT_UNHANDLED; return EVENT_RESULT_UNHANDLED; } void CGUIWindowFullScreen::FrameMove() { if (g_application.m_pPlayer->GetPlaySpeed() != 1) g_infoManager.SetDisplayAfterSeek(); if (m_bShowCurrentTime) g_infoManager.SetDisplayAfterSeek(); if (!g_application.m_pPlayer->HasPlayer()) return; if( g_application.m_pPlayer->IsCaching() ) { g_infoManager.SetDisplayAfterSeek(0); //Make sure these stuff aren't visible now } //------------------------ m_showCodec.Update(); if (m_showCodec) { // show audio codec info std::string strAudio, strVideo, strGeneral; g_application.m_pPlayer->GetAudioInfo(strAudio); { CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW1); msg.SetLabel(strAudio); OnMessage(msg); } // show video codec info g_application.m_pPlayer->GetVideoInfo(strVideo); { CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW2); msg.SetLabel(strVideo); OnMessage(msg); } // show general info g_application.m_pPlayer->GetGeneralInfo(strGeneral); { std::string strGeneralFPS; #if defined(TARGET_DARWIN) // We show CPU usage for the entire process, as it's arguably more useful. double dCPU = m_resourceCounter.GetCPUUsage(); std::string strCores; strCores = StringUtils::Format("cpu:%.0f%%", dCPU); #else std::string strCores = g_cpuInfo.GetCoresUsageString(); #endif int missedvblanks; double refreshrate; double clockspeed; std::string strClock; if (g_VideoReferenceClock.GetClockInfo(missedvblanks, clockspeed, refreshrate)) strClock = StringUtils::Format("S( refresh:%.3f missed:%i speed:%+.3f%% %s )" , refreshrate , missedvblanks , clockspeed - 100.0 , g_renderManager.GetVSyncState().c_str()); strGeneralFPS = StringUtils::Format("%s\nW( %s )\n%s" , strGeneral.c_str() , strCores.c_str(), strClock.c_str() ); CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW3); msg.SetLabel(strGeneralFPS); OnMessage(msg); } } //---------------------- // ViewMode Information //---------------------- if (m_bShowViewModeInfo && XbmcThreads::SystemClockMillis() - m_dwShowViewModeTimeout > 2500) { m_bShowViewModeInfo = false; } if (m_bShowViewModeInfo) { RESOLUTION_INFO res = g_graphicsContext.GetResInfo(); { // get the "View Mode" string std::string strTitle = g_localizeStrings.Get(629); std::string strMode = g_localizeStrings.Get(630 + CMediaSettings::Get().GetCurrentVideoSettings().m_ViewMode); std::string strInfo = StringUtils::Format("%s : %s", strTitle.c_str(), strMode.c_str()); CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW1); msg.SetLabel(strInfo); OnMessage(msg); } // show sizing information SPlayerVideoStreamInfo info; g_application.m_pPlayer->GetVideoStreamInfo(info); { // Splitres scaling factor float xscale = (float)res.iScreenWidth / (float)res.iWidth; float yscale = (float)res.iScreenHeight / (float)res.iHeight; std::string strSizing = StringUtils::Format(g_localizeStrings.Get(245).c_str(), (int)info.SrcRect.Width(), (int)info.SrcRect.Height(), (int)(info.DestRect.Width() * xscale), (int)(info.DestRect.Height() * yscale), CDisplaySettings::Get().GetZoomAmount(), info.videoAspectRatio*CDisplaySettings::Get().GetPixelRatio(), CDisplaySettings::Get().GetPixelRatio(), CDisplaySettings::Get().GetVerticalShift()); CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW2); msg.SetLabel(strSizing); OnMessage(msg); } // show resolution information { std::string strStatus; if (g_Windowing.IsFullScreen()) strStatus = StringUtils::Format("%s %ix%i@%.2fHz - %s", g_localizeStrings.Get(13287).c_str(), res.iScreenWidth, res.iScreenHeight, res.fRefreshRate, g_localizeStrings.Get(244).c_str()); else strStatus = StringUtils::Format("%s %ix%i - %s", g_localizeStrings.Get(13287).c_str(), res.iScreenWidth, res.iScreenHeight, g_localizeStrings.Get(242).c_str()); CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW3); msg.SetLabel(strStatus); OnMessage(msg); } } if (m_timeCodeShow && m_timeCodePosition != 0) { if ( (XbmcThreads::SystemClockMillis() - m_timeCodeTimeout) >= 2500) { m_timeCodeShow = false; m_timeCodePosition = 0; } std::string strDispTime = "00:00:00"; CGUIMessage msg(GUI_MSG_LABEL_SET, GetID(), LABEL_ROW1); for (int pos = 7, i = m_timeCodePosition; pos >= 0 && i > 0; pos--) { if (strDispTime[pos] != ':') { i -= 1; strDispTime[pos] = (char)m_timeCodeStamp[i] + '0'; } } strDispTime += "/" + g_infoManager.GetDuration(TIME_FORMAT_HH_MM_SS) + " [" + g_infoManager.GetCurrentPlayTime(TIME_FORMAT_HH_MM_SS) + "]"; // duration [ time ] msg.SetLabel(strDispTime); OnMessage(msg); } if (m_showCodec || m_bShowViewModeInfo) { SET_CONTROL_VISIBLE(LABEL_ROW1); SET_CONTROL_VISIBLE(LABEL_ROW2); SET_CONTROL_VISIBLE(LABEL_ROW3); SET_CONTROL_VISIBLE(BLUE_BAR); } else if (m_timeCodeShow) { SET_CONTROL_VISIBLE(LABEL_ROW1); SET_CONTROL_HIDDEN(LABEL_ROW2); SET_CONTROL_HIDDEN(LABEL_ROW3); SET_CONTROL_VISIBLE(BLUE_BAR); } else { SET_CONTROL_HIDDEN(LABEL_ROW1); SET_CONTROL_HIDDEN(LABEL_ROW2); SET_CONTROL_HIDDEN(LABEL_ROW3); SET_CONTROL_HIDDEN(BLUE_BAR); } g_renderManager.FrameMove(); } void CGUIWindowFullScreen::Process(unsigned int currentTime, CDirtyRegionList &dirtyregion) { if (g_renderManager.IsGuiLayer()) MarkDirtyRegion(); CGUIWindow::Process(currentTime, dirtyregion); // TODO: This isn't quite optimal - ideally we'd only be dirtying up the actual video render rect // which is probably the job of the renderer as it can more easily track resizing etc. m_renderRegion.SetRect(0, 0, (float)g_graphicsContext.GetWidth(), (float)g_graphicsContext.GetHeight()); } void CGUIWindowFullScreen::Render() { g_graphicsContext.SetRenderingResolution(g_graphicsContext.GetVideoResolution(), false); g_renderManager.Render(true, 0, 255); g_graphicsContext.SetRenderingResolution(m_coordsRes, m_needsScaling); CGUIWindow::Render(); } void CGUIWindowFullScreen::RenderEx() { CGUIWindow::RenderEx(); g_graphicsContext.SetRenderingResolution(g_graphicsContext.GetVideoResolution(), false); #ifdef HAS_VIDEO_PLAYBACK g_renderManager.Render(false, 0, 255, false); g_renderManager.FrameFinish(); #endif } void CGUIWindowFullScreen::ChangetheTimeCode(int remote) { if (remote >= REMOTE_0 && remote <= REMOTE_9) { m_timeCodeShow = true; m_timeCodeTimeout = XbmcThreads::SystemClockMillis(); if (m_timeCodePosition < 6) m_timeCodeStamp[m_timeCodePosition++] = remote - REMOTE_0; else { // rotate around for (int i = 0; i < 5; i++) m_timeCodeStamp[i] = m_timeCodeStamp[i+1]; m_timeCodeStamp[5] = remote - REMOTE_0; } } } void CGUIWindowFullScreen::SeekToTimeCodeStamp(SEEK_TYPE type, SEEK_DIRECTION direction) { double total = GetTimeCodeStamp(); if (type == SEEK_RELATIVE) total = g_application.GetTime() + (((direction == SEEK_FORWARD) ? 1 : -1) * total); if (total < g_application.GetTotalTime()) g_application.SeekTime(total); m_timeCodePosition = 0; m_timeCodeShow = false; } double CGUIWindowFullScreen::GetTimeCodeStamp() { // Convert the timestamp into an integer int tot = 0; for (int i = 0; i < m_timeCodePosition; i++) tot = tot * 10 + m_timeCodeStamp[i]; // Interpret result as HHMMSS int s = tot % 100; tot /= 100; int m = tot % 100; tot /= 100; int h = tot % 100; return h * 3600 + m * 60 + s; } void CGUIWindowFullScreen::SeekChapter(int iChapter) { g_application.m_pPlayer->SeekChapter(iChapter); // Make sure gui items are visible. g_infoManager.SetDisplayAfterSeek(); } void CGUIWindowFullScreen::ToggleOSD() { CGUIDialogVideoOSD *pOSD = (CGUIDialogVideoOSD *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_OSD); if (pOSD) { if (pOSD->IsDialogRunning()) pOSD->Close(); else pOSD->Open(); } MarkDirtyRegion(); } void CGUIWindowFullScreen::TriggerOSD() { CGUIDialogVideoOSD *pOSD = (CGUIDialogVideoOSD *)g_windowManager.GetWindow(WINDOW_DIALOG_VIDEO_OSD); if (pOSD && !pOSD->IsDialogRunning()) { pOSD->SetAutoClose(3000); pOSD->Open(); } }
yuvalt/xbmc
xbmc/video/windows/GUIWindowFullScreen.cpp
C++
gpl-2.0
19,632
/* * 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 * * (c)Copyright 2006 Hewlett-Packard Development Company, LP. * */ #include "C_ProtocolControl.hpp" #include "Utils.hpp" #include "GeneratorTrace.hpp" #include "GeneratorError.h" #include "C_ProtocolBinary.hpp" #include "C_ProtocolExternal.hpp" #include "C_ProtocolBinaryBodyNotInterpreted.hpp" #include "C_ProtocolBinarySeparator.hpp" #include "C_ProtocolText.hpp" #include "C_ProtocolTlv.hpp" #define XML_PROTOCOL_SECTION (char*)"protocol" #define XML_PROTOCOL_NAME (char*)"name" #define XML_PROTOCOL_TYPE (char*)"type" C_ProtocolControl::C_ProtocolControl(C_TransportControl *P_transport_control) { GEN_DEBUG(1, "C_ProtocolControl::C_ProtocolControl() start"); NEW_VAR(m_name_map, T_ProtocolNameMap()); m_name_map->clear() ; m_protocol_table = NULL ; m_protocol_name_table = NULL ; m_protocol_table_size = 0 ; NEW_VAR(m_id_gen, C_IdGenerator()); m_transport_control = P_transport_control ; GEN_DEBUG(1, "C_ProtocolControl::C_ProtocolControl() end"); } C_ProtocolControl::~C_ProtocolControl() { int L_i ; GEN_DEBUG(1, "C_ProtocolControl::~C_ProtocolControl() start"); if (!m_name_map->empty()) { m_name_map->erase(m_name_map->begin(), m_name_map->end()); } DELETE_VAR(m_name_map); if (m_protocol_table_size != 0) { for (L_i = 0 ; L_i < m_protocol_table_size; L_i++) { DELETE_VAR(m_protocol_table[L_i]); } FREE_TABLE(m_protocol_table); FREE_TABLE(m_protocol_name_table); m_protocol_table_size = 0 ; } DELETE_VAR(m_id_gen) ; m_transport_control = NULL ; GEN_DEBUG(1, "C_ProtocolControl::~C_ProtocolControl() end"); } char* C_ProtocolControl::get_protocol_name(C_XmlData *P_data) { return (P_data->find_value(XML_PROTOCOL_NAME)) ; } char* C_ProtocolControl::get_protocol_type(C_XmlData *P_data) { return (P_data->find_value(XML_PROTOCOL_TYPE)) ; } bool C_ProtocolControl::fromXml (C_XmlData *P_data, T_pConfigValueList P_config_value_list, bool P_display_protocol_stats) { bool L_ret = true ; T_pXmlData_List L_subList ; T_XmlData_List::iterator L_subListIt ; C_XmlData *L_data ; char *L_protocol_name, *L_protocol_type ; int L_protocol_id ; T_ProtocolInstList L_protocol_inst_list ; T_pProtocolInstanceInfo L_protocol_info ; T_ProtocolInstList::iterator L_it ; GEN_DEBUG(1, "C_ProtocolControl::fromXml() start"); if (P_data != NULL) { if ((L_subList = P_data->get_sub_data()) != NULL) { for (L_subListIt = L_subList->begin() ; L_subListIt != L_subList->end() ; L_subListIt++) { L_data = *L_subListIt ; if (L_data != NULL) { if (strcmp(L_data->get_name(), XML_PROTOCOL_SECTION) == 0) { // protocol section definition found L_protocol_name = get_protocol_name (L_data) ; // check protocol type for creation L_protocol_type = get_protocol_type (L_data) ; // check name/type presence if (L_protocol_name == NULL) { GEN_ERROR(E_GEN_FATAL_ERROR, "name mandatory for section " << XML_PROTOCOL_SECTION); L_ret = false ; break ; } if (L_protocol_type == NULL) { GEN_ERROR(E_GEN_FATAL_ERROR, "type mandatory for section " << XML_PROTOCOL_SECTION); L_ret = false ; break ; } // check protocol name unicity if (m_name_map->find(T_ProtocolNameMap::key_type(L_protocol_name)) != m_name_map->end()) { GEN_ERROR(E_GEN_FATAL_ERROR, XML_PROTOCOL_SECTION << " with name [" << L_protocol_name << "] already defined"); L_ret = false ; break ; } // check protocol type or sub type if (strcmp(L_protocol_type, "binary") == 0) { // create protocol instance C_ProtocolBinary *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolBinary()); L_protocol_instance->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "binary-tlv") == 0) { // create protocol instance C_ProtocolTlv *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolTlv()); L_protocol_instance->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "binary-body-not-interpreted") == 0) { // create protocol instance C_ProtocolBinaryBodyNotInterpreted *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolBinaryBodyNotInterpreted()); L_protocol_instance->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "binary-separator") == 0) { // create protocol instance C_ProtocolBinarySeparator *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolBinarySeparator()); L_protocol_instance ->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "external-library") == 0) { C_ProtocolExternal *L_protocol_instance = NULL ; T_ConstructorResult L_res = E_CONSTRUCTOR_OK ; NEW_VAR(L_protocol_instance, C_ProtocolExternal(m_transport_control, L_data, &L_protocol_name, P_config_value_list, &L_res)); if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } // store new instance L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "text") == 0) { C_ProtocolText *L_protocol_instance = NULL ; T_ConstructorResult L_res = E_CONSTRUCTOR_OK ; NEW_VAR(L_protocol_instance, C_ProtocolText()); L_protocol_instance->analyze_data(L_data, &L_protocol_name, P_config_value_list, &L_res); if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } // store new instance L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else { GEN_ERROR(E_GEN_FATAL_ERROR, XML_PROTOCOL_SECTION << " [" << L_protocol_name << "] with type [" << L_protocol_type << "] unsupported"); L_ret = false ; } } } } if (L_ret != false) { if (!L_protocol_inst_list.empty()) { m_protocol_table_size = L_protocol_inst_list.size() ; ALLOC_TABLE(m_protocol_table, T_pC_ProtocolFrame*, sizeof(T_pC_ProtocolFrame), m_protocol_table_size) ; ALLOC_TABLE(m_protocol_name_table, char**, sizeof(char*), m_protocol_table_size) ; for (L_it = L_protocol_inst_list.begin(); L_it != L_protocol_inst_list.end() ; L_it++) { L_protocol_info = *L_it ; m_protocol_table[L_protocol_info->m_id] = L_protocol_info->m_instance ; m_protocol_name_table[L_protocol_info->m_id] = L_protocol_info->m_name ; } } else { GEN_ERROR(E_GEN_FATAL_ERROR, "No protocol definition found"); L_ret = false ; } } // if L_ret != false if (!L_protocol_inst_list.empty()) { for (L_it = L_protocol_inst_list.begin(); L_it != L_protocol_inst_list.end() ; L_it++) { FREE_VAR(*L_it); } L_protocol_inst_list.erase(L_protocol_inst_list.begin(), L_protocol_inst_list.end()); } } } GEN_DEBUG(1, "C_ProtocolControl::fromXml() end ret=" << L_ret); return (L_ret); } C_ProtocolFrame* C_ProtocolControl::get_protocol (char *P_name) { C_ProtocolFrame *L_ret = NULL ; int L_id ; L_id = get_protocol_id (P_name) ; if (L_id != ERROR_PROTOCOL_UNKNOWN) { L_ret = m_protocol_table[L_id] ; } return (L_ret) ; } C_ProtocolFrame* C_ProtocolControl::get_protocol (int P_id) { C_ProtocolFrame *L_ret = NULL ; if ((P_id < m_protocol_table_size) && (P_id >= 0)) { L_ret = m_protocol_table[P_id] ; } return (L_ret); } int C_ProtocolControl::get_protocol_id (char *P_name) { int L_ret = ERROR_PROTOCOL_UNKNOWN ; T_ProtocolNameMap::iterator L_it ; L_it = m_name_map->find(T_ProtocolNameMap::key_type(P_name)) ; if (L_it != m_name_map->end()) { L_ret = L_it->second ; } return (L_ret) ; } int C_ProtocolControl::get_nb_protocol () { return (m_protocol_table_size); } char* C_ProtocolControl::get_protocol_name (int P_id) { char *L_ret = NULL ; if ((P_id < m_protocol_table_size) && (P_id >= 0)) { L_ret = m_protocol_name_table[P_id] ; } return (L_ret); }
hamzasheikh/Seagull
seagull/trunk/src/generator-model/C_ProtocolControl.cpp
C++
gpl-2.0
14,839
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-147 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.07.04 at 04:19:28 PM CEST // package icaro.infraestructura.entidadesBasicas.descEntidadesOrganizacion.jaxb; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the icaro.aplicaciones.descripcionorganizaciones package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _DescOrganizacion_QNAME = new QName("urn:icaro:aplicaciones:descripcionOrganizaciones", "DescOrganizacion"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: icaro.aplicaciones.descripcionorganizaciones * */ public ObjectFactory() { } /** * Create an instance of {@link RecursosAplicacion } * */ public RecursosAplicacion createRecursosAplicacion() { return new RecursosAplicacion(); } /** * Create an instance of {@link InstanciaGestor } * */ public InstanciaGestor createInstanciaGestor() { return new InstanciaGestor(); } /** * Create an instance of {@link ListaPropiedades } * */ public ListaPropiedades createListaPropiedades() { return new ListaPropiedades(); } /** * Create an instance of {@link Nodo } * */ public Nodo createNodo() { return new Nodo(); } /** * Create an instance of {@link PropiedadesGlobales } * */ public PropiedadesGlobales createPropiedadesGlobales() { return new PropiedadesGlobales(); } /** * Create an instance of {@link DescripcionComponentes } * */ public DescripcionComponentes createDescripcionComponentes() { return new DescripcionComponentes(); } /** * Create an instance of {@link AgentesAplicacion } * */ public AgentesAplicacion createAgentesAplicacion() { return new AgentesAplicacion(); } /** * Create an instance of {@link ListaNodosEjecucion } * */ public ListaNodosEjecucion createListaNodosEjecucion() { return new ListaNodosEjecucion(); } /** * Create an instance of {@link DescComportamientoAgentesAplicacion } * */ public DescComportamientoAgentesAplicacion createDescComportamientoAgentesAplicacion() { return new DescComportamientoAgentesAplicacion(); } /** * Create an instance of {@link DescInstancias } * */ public DescInstancias createDescInstancias() { return new DescInstancias(); } /** * Create an instance of {@link DescRecursosAplicacion } * */ public DescRecursosAplicacion createDescRecursosAplicacion() { return new DescRecursosAplicacion(); } /** * Create an instance of {@link DescComportamientoGestores } * */ public DescComportamientoGestores createDescComportamientoGestores() { return new DescComportamientoGestores(); } /** * Create an instance of {@link Propiedad } * */ public Propiedad createPropiedad() { return new Propiedad(); } /** * Create an instance of {@link Gestores } * */ public Gestores createGestores() { return new Gestores(); } /** * Create an instance of {@link DescComportamientoAgentes } * */ public DescComportamientoAgentes createDescComportamientoAgentes() { return new DescComportamientoAgentes(); } /** * Create an instance of {@link ComponentesGestionados } * */ public ComponentesGestionados createComponentesGestionados() { return new ComponentesGestionados(); } /** * Create an instance of {@link DescRecursoAplicacion } * */ public DescRecursoAplicacion createDescRecursoAplicacion() { return new DescRecursoAplicacion(); } /** * Create an instance of {@link Instancia } * */ public Instancia createInstancia() { return new Instancia(); } /** * Create an instance of {@link DescComportamientoAgente } * */ public DescComportamientoAgente createDescComportamientoAgente() { return new DescComportamientoAgente(); } /** * Create an instance of {@link ComponenteGestionado } * */ public ComponenteGestionado createComponenteGestionado() { return new ComponenteGestionado(); } /** * Create an instance of {@link DescComportamientoAgenteReactivo } * */ public DescComportamientoAgenteReactivo createDescComportamientoAgenteReactivo() { return new DescComportamientoAgenteReactivo(); } /** * Create an instance of {@link DescOrganizacion } * */ public DescOrganizacion createDescOrganizacion() { return new DescOrganizacion(); } /** * Create an instance of {@link DescComportamientoAgenteCognitivo } * */ public DescComportamientoAgenteCognitivo createDescComportamientoAgenteCognitivo() { return new DescComportamientoAgenteCognitivo(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DescOrganizacion }{@code >}} * */ @XmlElementDecl(namespace = "urn:icaro:aplicaciones:descripcionOrganizaciones", name = "DescOrganizacion") public JAXBElement<DescOrganizacion> createDescOrganizacion(DescOrganizacion value) { return new JAXBElement<DescOrganizacion>(_DescOrganizacion_QNAME, DescOrganizacion.class, null, value); } }
palomagc/MovieChatter
src/icaro/infraestructura/entidadesBasicas/descEntidadesOrganizacion/jaxb/ObjectFactory.java
Java
gpl-2.0
6,481
<?php namespace Yoast\WP\SEO\Conditionals; /** * Conditional that is met when the current request is an XML-RPC request. */ class XMLRPC_Conditional implements Conditional { /** * Returns whether the current request is an XML-RPC request. * * @return bool `true` when the current request is an XML-RPC request, `false` if not. */ public function is_met() { return ( \defined( 'XMLRPC_REQUEST' ) && \XMLRPC_REQUEST ); } }
TheThumbsupguy/Ross-Upholstery-Inc
wp-content/plugins/wordpress-seo/src/conditionals/xmlrpc-conditional.php
PHP
gpl-2.0
440
// Targeted by JavaCPP version 0.8-SNAPSHOT package com.googlecode.javacpp; import com.googlecode.javacpp.*; import com.googlecode.javacpp.annotation.*; import java.nio.*; import static com.googlecode.javacpp.opencv_core.*; import static com.googlecode.javacpp.opencv_imgproc.*; public class opencv_highgui extends com.googlecode.javacpp.helper.opencv_highgui { static { Loader.load(); } // Parsed from /usr/local/include/opencv2/highgui/highgui_c.h /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ // #ifndef __OPENCV_HIGHGUI_H__ // #define __OPENCV_HIGHGUI_H__ // #include "opencv2/core/core_c.h" // #ifdef __cplusplus // #endif /* __cplusplus */ /****************************************************************************************\ * Basic GUI functions * \****************************************************************************************/ //YV //-----------New for Qt /* For font */ /** enum */ public static final int CV_FONT_LIGHT = 25,//QFont::Light, CV_FONT_NORMAL = 50,//QFont::Normal, CV_FONT_DEMIBOLD = 63,//QFont::DemiBold, CV_FONT_BOLD = 75,//QFont::Bold, CV_FONT_BLACK = 87; //QFont::Black /** enum */ public static final int CV_STYLE_NORMAL = 0,//QFont::StyleNormal, CV_STYLE_ITALIC = 1,//QFont::StyleItalic, CV_STYLE_OBLIQUE = 2; //QFont::StyleOblique /* ---------*/ //for color cvScalar(blue_component, green_component, red\_component[, alpha_component]) //and alpha= 0 <-> 0xFF (not transparent <-> transparent) public static native @ByVal @Platform("linux") CvFont cvFontQt(@Cast("const char*") BytePointer nameFont, int pointSize/*CV_DEFAULT(-1)*/, @ByVal CvScalar color/*CV_DEFAULT(cvScalarAll(0))*/, int weight/*CV_DEFAULT(CV_FONT_NORMAL)*/, int style/*CV_DEFAULT(CV_STYLE_NORMAL)*/, int spacing/*CV_DEFAULT(0)*/); public static native @ByVal @Platform("linux") CvFont cvFontQt(@Cast("const char*") BytePointer nameFont); public static native @ByVal @Platform("linux") CvFont cvFontQt(String nameFont, int pointSize/*CV_DEFAULT(-1)*/, @ByVal CvScalar color/*CV_DEFAULT(cvScalarAll(0))*/, int weight/*CV_DEFAULT(CV_FONT_NORMAL)*/, int style/*CV_DEFAULT(CV_STYLE_NORMAL)*/, int spacing/*CV_DEFAULT(0)*/); public static native @ByVal @Platform("linux") CvFont cvFontQt(String nameFont); public static native @Platform("linux") void cvAddText(@Const CvArr img, @Cast("const char*") BytePointer text, @ByVal CvPoint org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, String text, @ByVal @Cast("CvPoint*") IntBuffer org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, @Cast("const char*") BytePointer text, @ByVal @Cast("CvPoint*") int[] org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, String text, @ByVal CvPoint org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, @Cast("const char*") BytePointer text, @ByVal @Cast("CvPoint*") IntBuffer org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, String text, @ByVal @Cast("CvPoint*") int[] org, CvFont arg2); public static native @Platform("linux") void cvDisplayOverlay(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayOverlay(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text); public static native @Platform("linux") void cvDisplayOverlay(String name, String text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayOverlay(String name, String text); public static native @Platform("linux") void cvDisplayStatusBar(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayStatusBar(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text); public static native @Platform("linux") void cvDisplayStatusBar(String name, String text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayStatusBar(String name, String text); public static native @Platform("linux") void cvSaveWindowParameters(@Cast("const char*") BytePointer name); public static native @Platform("linux") void cvSaveWindowParameters(String name); public static native @Platform("linux") void cvLoadWindowParameters(@Cast("const char*") BytePointer name); public static native @Platform("linux") void cvLoadWindowParameters(String name); public static class Pt2Func_int_PointerPointer extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_PointerPointer(Pointer p) { super(p); } protected Pt2Func_int_PointerPointer() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") PointerPointer argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_PointerPointer pt2Func, int argc, @Cast("char**") PointerPointer argv); public static class Pt2Func_int_BytePointer extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_BytePointer(Pointer p) { super(p); } protected Pt2Func_int_BytePointer() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") @ByPtrPtr BytePointer argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_BytePointer pt2Func, int argc, @Cast("char**") @ByPtrPtr BytePointer argv); public static class Pt2Func_int_ByteBuffer extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_ByteBuffer(Pointer p) { super(p); } protected Pt2Func_int_ByteBuffer() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_ByteBuffer pt2Func, int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv); public static class Pt2Func_int_byte__ extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_byte__(Pointer p) { super(p); } protected Pt2Func_int_byte__() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") @ByPtrPtr byte[] argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_byte__ pt2Func, int argc, @Cast("char**") @ByPtrPtr byte[] argv); public static native @Platform("linux") void cvStopLoop( ); @Convention("CV_CDECL") public static class CvButtonCallback extends FunctionPointer { static { Loader.load(); } public CvButtonCallback(Pointer p) { super(p); } protected CvButtonCallback() { allocate(); } private native void allocate(); public native void call(int state, Pointer userdata); } /** enum */ public static final int CV_PUSH_BUTTON = 0, CV_CHECKBOX = 1, CV_RADIOBOX = 2; public static native @Platform("linux") int cvCreateButton( @Cast("const char*") BytePointer button_name/*CV_DEFAULT(NULL)*/,CvButtonCallback on_change/*CV_DEFAULT(NULL)*/, Pointer userdata/*CV_DEFAULT(NULL)*/, int button_type/*CV_DEFAULT(CV_PUSH_BUTTON)*/, int initial_button_state/*CV_DEFAULT(0)*/); public static native @Platform("linux") int cvCreateButton(); public static native @Platform("linux") int cvCreateButton( String button_name/*CV_DEFAULT(NULL)*/,CvButtonCallback on_change/*CV_DEFAULT(NULL)*/, Pointer userdata/*CV_DEFAULT(NULL)*/, int button_type/*CV_DEFAULT(CV_PUSH_BUTTON)*/, int initial_button_state/*CV_DEFAULT(0)*/); //---------------------- /* this function is used to set some external parameters in case of X Window */ public static native int cvInitSystem( int argc, @Cast("char**") PointerPointer argv ); public static native int cvInitSystem( int argc, @Cast("char**") @ByPtrPtr BytePointer argv ); public static native int cvInitSystem( int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv ); public static native int cvInitSystem( int argc, @Cast("char**") @ByPtrPtr byte[] argv ); public static native int cvStartWindowThread( ); // --------- YV --------- /** enum */ public static final int //These 3 flags are used by cvSet/GetWindowProperty CV_WND_PROP_FULLSCREEN = 0, //to change/get window's fullscreen property CV_WND_PROP_AUTOSIZE = 1, //to change/get window's autosize property CV_WND_PROP_ASPECTRATIO= 2, //to change/get window's aspectratio property CV_WND_PROP_OPENGL = 3, //to change/get window's opengl support //These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty CV_WINDOW_NORMAL = 0x00000000, //the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size CV_WINDOW_AUTOSIZE = 0x00000001, //the user cannot resize the window, the size is constrainted by the image displayed CV_WINDOW_OPENGL = 0x00001000, //window with opengl support //Those flags are only for Qt CV_GUI_EXPANDED = 0x00000000, //status bar and tool bar CV_GUI_NORMAL = 0x00000010, //old fashious way //These 3 flags are used by cvNamedWindow and cvSet/GetWindowProperty CV_WINDOW_FULLSCREEN = 1,//change the window to fullscreen CV_WINDOW_FREERATIO = 0x00000100,//the image expends as much as it can (no ratio constraint) CV_WINDOW_KEEPRATIO = 0x00000000;//the ration image is respected. /* create window */ public static native int cvNamedWindow( @Cast("const char*") BytePointer name, int flags/*CV_DEFAULT(CV_WINDOW_AUTOSIZE)*/ ); public static native int cvNamedWindow( @Cast("const char*") BytePointer name ); public static native int cvNamedWindow( String name, int flags/*CV_DEFAULT(CV_WINDOW_AUTOSIZE)*/ ); public static native int cvNamedWindow( String name ); /* Set and Get Property of the window */ public static native void cvSetWindowProperty(@Cast("const char*") BytePointer name, int prop_id, double prop_value); public static native void cvSetWindowProperty(String name, int prop_id, double prop_value); public static native double cvGetWindowProperty(@Cast("const char*") BytePointer name, int prop_id); public static native double cvGetWindowProperty(String name, int prop_id); /* display image within window (highgui windows remember their content) */ public static native void cvShowImage( @Cast("const char*") BytePointer name, @Const CvArr image ); public static native void cvShowImage( String name, @Const CvArr image ); /* resize/move window */ public static native void cvResizeWindow( @Cast("const char*") BytePointer name, int width, int height ); public static native void cvResizeWindow( String name, int width, int height ); public static native void cvMoveWindow( @Cast("const char*") BytePointer name, int x, int y ); public static native void cvMoveWindow( String name, int x, int y ); /* destroy window and all the trackers associated with it */ public static native void cvDestroyWindow( @Cast("const char*") BytePointer name ); public static native void cvDestroyWindow( String name ); public static native void cvDestroyAllWindows(); /* get native window handle (HWND in case of Win32 and Widget in case of X Window) */ public static native Pointer cvGetWindowHandle( @Cast("const char*") BytePointer name ); public static native Pointer cvGetWindowHandle( String name ); /* get name of highgui window given its native handle */ public static native @Cast("const char*") BytePointer cvGetWindowName( Pointer window_handle ); @Convention("CV_CDECL") public static class CvTrackbarCallback extends FunctionPointer { static { Loader.load(); } public CvTrackbarCallback(Pointer p) { super(p); } protected CvTrackbarCallback() { allocate(); } private native void allocate(); public native void call(int pos); } /* create trackbar and display it on top of given window, set callback */ public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntBuffer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntBuffer value, int count); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntPointer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntPointer value, int count); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count); public static native int cvCreateTrackbar( String trackbar_name, String window_name, int[] value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( String trackbar_name, String window_name, int[] value, int count); @Convention("CV_CDECL") public static class CvTrackbarCallback2 extends FunctionPointer { static { Loader.load(); } public CvTrackbarCallback2(Pointer p) { super(p); } protected CvTrackbarCallback2() { allocate(); } private native void allocate(); public native void call(int pos, Pointer userdata); } public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntPointer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntPointer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, int[] value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, int[] value, int count, CvTrackbarCallback2 on_change); /* retrieve or set trackbar position */ public static native int cvGetTrackbarPos( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name ); public static native int cvGetTrackbarPos( String trackbar_name, String window_name ); public static native void cvSetTrackbarPos( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int pos ); public static native void cvSetTrackbarPos( String trackbar_name, String window_name, int pos ); /** enum */ public static final int CV_EVENT_MOUSEMOVE = 0, CV_EVENT_LBUTTONDOWN = 1, CV_EVENT_RBUTTONDOWN = 2, CV_EVENT_MBUTTONDOWN = 3, CV_EVENT_LBUTTONUP = 4, CV_EVENT_RBUTTONUP = 5, CV_EVENT_MBUTTONUP = 6, CV_EVENT_LBUTTONDBLCLK = 7, CV_EVENT_RBUTTONDBLCLK = 8, CV_EVENT_MBUTTONDBLCLK = 9; /** enum */ public static final int CV_EVENT_FLAG_LBUTTON = 1, CV_EVENT_FLAG_RBUTTON = 2, CV_EVENT_FLAG_MBUTTON = 4, CV_EVENT_FLAG_CTRLKEY = 8, CV_EVENT_FLAG_SHIFTKEY = 16, CV_EVENT_FLAG_ALTKEY = 32; @Convention("CV_CDECL") public static class CvMouseCallback extends FunctionPointer { static { Loader.load(); } public CvMouseCallback(Pointer p) { super(p); } protected CvMouseCallback() { allocate(); } private native void allocate(); public native void call(int event, int x, int y, int flags, Pointer param); } /* assign callback for mouse events */ public static native void cvSetMouseCallback( @Cast("const char*") BytePointer window_name, CvMouseCallback on_mouse, Pointer param/*CV_DEFAULT(NULL)*/); public static native void cvSetMouseCallback( @Cast("const char*") BytePointer window_name, CvMouseCallback on_mouse); public static native void cvSetMouseCallback( String window_name, CvMouseCallback on_mouse, Pointer param/*CV_DEFAULT(NULL)*/); public static native void cvSetMouseCallback( String window_name, CvMouseCallback on_mouse); /** enum */ public static final int /* 8bit, color or not */ CV_LOAD_IMAGE_UNCHANGED = -1, /* 8bit, gray */ CV_LOAD_IMAGE_GRAYSCALE = 0, /* ?, color */ CV_LOAD_IMAGE_COLOR = 1, /* any depth, ? */ CV_LOAD_IMAGE_ANYDEPTH = 2, /* ?, any color */ CV_LOAD_IMAGE_ANYCOLOR = 4; /* load image from file iscolor can be a combination of above flags where CV_LOAD_IMAGE_UNCHANGED overrides the other flags using CV_LOAD_IMAGE_ANYCOLOR alone is equivalent to CV_LOAD_IMAGE_UNCHANGED unless CV_LOAD_IMAGE_ANYDEPTH is specified images are converted to 8bit */ public static native IplImage cvLoadImage( @Cast("const char*") BytePointer filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native IplImage cvLoadImage( @Cast("const char*") BytePointer filename); public static native IplImage cvLoadImage( String filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native IplImage cvLoadImage( String filename); public static native CvMat cvLoadImageM( @Cast("const char*") BytePointer filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native CvMat cvLoadImageM( @Cast("const char*") BytePointer filename); public static native CvMat cvLoadImageM( String filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native CvMat cvLoadImageM( String filename); /** enum */ public static final int CV_IMWRITE_JPEG_QUALITY = 1, CV_IMWRITE_PNG_COMPRESSION = 16, CV_IMWRITE_PNG_STRATEGY = 17, CV_IMWRITE_PNG_BILEVEL = 18, CV_IMWRITE_PNG_STRATEGY_DEFAULT = 0, CV_IMWRITE_PNG_STRATEGY_FILTERED = 1, CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, CV_IMWRITE_PNG_STRATEGY_RLE = 3, CV_IMWRITE_PNG_STRATEGY_FIXED = 4, CV_IMWRITE_PXM_BINARY = 32; /* save image to file */ public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image ); public static native int cvSaveImage( String filename, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( String filename, @Const CvArr image ); public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( String filename, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( String filename, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); /* decode image stored in the buffer */ public static native IplImage cvDecodeImage( @Const CvMat buf, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native IplImage cvDecodeImage( @Const CvMat buf); public static native CvMat cvDecodeImageM( @Const CvMat buf, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native CvMat cvDecodeImageM( @Const CvMat buf); /* encode image and store the result as a byte vector (single-row 8uC1 matrix) */ public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image ); public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); /** enum */ public static final int CV_CVTIMG_FLIP = 1, CV_CVTIMG_SWAP_RB = 2; /* utility function: convert one image to another with optional vertical flip */ public static native void cvConvertImage( @Const CvArr src, CvArr dst, int flags/*CV_DEFAULT(0)*/); public static native void cvConvertImage( @Const CvArr src, CvArr dst); /* wait for key event infinitely (delay<=0) or for "delay" milliseconds */ public static native int cvWaitKey(int delay/*CV_DEFAULT(0)*/); public static native int cvWaitKey(); // OpenGL support @Convention("CV_CDECL") public static class CvOpenGlDrawCallback extends FunctionPointer { static { Loader.load(); } public CvOpenGlDrawCallback(Pointer p) { super(p); } protected CvOpenGlDrawCallback() { allocate(); } private native void allocate(); public native void call(Pointer userdata); } public static native void cvSetOpenGlDrawCallback(@Cast("const char*") BytePointer window_name, CvOpenGlDrawCallback callback, Pointer userdata/*CV_DEFAULT(NULL)*/); public static native void cvSetOpenGlDrawCallback(@Cast("const char*") BytePointer window_name, CvOpenGlDrawCallback callback); public static native void cvSetOpenGlDrawCallback(String window_name, CvOpenGlDrawCallback callback, Pointer userdata/*CV_DEFAULT(NULL)*/); public static native void cvSetOpenGlDrawCallback(String window_name, CvOpenGlDrawCallback callback); public static native void cvSetOpenGlContext(@Cast("const char*") BytePointer window_name); public static native void cvSetOpenGlContext(String window_name); public static native void cvUpdateWindow(@Cast("const char*") BytePointer window_name); public static native void cvUpdateWindow(String window_name); /****************************************************************************************\ * Working with Video Files and Cameras * \****************************************************************************************/ /* "black box" capture structure */ @Opaque public static class CvCapture extends Pointer { public CvCapture() { } public CvCapture(Pointer p) { super(p); } } /* start capturing frames from video file */ public static native CvCapture cvCreateFileCapture( @Cast("const char*") BytePointer filename ); public static native CvCapture cvCreateFileCapture( String filename ); /** enum */ public static final int CV_CAP_ANY = 0, // autodetect CV_CAP_MIL = 100, // MIL proprietary drivers CV_CAP_VFW = 200, // platform native CV_CAP_V4L = 200, CV_CAP_V4L2 = 200, CV_CAP_FIREWARE = 300, // IEEE 1394 drivers CV_CAP_FIREWIRE = 300, CV_CAP_IEEE1394 = 300, CV_CAP_DC1394 = 300, CV_CAP_CMU1394 = 300, CV_CAP_STEREO = 400, // TYZX proprietary drivers CV_CAP_TYZX = 400, CV_TYZX_LEFT = 400, CV_TYZX_RIGHT = 401, CV_TYZX_COLOR = 402, CV_TYZX_Z = 403, CV_CAP_QT = 500, // QuickTime CV_CAP_UNICAP = 600, // Unicap drivers CV_CAP_DSHOW = 700, // DirectShow (via videoInput) CV_CAP_MSMF = 1400, // Microsoft Media Foundation (via videoInput) CV_CAP_PVAPI = 800, // PvAPI, Prosilica GigE SDK CV_CAP_OPENNI = 900, // OpenNI (for Kinect) CV_CAP_OPENNI_ASUS = 910, // OpenNI (for Asus Xtion) CV_CAP_ANDROID = 1000, // Android CV_CAP_ANDROID_BACK = CV_CAP_ANDROID+99, // Android back camera CV_CAP_ANDROID_FRONT = CV_CAP_ANDROID+98, // Android front camera CV_CAP_XIAPI = 1100, // XIMEA Camera API CV_CAP_AVFOUNDATION = 1200, // AVFoundation framework for iOS (OS X Lion will have the same API) CV_CAP_GIGANETIX = 1300, // Smartek Giganetix GigEVisionSDK CV_CAP_INTELPERC = 1500; // Intel Perceptual Computing SDK /* start capturing frames from camera: index = camera_index + domain_offset (CV_CAP_*) */ public static native CvCapture cvCreateCameraCapture( int index ); /* grab a frame, return 1 on success, 0 on fail. this function is thought to be fast */ public static native int cvGrabFrame( CvCapture capture ); /* get the frame grabbed with cvGrabFrame(..) This function may apply some frame processing like frame decompression, flipping etc. !!!DO NOT RELEASE or MODIFY the retrieved frame!!! */ public static native IplImage cvRetrieveFrame( CvCapture capture, int streamIdx/*CV_DEFAULT(0)*/ ); public static native IplImage cvRetrieveFrame( CvCapture capture ); /* Just a combination of cvGrabFrame and cvRetrieveFrame !!!DO NOT RELEASE or MODIFY the retrieved frame!!! */ public static native IplImage cvQueryFrame( CvCapture capture ); /* stop capturing/reading and free resources */ public static native void cvReleaseCapture( @Cast("CvCapture**") PointerPointer capture ); public static native void cvReleaseCapture( @ByPtrPtr CvCapture capture ); /** enum */ public static final int // modes of the controlling registers (can be: auto, manual, auto single push, absolute Latter allowed with any other mode) // every feature can have only one mode turned on at a time CV_CAP_PROP_DC1394_OFF = -4, //turn the feature off (not controlled manually nor automatically) CV_CAP_PROP_DC1394_MODE_MANUAL = -3, //set automatically when a value of the feature is set by the user CV_CAP_PROP_DC1394_MODE_AUTO = -2, CV_CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, CV_CAP_PROP_POS_MSEC = 0, CV_CAP_PROP_POS_FRAMES = 1, CV_CAP_PROP_POS_AVI_RATIO = 2, CV_CAP_PROP_FRAME_WIDTH = 3, CV_CAP_PROP_FRAME_HEIGHT = 4, CV_CAP_PROP_FPS = 5, CV_CAP_PROP_FOURCC = 6, CV_CAP_PROP_FRAME_COUNT = 7, CV_CAP_PROP_FORMAT = 8, CV_CAP_PROP_MODE = 9, CV_CAP_PROP_BRIGHTNESS = 10, CV_CAP_PROP_CONTRAST = 11, CV_CAP_PROP_SATURATION = 12, CV_CAP_PROP_HUE = 13, CV_CAP_PROP_GAIN = 14, CV_CAP_PROP_EXPOSURE = 15, CV_CAP_PROP_CONVERT_RGB = 16, CV_CAP_PROP_WHITE_BALANCE_BLUE_U = 17, CV_CAP_PROP_RECTIFICATION = 18, CV_CAP_PROP_MONOCROME = 19, CV_CAP_PROP_SHARPNESS = 20, CV_CAP_PROP_AUTO_EXPOSURE = 21, // exposure control done by camera, // user can adjust refernce level // using this feature CV_CAP_PROP_GAMMA = 22, CV_CAP_PROP_TEMPERATURE = 23, CV_CAP_PROP_TRIGGER = 24, CV_CAP_PROP_TRIGGER_DELAY = 25, CV_CAP_PROP_WHITE_BALANCE_RED_V = 26, CV_CAP_PROP_ZOOM = 27, CV_CAP_PROP_FOCUS = 28, CV_CAP_PROP_GUID = 29, CV_CAP_PROP_ISO_SPEED = 30, CV_CAP_PROP_MAX_DC1394 = 31, CV_CAP_PROP_BACKLIGHT = 32, CV_CAP_PROP_PAN = 33, CV_CAP_PROP_TILT = 34, CV_CAP_PROP_ROLL = 35, CV_CAP_PROP_IRIS = 36, CV_CAP_PROP_SETTINGS = 37, CV_CAP_PROP_AUTOGRAB = 1024, // property for highgui class CvCapture_Android only CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING= 1025, // readonly, tricky property, returns cpnst char* indeed CV_CAP_PROP_PREVIEW_FORMAT= 1026, // readonly, tricky property, returns cpnst char* indeed // OpenNI map generators CV_CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, CV_CAP_OPENNI_GENERATORS_MASK = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_OPENNI_IMAGE_GENERATOR, // Properties of cameras available through OpenNI interfaces CV_CAP_PROP_OPENNI_OUTPUT_MODE = 100, CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, // in mm CV_CAP_PROP_OPENNI_BASELINE = 102, // in mm CV_CAP_PROP_OPENNI_FOCAL_LENGTH = 103, // in pixels CV_CAP_PROP_OPENNI_REGISTRATION = 104, // flag CV_CAP_PROP_OPENNI_REGISTRATION_ON = CV_CAP_PROP_OPENNI_REGISTRATION, // flag that synchronizes the remapping depth map to image map // by changing depth generator's view point (if the flag is "on") or // sets this view point to its normal one (if the flag is "off"). CV_CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, CV_CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, CV_CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, CV_CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, CV_CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE, CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE, CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH, CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_REGISTRATION, CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, // Properties of cameras available through GStreamer interface CV_CAP_GSTREAMER_QUEUE_LENGTH = 200, // default is 1 CV_CAP_PROP_PVAPI_MULTICASTIP = 300, // ip for anable multicast master mode. 0 for disable multicast // Properties of cameras available through XIMEA SDK interface CV_CAP_PROP_XI_DOWNSAMPLING = 400, // Change image resolution by binning or skipping. CV_CAP_PROP_XI_DATA_FORMAT = 401, // Output data format. CV_CAP_PROP_XI_OFFSET_X = 402, // Horizontal offset from the origin to the area of interest (in pixels). CV_CAP_PROP_XI_OFFSET_Y = 403, // Vertical offset from the origin to the area of interest (in pixels). CV_CAP_PROP_XI_TRG_SOURCE = 404, // Defines source of trigger. CV_CAP_PROP_XI_TRG_SOFTWARE = 405, // Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. CV_CAP_PROP_XI_GPI_SELECTOR = 406, // Selects general purpose input CV_CAP_PROP_XI_GPI_MODE = 407, // Set general purpose input mode CV_CAP_PROP_XI_GPI_LEVEL = 408, // Get general purpose level CV_CAP_PROP_XI_GPO_SELECTOR = 409, // Selects general purpose output CV_CAP_PROP_XI_GPO_MODE = 410, // Set general purpose output mode CV_CAP_PROP_XI_LED_SELECTOR = 411, // Selects camera signalling LED CV_CAP_PROP_XI_LED_MODE = 412, // Define camera signalling LED functionality CV_CAP_PROP_XI_MANUAL_WB = 413, // Calculates White Balance(must be called during acquisition) CV_CAP_PROP_XI_AUTO_WB = 414, // Automatic white balance CV_CAP_PROP_XI_AEAG = 415, // Automatic exposure/gain CV_CAP_PROP_XI_EXP_PRIORITY = 416, // Exposure priority (0.5 - exposure 50%, gain 50%). CV_CAP_PROP_XI_AE_MAX_LIMIT = 417, // Maximum limit of exposure in AEAG procedure CV_CAP_PROP_XI_AG_MAX_LIMIT = 418, // Maximum limit of gain in AEAG procedure CV_CAP_PROP_XI_AEAG_LEVEL = 419, // Average intensity of output signal AEAG should achieve(in %) CV_CAP_PROP_XI_TIMEOUT = 420, // Image capture timeout in milliseconds // Properties for Android cameras CV_CAP_PROP_ANDROID_FLASH_MODE = 8001, CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002, CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003, CV_CAP_PROP_ANDROID_ANTIBANDING = 8004, CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008, // Properties of cameras available through AVFOUNDATION interface CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001, CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, CV_CAP_PROP_IOS_DEVICE_FLASH = 9003, CV_CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, CV_CAP_PROP_IOS_DEVICE_TORCH = 9005, // Properties of cameras available through Smartek Giganetix Ethernet Vision interface /* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ CV_CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, CV_CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, CV_CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, CV_CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, CV_CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, CV_CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006, CV_CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, CV_CAP_PROP_INTELPERC_PROFILE_IDX = 11002, CV_CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, CV_CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, CV_CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007, // Intel PerC streams CV_CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, CV_CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, CV_CAP_INTELPERC_GENERATORS_MASK = CV_CAP_INTELPERC_DEPTH_GENERATOR + CV_CAP_INTELPERC_IMAGE_GENERATOR; /** enum */ public static final int // Data given from depth generator. CV_CAP_OPENNI_DEPTH_MAP = 0, // Depth values in mm (CV_16UC1) CV_CAP_OPENNI_POINT_CLOUD_MAP = 1, // XYZ in meters (CV_32FC3) CV_CAP_OPENNI_DISPARITY_MAP = 2, // Disparity in pixels (CV_8UC1) CV_CAP_OPENNI_DISPARITY_MAP_32F = 3, // Disparity in pixels (CV_32FC1) CV_CAP_OPENNI_VALID_DEPTH_MASK = 4, // CV_8UC1 // Data given from RGB image generator. CV_CAP_OPENNI_BGR_IMAGE = 5, CV_CAP_OPENNI_GRAY_IMAGE = 6; // Supported output modes of OpenNI image generator /** enum */ public static final int CV_CAP_OPENNI_VGA_30HZ = 0, CV_CAP_OPENNI_SXGA_15HZ = 1, CV_CAP_OPENNI_SXGA_30HZ = 2, CV_CAP_OPENNI_QVGA_30HZ = 3, CV_CAP_OPENNI_QVGA_60HZ = 4; //supported by Android camera output formats /** enum */ public static final int CV_CAP_ANDROID_COLOR_FRAME_BGR = 0, //BGR CV_CAP_ANDROID_COLOR_FRAME = CV_CAP_ANDROID_COLOR_FRAME_BGR, CV_CAP_ANDROID_GREY_FRAME = 1, //Y CV_CAP_ANDROID_COLOR_FRAME_RGB = 2, CV_CAP_ANDROID_COLOR_FRAME_BGRA = 3, CV_CAP_ANDROID_COLOR_FRAME_RGBA = 4; // supported Android camera flash modes /** enum */ public static final int CV_CAP_ANDROID_FLASH_MODE_AUTO = 0, CV_CAP_ANDROID_FLASH_MODE_OFF = 1, CV_CAP_ANDROID_FLASH_MODE_ON = 2, CV_CAP_ANDROID_FLASH_MODE_RED_EYE = 3, CV_CAP_ANDROID_FLASH_MODE_TORCH = 4; // supported Android camera focus modes /** enum */ public static final int CV_CAP_ANDROID_FOCUS_MODE_AUTO = 0, CV_CAP_ANDROID_FOCUS_MODE_CONTINUOUS_VIDEO = 1, CV_CAP_ANDROID_FOCUS_MODE_EDOF = 2, CV_CAP_ANDROID_FOCUS_MODE_FIXED = 3, CV_CAP_ANDROID_FOCUS_MODE_INFINITY = 4, CV_CAP_ANDROID_FOCUS_MODE_MACRO = 5; // supported Android camera white balance modes /** enum */ public static final int CV_CAP_ANDROID_WHITE_BALANCE_AUTO = 0, CV_CAP_ANDROID_WHITE_BALANCE_CLOUDY_DAYLIGHT = 1, CV_CAP_ANDROID_WHITE_BALANCE_DAYLIGHT = 2, CV_CAP_ANDROID_WHITE_BALANCE_FLUORESCENT = 3, CV_CAP_ANDROID_WHITE_BALANCE_INCANDESCENT = 4, CV_CAP_ANDROID_WHITE_BALANCE_SHADE = 5, CV_CAP_ANDROID_WHITE_BALANCE_TWILIGHT = 6, CV_CAP_ANDROID_WHITE_BALANCE_WARM_FLUORESCENT = 7; // supported Android camera antibanding modes /** enum */ public static final int CV_CAP_ANDROID_ANTIBANDING_50HZ = 0, CV_CAP_ANDROID_ANTIBANDING_60HZ = 1, CV_CAP_ANDROID_ANTIBANDING_AUTO = 2, CV_CAP_ANDROID_ANTIBANDING_OFF = 3; /** enum */ public static final int CV_CAP_INTELPERC_DEPTH_MAP = 0, // Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth. CV_CAP_INTELPERC_UVDEPTH_MAP = 1, // Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates. CV_CAP_INTELPERC_IR_MAP = 2, // Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam. CV_CAP_INTELPERC_IMAGE = 3; /* retrieve or set capture properties */ public static native double cvGetCaptureProperty( CvCapture capture, int property_id ); public static native int cvSetCaptureProperty( CvCapture capture, int property_id, double value ); // Return the type of the capturer (eg, CV_CAP_V4W, CV_CAP_UNICAP), which is unknown if created with CV_CAP_ANY public static native int cvGetCaptureDomain( CvCapture capture); /* "black box" video file writer structure */ @Opaque public static class CvVideoWriter extends Pointer { public CvVideoWriter() { } public CvVideoWriter(Pointer p) { super(p); } } // #define CV_FOURCC_MACRO(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24)) public static native int CV_FOURCC(@Cast("char") byte c1, @Cast("char") byte c2, @Cast("char") byte c3, @Cast("char") byte c4); public static final int CV_FOURCC_PROMPT = -1; /* Open Codec Selection Dialog (Windows only) */ public static native @MemberGetter int CV_FOURCC_DEFAULT(); public static final int CV_FOURCC_DEFAULT = CV_FOURCC_DEFAULT(); /* Use default codec for specified filename (Linux only) */ /* initialize video file writer */ public static native CvVideoWriter cvCreateVideoWriter( @Cast("const char*") BytePointer filename, int fourcc, double fps, @ByVal CvSize frame_size, int is_color/*CV_DEFAULT(1)*/); public static native CvVideoWriter cvCreateVideoWriter( @Cast("const char*") BytePointer filename, int fourcc, double fps, @ByVal CvSize frame_size); public static native CvVideoWriter cvCreateVideoWriter( String filename, int fourcc, double fps, @ByVal CvSize frame_size, int is_color/*CV_DEFAULT(1)*/); public static native CvVideoWriter cvCreateVideoWriter( String filename, int fourcc, double fps, @ByVal CvSize frame_size); //CVAPI(CvVideoWriter*) cvCreateImageSequenceWriter( const char* filename, // int is_color CV_DEFAULT(1)); /* write frame to video file */ public static native int cvWriteFrame( CvVideoWriter writer, @Const IplImage image ); /* close video file writer */ public static native void cvReleaseVideoWriter( @Cast("CvVideoWriter**") PointerPointer writer ); public static native void cvReleaseVideoWriter( @ByPtrPtr CvVideoWriter writer ); /****************************************************************************************\ * Obsolete functions/synonyms * \****************************************************************************************/ public static native CvCapture cvCaptureFromFile(@Cast("const char*") BytePointer arg1); public static native CvCapture cvCaptureFromFile(String arg1); public static native CvCapture cvCaptureFromCAM(int arg1); public static native CvCapture cvCaptureFromAVI(@Cast("const char*") BytePointer arg1); public static native CvCapture cvCaptureFromAVI(String arg1); public static native CvVideoWriter cvCreateAVIWriter(@Cast("const char*") BytePointer arg1, int arg2, double arg3, @ByVal CvSize arg4, int arg5); public static native CvVideoWriter cvCreateAVIWriter(String arg1, int arg2, double arg3, @ByVal CvSize arg4, int arg5); public static native int cvWriteToAVI(CvVideoWriter arg1, IplImage arg2); public static native void cvAddSearchPath(@Cast("const char*") BytePointer path); public static native void cvAddSearchPath(String path); public static native int cvvInitSystem(int arg1, @Cast("char**") PointerPointer arg2); public static native int cvvInitSystem(int arg1, @Cast("char**") @ByPtrPtr BytePointer arg2); public static native int cvvInitSystem(int arg1, @Cast("char**") @ByPtrPtr ByteBuffer arg2); public static native int cvvInitSystem(int arg1, @Cast("char**") @ByPtrPtr byte[] arg2); public static native void cvvNamedWindow(@Cast("const char*") BytePointer arg1, int arg2); public static native void cvvNamedWindow(String arg1, int arg2); public static native void cvvShowImage(@Cast("const char*") BytePointer arg1, CvArr arg2); public static native void cvvShowImage(String arg1, CvArr arg2); public static native void cvvResizeWindow(@Cast("const char*") BytePointer arg1, int arg2, int arg3); public static native void cvvResizeWindow(String arg1, int arg2, int arg3); public static native void cvvDestroyWindow(@Cast("const char*") BytePointer arg1); public static native void cvvDestroyWindow(String arg1); public static native int cvvCreateTrackbar(@Cast("const char*") BytePointer arg1, @Cast("const char*") BytePointer arg2, IntPointer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(String arg1, String arg2, IntBuffer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(@Cast("const char*") BytePointer arg1, @Cast("const char*") BytePointer arg2, int[] arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(String arg1, String arg2, IntPointer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(@Cast("const char*") BytePointer arg1, @Cast("const char*") BytePointer arg2, IntBuffer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(String arg1, String arg2, int[] arg3, int arg4, CvTrackbarCallback arg5); public static native IplImage cvvLoadImage(@Cast("const char*") BytePointer name); public static native IplImage cvvLoadImage(String name); public static native int cvvSaveImage(@Cast("const char*") BytePointer arg1, CvArr arg2, IntPointer arg3); public static native int cvvSaveImage(String arg1, CvArr arg2, IntBuffer arg3); public static native int cvvSaveImage(@Cast("const char*") BytePointer arg1, CvArr arg2, int[] arg3); public static native int cvvSaveImage(String arg1, CvArr arg2, IntPointer arg3); public static native int cvvSaveImage(@Cast("const char*") BytePointer arg1, CvArr arg2, IntBuffer arg3); public static native int cvvSaveImage(String arg1, CvArr arg2, int[] arg3); public static native void cvvAddSearchPath(@Cast("const char*") BytePointer arg1); public static native void cvvAddSearchPath(String arg1); public static native int cvvWaitKey(@Cast("const char*") BytePointer name); public static native int cvvWaitKey(String name); public static native int cvvWaitKeyEx(@Cast("const char*") BytePointer name, int delay); public static native int cvvWaitKeyEx(String name, int delay); public static native void cvvConvertImage(CvArr arg1, CvArr arg2, int arg3); public static final int HG_AUTOSIZE = CV_WINDOW_AUTOSIZE; // #define set_preprocess_func cvSetPreprocessFuncWin32 // #define set_postprocess_func cvSetPostprocessFuncWin32 // #if defined WIN32 || defined _WIN32 // #endif // #ifdef __cplusplus // #endif // #endif // Parsed from /usr/local/include/opencv2/highgui/highgui.hpp /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ // #ifndef __OPENCV_HIGHGUI_HPP__ // #define __OPENCV_HIGHGUI_HPP__ // #include "opencv2/core/core.hpp" // #include "opencv2/highgui/highgui_c.h" // #ifdef __cplusplus /** enum cv:: */ public static final int // Flags for namedWindow WINDOW_NORMAL = CV_WINDOW_NORMAL, // the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size WINDOW_AUTOSIZE = CV_WINDOW_AUTOSIZE, // the user cannot resize the window, the size is constrainted by the image displayed WINDOW_OPENGL = CV_WINDOW_OPENGL, // window with opengl support // Flags for set / getWindowProperty WND_PROP_FULLSCREEN = CV_WND_PROP_FULLSCREEN, // fullscreen property WND_PROP_AUTOSIZE = CV_WND_PROP_AUTOSIZE, // autosize property WND_PROP_ASPECT_RATIO = CV_WND_PROP_ASPECTRATIO, // window's aspect ration WND_PROP_OPENGL = CV_WND_PROP_OPENGL; // opengl support @Namespace("cv") public static native void namedWindow(@StdString BytePointer winname, int flags/*=WINDOW_AUTOSIZE*/); @Namespace("cv") public static native void namedWindow(@StdString BytePointer winname); @Namespace("cv") public static native void namedWindow(@StdString String winname, int flags/*=WINDOW_AUTOSIZE*/); @Namespace("cv") public static native void namedWindow(@StdString String winname); @Namespace("cv") public static native void destroyWindow(@StdString BytePointer winname); @Namespace("cv") public static native void destroyWindow(@StdString String winname); @Namespace("cv") public static native void destroyAllWindows(); @Namespace("cv") public static native int startWindowThread(); @Namespace("cv") public static native int waitKey(int delay/*=0*/); @Namespace("cv") public static native int waitKey(); @Namespace("cv") public static native void imshow(@StdString BytePointer winname, @ByVal Mat mat); @Namespace("cv") public static native void imshow(@StdString String winname, @ByVal Mat mat); @Namespace("cv") public static native void resizeWindow(@StdString BytePointer winname, int width, int height); @Namespace("cv") public static native void resizeWindow(@StdString String winname, int width, int height); @Namespace("cv") public static native void moveWindow(@StdString BytePointer winname, int x, int y); @Namespace("cv") public static native void moveWindow(@StdString String winname, int x, int y); @Namespace("cv") public static native void setWindowProperty(@StdString BytePointer winname, int prop_id, double prop_value); @Namespace("cv") public static native void setWindowProperty(@StdString String winname, int prop_id, double prop_value);//YV @Namespace("cv") public static native double getWindowProperty(@StdString BytePointer winname, int prop_id); @Namespace("cv") public static native double getWindowProperty(@StdString String winname, int prop_id);//YV /** enum cv:: */ public static final int EVENT_MOUSEMOVE = 0, EVENT_LBUTTONDOWN = 1, EVENT_RBUTTONDOWN = 2, EVENT_MBUTTONDOWN = 3, EVENT_LBUTTONUP = 4, EVENT_RBUTTONUP = 5, EVENT_MBUTTONUP = 6, EVENT_LBUTTONDBLCLK = 7, EVENT_RBUTTONDBLCLK = 8, EVENT_MBUTTONDBLCLK = 9; /** enum cv:: */ public static final int EVENT_FLAG_LBUTTON = 1, EVENT_FLAG_RBUTTON = 2, EVENT_FLAG_MBUTTON = 4, EVENT_FLAG_CTRLKEY = 8, EVENT_FLAG_SHIFTKEY = 16, EVENT_FLAG_ALTKEY = 32; public static class MouseCallback extends FunctionPointer { static { Loader.load(); } public MouseCallback(Pointer p) { super(p); } protected MouseCallback() { allocate(); } private native void allocate(); public native void call(int event, int x, int y, int flags, Pointer userdata); } /** assigns callback for mouse events */ @Namespace("cv") public static native void setMouseCallback(@StdString BytePointer winname, MouseCallback onMouse, Pointer userdata/*=0*/); @Namespace("cv") public static native void setMouseCallback(@StdString BytePointer winname, MouseCallback onMouse); @Namespace("cv") public static native void setMouseCallback(@StdString String winname, MouseCallback onMouse, Pointer userdata/*=0*/); @Namespace("cv") public static native void setMouseCallback(@StdString String winname, MouseCallback onMouse); @Convention("CV_CDECL") public static class TrackbarCallback extends FunctionPointer { static { Loader.load(); } public TrackbarCallback(Pointer p) { super(p); } protected TrackbarCallback() { allocate(); } private native void allocate(); public native void call(int pos, Pointer userdata); } @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntPointer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntPointer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntBuffer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntBuffer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, int[] value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, int[] value, int count); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntPointer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntPointer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntBuffer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntBuffer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, int[] value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, int[] value, int count); @Namespace("cv") public static native int getTrackbarPos(@StdString BytePointer trackbarname, @StdString BytePointer winname); @Namespace("cv") public static native int getTrackbarPos(@StdString String trackbarname, @StdString String winname); @Namespace("cv") public static native void setTrackbarPos(@StdString BytePointer trackbarname, @StdString BytePointer winname, int pos); @Namespace("cv") public static native void setTrackbarPos(@StdString String trackbarname, @StdString String winname, int pos); // OpenGL support public static class OpenGlDrawCallback extends FunctionPointer { static { Loader.load(); } public OpenGlDrawCallback(Pointer p) { super(p); } protected OpenGlDrawCallback() { allocate(); } private native void allocate(); public native void call(Pointer userdata); } @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString BytePointer winname, OpenGlDrawCallback onOpenGlDraw, Pointer userdata/*=0*/); @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString BytePointer winname, OpenGlDrawCallback onOpenGlDraw); @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString String winname, OpenGlDrawCallback onOpenGlDraw, Pointer userdata/*=0*/); @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString String winname, OpenGlDrawCallback onOpenGlDraw); @Namespace("cv") public static native void setOpenGlContext(@StdString BytePointer winname); @Namespace("cv") public static native void setOpenGlContext(@StdString String winname); @Namespace("cv") public static native void updateWindow(@StdString BytePointer winname); @Namespace("cv") public static native void updateWindow(@StdString String winname); // < Deperecated @Namespace("cv") public static native void pointCloudShow(@StdString BytePointer winname, @Const @ByRef GlCamera camera, @Const @ByRef GlArrays arr); @Namespace("cv") public static native void pointCloudShow(@StdString String winname, @Const @ByRef GlCamera camera, @Const @ByRef GlArrays arr); @Namespace("cv") public static native void pointCloudShow(@StdString BytePointer winname, @Const @ByRef GlCamera camera, @ByVal Mat points, @ByVal Mat colors/*=noArray()*/); @Namespace("cv") public static native void pointCloudShow(@StdString BytePointer winname, @Const @ByRef GlCamera camera, @ByVal Mat points); @Namespace("cv") public static native void pointCloudShow(@StdString String winname, @Const @ByRef GlCamera camera, @ByVal Mat points, @ByVal Mat colors/*=noArray()*/); @Namespace("cv") public static native void pointCloudShow(@StdString String winname, @Const @ByRef GlCamera camera, @ByVal Mat points); // > //Only for Qt @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString BytePointer nameFont, int pointSize/*=-1*/, @ByVal Scalar color/*=Scalar::all(0)*/, int weight/*=CV_FONT_NORMAL*/, int style/*=CV_STYLE_NORMAL*/, int spacing/*=0*/); @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString BytePointer nameFont); @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString String nameFont, int pointSize/*=-1*/, @ByVal Scalar color/*=Scalar::all(0)*/, int weight/*=CV_FONT_NORMAL*/, int style/*=CV_STYLE_NORMAL*/, int spacing/*=0*/); @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString String nameFont); @Namespace("cv") public static native void addText( @Const @ByRef Mat img, @StdString BytePointer text, @ByVal Point org, @ByVal CvFont font); @Namespace("cv") public static native void addText( @Const @ByRef Mat img, @StdString String text, @ByVal Point org, @ByVal CvFont font); @Namespace("cv") public static native void displayOverlay(@StdString BytePointer winname, @StdString BytePointer text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayOverlay(@StdString BytePointer winname, @StdString BytePointer text); @Namespace("cv") public static native void displayOverlay(@StdString String winname, @StdString String text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayOverlay(@StdString String winname, @StdString String text); @Namespace("cv") public static native void displayStatusBar(@StdString BytePointer winname, @StdString BytePointer text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayStatusBar(@StdString BytePointer winname, @StdString BytePointer text); @Namespace("cv") public static native void displayStatusBar(@StdString String winname, @StdString String text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayStatusBar(@StdString String winname, @StdString String text); @Namespace("cv") public static native void saveWindowParameters(@StdString BytePointer windowName); @Namespace("cv") public static native void saveWindowParameters(@StdString String windowName); @Namespace("cv") public static native void loadWindowParameters(@StdString BytePointer windowName); @Namespace("cv") public static native void loadWindowParameters(@StdString String windowName); @Namespace("cv") public static native int startLoop(Pt2Func_int_PointerPointer pt2Func, int argc, @Cast("char**") PointerPointer argv); @Namespace("cv") public static native int startLoop(Pt2Func_int_BytePointer pt2Func, int argc, @Cast("char**") @ByPtrPtr BytePointer argv); @Namespace("cv") public static native int startLoop(Pt2Func_int_ByteBuffer pt2Func, int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv); @Namespace("cv") public static native int startLoop(Pt2Func_int_byte__ pt2Func, int argc, @Cast("char**") @ByPtrPtr byte[] argv); @Namespace("cv") public static native void stopLoop(); @Convention("CV_CDECL") public static class ButtonCallback extends FunctionPointer { static { Loader.load(); } public ButtonCallback(Pointer p) { super(p); } protected ButtonCallback() { allocate(); } private native void allocate(); public native void call(int state, Pointer userdata); } @Namespace("cv") public static native int createButton( @StdString BytePointer bar_name, ButtonCallback on_change, Pointer userdata/*=NULL*/, int type/*=CV_PUSH_BUTTON*/, @Cast("bool") boolean initial_button_state/*=0*/); @Namespace("cv") public static native int createButton( @StdString BytePointer bar_name, ButtonCallback on_change); @Namespace("cv") public static native int createButton( @StdString String bar_name, ButtonCallback on_change, Pointer userdata/*=NULL*/, int type/*=CV_PUSH_BUTTON*/, @Cast("bool") boolean initial_button_state/*=0*/); @Namespace("cv") public static native int createButton( @StdString String bar_name, ButtonCallback on_change); //------------------------- /** enum cv:: */ public static final int // 8bit, color or not IMREAD_UNCHANGED = -1, // 8bit, gray IMREAD_GRAYSCALE = 0, // ?, color IMREAD_COLOR = 1, // any depth, ? IMREAD_ANYDEPTH = 2, // ?, any color IMREAD_ANYCOLOR = 4; /** enum cv:: */ public static final int IMWRITE_JPEG_QUALITY = 1, IMWRITE_PNG_COMPRESSION = 16, IMWRITE_PNG_STRATEGY = 17, IMWRITE_PNG_BILEVEL = 18, IMWRITE_PNG_STRATEGY_DEFAULT = 0, IMWRITE_PNG_STRATEGY_FILTERED = 1, IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, IMWRITE_PNG_STRATEGY_RLE = 3, IMWRITE_PNG_STRATEGY_FIXED = 4, IMWRITE_PXM_BINARY = 32; @Namespace("cv") public static native @ByVal Mat imread( @StdString BytePointer filename, int flags/*=1*/ ); @Namespace("cv") public static native @ByVal Mat imread( @StdString BytePointer filename ); @Namespace("cv") public static native @ByVal Mat imread( @StdString String filename, int flags/*=1*/ ); @Namespace("cv") public static native @ByVal Mat imread( @StdString String filename ); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @ByVal Mat imdecode( @ByVal Mat buf, int flags ); @Namespace("cv") public static native @ByVal Mat imdecode( @ByVal Mat buf, int flags, Mat dst ); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf); // #ifndef CV_NO_VIDEO_CAPTURE_CPP_API @Namespace("cv") @NoOffset public static class VideoCapture extends Pointer { static { Loader.load(); } public VideoCapture(Pointer p) { super(p); } public VideoCapture() { allocate(); } private native void allocate(); public VideoCapture(@StdString BytePointer filename) { allocate(filename); } private native void allocate(@StdString BytePointer filename); public VideoCapture(@StdString String filename) { allocate(filename); } private native void allocate(@StdString String filename); public VideoCapture(int device) { allocate(device); } private native void allocate(int device); public native @Cast("bool") boolean open(@StdString BytePointer filename); public native @Cast("bool") boolean open(@StdString String filename); public native @Cast("bool") boolean open(int device); public native @Cast("bool") boolean isOpened(); public native void release(); public native @Cast("bool") boolean grab(); public native @Cast("bool") boolean retrieve(@ByRef Mat image, int channel/*=0*/); public native @Cast("bool") boolean retrieve(@ByRef Mat image); public native @ByRef @Name("operator>>") VideoCapture shiftRight(@ByRef Mat image); public native @Cast("bool") boolean read(@ByRef Mat image); public native @Cast("bool") boolean set(int propId, double value); public native double get(int propId); } @Namespace("cv") @NoOffset public static class VideoWriter extends Pointer { static { Loader.load(); } public VideoWriter(Pointer p) { super(p); } public VideoWriter(int size) { allocateArray(size); } private native void allocateArray(int size); @Override public VideoWriter position(int position) { return (VideoWriter)super.position(position); } public VideoWriter() { allocate(); } private native void allocate(); public VideoWriter(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/) { allocate(filename, fourcc, fps, frameSize, isColor); } private native void allocate(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public VideoWriter(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize) { allocate(filename, fourcc, fps, frameSize); } private native void allocate(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize); public VideoWriter(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/) { allocate(filename, fourcc, fps, frameSize, isColor); } private native void allocate(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public VideoWriter(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize) { allocate(filename, fourcc, fps, frameSize); } private native void allocate(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize); public native @Cast("bool") boolean open(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public native @Cast("bool") boolean open(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize); public native @Cast("bool") boolean open(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public native @Cast("bool") boolean open(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize); public native @Cast("bool") boolean isOpened(); public native void release(); public native @ByRef @Name("operator<<") VideoWriter shiftLeft(@Const @ByRef Mat image); public native void write(@Const @ByRef Mat image); } // #endif // #endif // #endif }
duongtung4691/javacpp.presets
opencv/src/main/java/com/googlecode/javacpp/opencv_highgui.java
Java
gpl-2.0
75,386