code stringlengths 5 1.01M | repo_name stringlengths 5 84 | path stringlengths 4 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 5 1.01M | input_ids listlengths 502 502 | token_type_ids listlengths 502 502 | attention_mask listlengths 502 502 | labels listlengths 502 502 |
|---|---|---|---|---|---|---|---|---|---|
/*
* 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.ode.bpel.compiler;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Basic implementation of the {@link ResourceFinder} interface. Resolves
* URIs relative to a base URI specified at the time of construction.
*
* @author Maciej Szefler - m s z e f l e r @ g m a i l . c o m
*
*/
public class DefaultResourceFinder implements ResourceFinder {
private static final Log __log = LogFactory.getLog(DefaultResourceFinder.class);
private File _relativeDir;
private File _absoluteDir;
/**
* Default constructor: resolve relative URIs against current working directory.
*/
public DefaultResourceFinder() {
_absoluteDir = new File("");
_relativeDir = _absoluteDir;
}
/**
* Constructor: resolve relative URIs against specified directory.
* @param relativeDir base path for relative URLs.
* @param absoluteDir base path for absolute URLs.
*/
public DefaultResourceFinder(File relativeDir, File absoluteDir) {
checkDir("relativeDir", relativeDir);
checkDir("absoluteDir", absoluteDir);
_relativeDir = relativeDir;
_absoluteDir = absoluteDir;
}
private void checkDir(String arg, File dir) {
if (dir == null) {
throw new IllegalArgumentException("Argument '"+arg+"' is null");
}
if (!dir.exists()) {
throw new IllegalArgumentException("Directory does not exist: " + dir);
}
}
public InputStream openResource(URI uri) throws MalformedURLException, IOException {
uri = relativize(uri);
InputStream r = openFileResource(uri);
if (r != null) {
return r;
}
if (__log.isDebugEnabled()) {
__log.debug("trying classpath resource for " + uri);
}
r = Thread.currentThread().getContextClassLoader().getResourceAsStream(uri.getPath());
if (r != null) {
return r;
} else {
if (__log.isDebugEnabled()) {
__log.debug("classpath resource not found " + uri);
}
return null;
}
}
private InputStream openFileResource(URI uri) throws MalformedURLException, IOException {
URI absolute = _absoluteDir.toURI();
if (__log.isDebugEnabled()) {
__log.debug("openResource: uri="+uri+" relativeDir="+_relativeDir+" absoluteDir="+_absoluteDir);
}
if (uri.isAbsolute() && uri.getScheme().equals("file")) {
try {
return uri.toURL().openStream();
} catch (Exception except) {
__log.debug("openResource: unable to open file URL " + uri + "; " + except.toString());
return null;
}
}
// Note that if we get an absolute URI, the relativize operation will simply
// return the absolute URI.
URI relative = _relativeDir.toURI().relativize(uri);
if (relative.isAbsolute() && !(relative.getScheme().equals("urn"))) {
__log.fatal("openResource: invalid scheme (should be urn:) " + uri);
return null;
}
File f = new File(absolute.getPath(), relative.getPath());
if (f.exists()) {
return new FileInputStream(f);
} else {
if (__log.isDebugEnabled()) {
__log.debug("fileNotFound: " + f);
}
return null;
}
}
public URI getBaseResourceURI() {
return _absoluteDir.toURI();
}
private URI relativize(URI u) {
if (u.isAbsolute()) {
return _absoluteDir.toURI().relativize(u);
} else return u;
}
public URI resolve(URI parent, URI child) {
parent = relativize(parent);
child = relativize(child);
URI result = parent.resolve(child);
URI result2 = _absoluteDir.toURI().resolve(result);
if (__log.isDebugEnabled()) {
__log.debug("resolving URI: parent " + parent + " child " + child + " result " + result + " resultAbsolute:" + result2);
}
return result2;
}
}
| riftsaw/riftsaw-ode | bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/DefaultResourceFinder.java | Java | apache-2.0 | 5,182 | [
30522,
1013,
1008,
1008,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
1008,
2030,
2062,
12130,
6105,
10540,
1012,
2156,
1996,
5060,
5371,
1008,
5500,
2007,
2023,
2147,
2005,
3176,
2592,
1008,
4953,
9385,
6095,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
namespace module;
use Exception;
use Zend\Config\Reader\Ini;
use Zend\Config\Config;
use ulfberht\core\module;
use module\application\service\store;
use module\application\service\request;
use module\application\service\response;
use module\application\service\router;
use module\application\service\doctrine;
/**
* The application module is the backbone of Ulfberht Applications and provides much of the
* automatical things we see like initializing configurations.
*/
class application extends module {
/**
* The constructor. Registers all services for the application module.
*/
public function __construct() {
$this->dependsOn('module\debugger');
$this->registerSingleton('module\application\controller\resourceBundle');
$this->registerSingleton('module\application\service\store');
$this->registerSingleton('module\application\service\doctrine');
$this->registerSingleton('module\application\service\request');
$this->registerSingleton('module\application\service\response');
$this->registerSingleton('module\application\service\router');
$this->registerSingleton('module\application\service\view');
$this->registerFactory('module\application\service\doctrine\config');
$this->registerFactory('module\application\service\minifier');
}
/**
* [Ulfberht Forging Hook] Initializes an ulfberht application.
* @param $store module\application\service\store
* @param $request module\application\service\request
* @param $router module\application\service\router
* @return void
*/
public function applicationInit(store $store, request $request, router $router, doctrine $doctrine) {
$this->applicationInitConfig($store, $request);
$this->applicationInitRoutes($store, $router);
$this->applicationInitDoctrine($store, $doctrine);
}
/**
* [Ulfberht Forging Hook] This method is responsible for loading in initial
* application configurations from application ini files located in
* /src/module/application/configs/application.ini.
* @param $store module\application\service\store
* @param $request module\application\service\request
* @return void
*/
public function applicationInitConfig(store $store, request $request) {
//get app config and loop though additional configs
$appConfigSrcPath = APPLICATION_ROOT . '/src/module/application/config/application.ini';
$appConfigIni = $this->_getConfigIniFromIniPath($appConfigSrcPath);
$appConfigName = $this->_getFileNameFromIniPath($appConfigSrcPath);
$store->set($appConfigName, $appConfigIni);
//look through application config configs array and setup those configs
$configs = ($appConfigIni->configs) ? $appConfigIni->configs : [];
foreach ($appConfigIni->application->configs as $storePath) {
$storeSrcPath = APPLICATION_ROOT . $storePath;
$configName = $this->_getFileNameFromIniPath($storeSrcPath);
$configIni = $this->_getConfigIniFromIniPath($storeSrcPath);
$existingConfig = $store->get($configName);
if ($existingConfig) {
$existingConfig->merge($configIni);
} else {
$store->set($configName, $configIni);
}
}
//setup env config
$host = $request->server->get('HTTP_HOST');
//if host comes back undefined assume localhost:8000 settings
if (!$host) {
$host = 'localhost:8000';
}
$environmentConfig = $store->get('environment');
$envVar = false;
foreach ($environmentConfig->environments as $environmentVar => $domain) {
if (strtolower($host) === strtolower($domain)) {
$envVar = $environmentVar;
break;
}
}
if (!$envVar) {
throw new Exception('Could not find proper environment config variable for host "' . $host . '"');
} else {
$envConfig = $store->get('environment')->{$envVar};
$store->set('ENV', $envConfig);
}
}
/**
* [Ulfberht Forging Hook] This method is responsible for loading in routes
* based on routes.ini
* @param $store module\application\service\store
* @param $request module\application\service\router
* @return void
*/
public function applicationInitRoutes(store $store, router $router) {
$env = $store->get('ENV');
$routesConfig = $store->get('routes');
foreach ($routesConfig->routes as $key => $route) {
$path = $route->path;
$verb = $route->verb;
$controller = $route->controller . ':' . $route->action;
$router->{$verb}($path, $controller);
}
//setting default controller if it is set in routes.ini
if ($routesConfig->default->controller && $routesConfig->default->action) {
$router->otherwise($routesConfig->default->controller . ':' . $routesConfig->default->action);
}
//set routes for resource bundles if in develop mode
if ($env->application->debug) {
$router->get('/debug/bundle/js/{resourceBundleId}', 'module\application\controller\resourceBundle:js');
$router->get('/debug/bundle/css/{resourceBundleId}', 'module\application\controller\resourceBundle:css');
}
}
/**
* This method is responsible for setting up the application entity manager
* based on application.ini and environment.ini configs.
* @param $store module\application\service\store
* @return void
*/
public function applicationInitDoctrine(store $store, doctrine $doctrine) {
$envConfig = $store->get('ENV');
$applicationConfig = $store->get('application');
//get new doctrine config object.
$doctrineConfig = $this->get('module\application\service\doctrine\config');
$doctrineConfig->develop = $envConfig->application->debug;
$doctrineConfig->enableCache = $envConfig->doctrine->cache;
$doctrineConfig->type = $applicationConfig->doctrine->type;
$doctrineConfig->database->driver = $envConfig->database->driver;
$doctrineConfig->database->host = $envConfig->database->host;
$doctrineConfig->database->name = $envConfig->database->name;
$doctrineConfig->database->user = $envConfig->database->user;
$doctrineConfig->database->password = $envConfig->database->password;
//setting doctrine paths
$doctrinePaths = [];
foreach ($applicationConfig->doctrine->paths as $path) {
$doctrinePaths[] = APPLICATION_ROOT . $path;
}
$doctrineConfig->paths = $doctrinePaths;
//set doctrine application config
$doctrine->addEntityManager('application', $doctrineConfig);
}
/**
* [Ulfberht Forging Hook] This method is setup to run as a hook when forging
* an ulfberht application. The purpose of this hook is to resolve a path to
* a controller and run that controller's action.
* @param $router module\application\service\router
* @param $request module\application\service\request
* @param $response module\application\service\response
* @return void
*/
public function applicationMvc(router $router, request $request, response $response) {
$params = $router->resolve();
$request->attributes->add($params);
$controllerActionSetting = explode(':', $params['controller']);
$controllerClass = $controllerActionSetting[0];
$controllerAction = (isset($controllerActionSetting[1])) ? $controllerActionSetting[1] : false;
if (!$controllerClass) {
throw new Exception('Could not find a controller to resolve.');
}
if (!$controllerAction) {
throw new Exception('A controller action was not defined.');
}
if (!ulfberht()->exists($controllerClass)) {
throw new Exception('Could not find controller "' . $controllerClass . '"');
}
$controller = ulfberht()->get($controllerClass);
if ($controllerAction) {
if (!method_exists($controller, $controllerAction)) {
throw new Exception('Cound not find action method "' . $controllerAction . '" on controller "' . $controllerClass . '"');
}
call_user_func([$controller, $controllerAction]);
}
$response->prepare($request);
$response->send();
}
/**
* This method is responsible for returning a configIni object wrapping
* which ever ini file is passed in.
* @param $fileSrcPath string The path to the ini file.
* @return Zend\Config\Config
*/
private function _getConfigIniFromIniPath($fileSrcPath) {
$reader = new Ini();
$config = $reader->fromFile($fileSrcPath);
return new Config($config);
}
/**
* Returns the filename of the files source path you pass into it.
* @param $fileSrcPath string The path to the ini file.
* @return string The filename parsed out of the path.
*/
private function _getFileNameFromIniPath($fileSrcPath) {
$pathParts = preg_split('/\//', $fileSrcPath);
$fileName = $pathParts[count($pathParts) - 1];
$fileNameParts = preg_split('/\./', $fileName);
return $fileNameParts[0];
}
}
| ua1-labs/ulfberht-application | src/module/application.php | PHP | mit | 9,505 | [
30522,
1026,
1029,
25718,
3415,
15327,
11336,
1025,
2224,
6453,
1025,
2224,
16729,
2094,
1032,
9530,
8873,
2290,
1032,
8068,
1032,
1999,
2072,
1025,
2224,
16729,
2094,
1032,
9530,
8873,
2290,
1032,
9530,
8873,
2290,
1025,
2224,
17359,
26337... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
dimensions(8,8)
wall((2,0),(2,4))
wall((2,4),(4,4))
wall((2,6),(6,6))
wall((6,6),(6,0))
wall((6,2),(4,2))
initialRobotLoc(1.0, 1.0)
| Cynary/distro6.01 | arch/6.01Soft/lib601-F13-4/soar/worlds/bigFrustrationWorld.py | Python | mit | 133 | [
30522,
9646,
1006,
1022,
1010,
1022,
1007,
2813,
1006,
1006,
1016,
1010,
1014,
1007,
1010,
1006,
1016,
1010,
1018,
1007,
1007,
2813,
1006,
1006,
1016,
1010,
1018,
1007,
1010,
1006,
1018,
1010,
1018,
1007,
1007,
2813,
1006,
1006,
1016,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright 2004-2006 Adrian Thurston <thurston@complang.org>
* 2004 Erich Ocean <eric.ocean@ampede.com>
* 2005 Alan West <alan@alanz.com>
*/
/* This file is part of Ragel.
*
* Ragel 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.
*
* Ragel 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 Ragel; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ragel.h"
#include "fflat.h"
#include "redfsm.h"
#include "gendata.h"
using std::endl;
namespace Go {
std::ostream &GoFFlatCodeGen::TO_STATE_ACTION( RedStateAp *state )
{
int act = 0;
if ( state->toStateAction != 0 )
act = state->toStateAction->actListId+1;
out << act;
return out;
}
std::ostream &GoFFlatCodeGen::FROM_STATE_ACTION( RedStateAp *state )
{
int act = 0;
if ( state->fromStateAction != 0 )
act = state->fromStateAction->actListId+1;
out << act;
return out;
}
std::ostream &GoFFlatCodeGen::EOF_ACTION( RedStateAp *state )
{
int act = 0;
if ( state->eofAction != 0 )
act = state->eofAction->actListId+1;
out << act;
return out;
}
/* Write out the function for a transition. */
std::ostream &GoFFlatCodeGen::TRANS_ACTION( RedTransAp *trans )
{
int action = 0;
if ( trans->action != 0 )
action = trans->action->actListId+1;
out << action;
return out;
}
/* Write out the function switch. This switch is keyed on the values
* of the func index. */
std::ostream &GoFFlatCodeGen::TO_STATE_ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numToStateRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, false, false );
}
}
genLineDirective( out );
return out;
}
/* Write out the function switch. This switch is keyed on the values
* of the func index. */
std::ostream &GoFFlatCodeGen::FROM_STATE_ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numFromStateRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, false, false );
}
}
genLineDirective( out );
return out;
}
std::ostream &GoFFlatCodeGen::EOF_ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numEofRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, true, false );
}
}
genLineDirective( out );
return out;
}
/* Write out the function switch. This switch is keyed on the values
* of the func index. */
std::ostream &GoFFlatCodeGen::ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numTransRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, false, false );
}
}
genLineDirective( out );
return out;
}
void GoFFlatCodeGen::writeData()
{
if ( redFsm->anyConditions() ) {
OPEN_ARRAY( WIDE_ALPH_TYPE(), CK() );
COND_KEYS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCondSpan), CSP() );
COND_KEY_SPANS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCond), C() );
CONDS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCondIndexOffset), CO() );
COND_INDEX_OFFSET();
CLOSE_ARRAY() <<
endl;
}
OPEN_ARRAY( WIDE_ALPH_TYPE(), K() );
KEYS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxSpan), SP() );
KEY_SPANS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxFlatIndexOffset), IO() );
FLAT_INDEX_OFFSET();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxIndex), I() );
INDICIES();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxState), TT() );
TRANS_TARGS();
CLOSE_ARRAY() <<
endl;
if ( redFsm->anyActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActListId), TA() );
TRANS_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyToStateActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActionLoc), TSA() );
TO_STATE_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyFromStateActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActionLoc), FSA() );
FROM_STATE_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyEofActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActListId), EA() );
EOF_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyEofTrans() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxIndexOffset+1), ET() );
EOF_TRANS();
CLOSE_ARRAY() <<
endl;
}
STATE_IDS();
}
void GoFFlatCodeGen::writeExec()
{
testEofUsed = false;
outLabelUsed = false;
out <<
" {" << endl <<
" var _slen " << INT() << endl;
if ( redFsm->anyRegCurStateRef() )
out << " var _ps " << INT() << endl;
out << " var _trans " << INT() << endl;
if ( redFsm->anyConditions() )
out << " var _cond " << INT() << endl;
out <<
" var _keys " << INT() << endl <<
" var _inds " << INT() << endl;
if ( redFsm->anyConditions() ) {
out <<
" var _conds " << INT() << endl <<
" var _widec " << WIDE_ALPH_TYPE() << endl;
}
if ( !noEnd ) {
testEofUsed = true;
out <<
" if " << P() << " == " << PE() << " {" << endl <<
" goto _test_eof" << endl <<
" }" << endl;
}
if ( redFsm->errState != 0 ) {
outLabelUsed = true;
out <<
" if " << vCS() << " == " << redFsm->errState->id << " {" << endl <<
" goto _out" << endl <<
" }" << endl;
}
out << "_resume:" << endl;
if ( redFsm->anyFromStateActions() ) {
out <<
" switch " << FSA() << "[" << vCS() << "] {" << endl;
FROM_STATE_ACTION_SWITCH(1);
out <<
" }" << endl <<
endl;
}
if ( redFsm->anyConditions() )
COND_TRANSLATE();
LOCATE_TRANS();
if ( redFsm->anyEofTrans() )
out << "_eof_trans:" << endl;
if ( redFsm->anyRegCurStateRef() )
out << " _ps = " << vCS() << endl;
out <<
" " << vCS() << " = " << CAST(INT(), TT() + "[_trans]") << endl <<
endl;
if ( redFsm->anyRegActions() ) {
out <<
" if " << TA() << "[_trans] == 0 {" << endl <<
" goto _again" << endl <<
" }" << endl <<
endl <<
" switch " << TA() << "[_trans] {" << endl;
ACTION_SWITCH(1);
out <<
" }" << endl <<
endl;
}
if ( redFsm->anyRegActions() || redFsm->anyActionGotos() ||
redFsm->anyActionCalls() || redFsm->anyActionRets() )
out << "_again:" << endl;
if ( redFsm->anyToStateActions() ) {
out <<
" switch " << TSA() << "[" << vCS() << "] {" << endl;
TO_STATE_ACTION_SWITCH(1);
out <<
" }" << endl <<
endl;
}
if ( redFsm->errState != 0 ) {
outLabelUsed = true;
out <<
" if " << vCS() << " == " << redFsm->errState->id << " {" << endl <<
" goto _out" << endl <<
" }" << endl;
}
if ( !noEnd ) {
out <<
" if " << P() << "++; " << P() << " != " << PE() << " {"
" goto _resume" << endl <<
" }" << endl;
}
else {
out <<
" " << P() << "++" << endl <<
" goto _resume" << endl;
}
if ( testEofUsed )
out << " _test_eof: {}" << endl;
if ( redFsm->anyEofTrans() || redFsm->anyEofActions() ) {
out <<
" if " << P() << " == " << vEOF() << " {" << endl;
if ( redFsm->anyEofTrans() ) {
out <<
" if " << ET() << "[" << vCS() << "] > 0 {" << endl <<
" _trans = " << CAST(INT(), ET() + "[" + vCS() + "] - 1") << endl <<
" goto _eof_trans" << endl <<
" }" << endl;
}
if ( redFsm->anyEofActions() ) {
out <<
" switch " << EA() << "[" << vCS() << "] {" << endl;
EOF_ACTION_SWITCH(2);
out <<
" }" << endl;
}
out <<
" }" << endl <<
endl;
}
if ( outLabelUsed )
out << " _out: {}" << endl;
out << " }" << endl;
}
}
| kennytm/ragel | src/go/fflat.cc | C++ | gpl-2.0 | 9,175 | [
30522,
1013,
1008,
1008,
9385,
2432,
1011,
2294,
7918,
16215,
29402,
2239,
1026,
16215,
29402,
2239,
1030,
4012,
24759,
5654,
1012,
8917,
1028,
1008,
2432,
17513,
4153,
1026,
4388,
1012,
4153,
1030,
23713,
14728,
1012,
4012,
1028,
1008,
238... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
---
layout: post
title: 棋子翻转(美团)
categories: C和C++基础
description: 编程基础。
keywords: C++,基础
---
#### 题目描述
在4x4的棋盘上摆满了黑白棋子,黑白两色的位置和数目随机,其中左上角坐标为(1,1),右下角坐标为(4,4),现在依次有一些翻转操作,要对一些给定支点坐标为中心的上下左右四个棋子的颜色进行翻转,请计算出翻转后的棋盘颜色。
给定两个数组A和f,分别为初始棋盘和翻转位置。其中翻转位置共有3个。请返回翻转后的棋盘。
测试样例:
[[0,0,1,1],[1,0,1,0],[0,1,1,0],[0,0,1,0]],[[2,2],[3,3],[4,4]]
返回:[[0,1,1,1],[0,0,1,0],[0,1,1,0],[0,0,1,0]]
#### 程序代码
```cpp
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int> > flipChess(vector<vector<int> > A, vector<vector<int> > f){
for(int i=0;i<f.size();i++){
int x=f[i][0]-1;
int y=f[i][1]-1;
if(x-1>=0){
if(A[x-1][y]==1)
A[x-1][y]=0;
else
A[x-1][y]=1;
}
if(x+1<=3){
if(A[x+1][y]==1)
A[x+1][y]=0;
else
A[x+1][y]=1;
}
if(y-1>=0){
if(A[x][y-1]==1)
A[x][y-1]=0;
else
A[x][y-1]=1;
}
if(y+1<=3){
if(A[x][y+1]==1)
A[x][y+1]=0;
else
A[x][y+1]=1;
}
}
for(int i=0;i<A.size();i++){
for(int j=0;j<A[i].size();j++){
cout<<A[i][j]<<" ";
}
cout<<endl;
}
return A;
}
int main(){
int a1[4]={0,0,1,1};
int a2[4]={1,0,1,0};
int a3[4]={0,1,1,0};
int a4[4]={0,0,1,0};
vector<int> arr1(a1,a1+4);
vector<int> arr2(a2,a2+4);
vector<int> arr3(a3,a3+4);
vector<int> arr4(a4,a4+4);
vector<vector<int> >A;
A.push_back(arr1);
A.push_back(arr2);
A.push_back(arr3);
A.push_back(arr4);
int af1[2]={2,2};
int af2[2]={3,3};
int af3[2]={4,4};
vector<int> f1(af1,af1+2);
vector<int> f2(af2,af2+2);
vector<int> f3(af3,af3+2);
vector<vector<int> > f;
f.push_back(f1);
f.push_back(f2);
f.push_back(f3);
flipChess(A,f);
system("pause");
}
```
| Lzpgithub/Lzpgithub.github.io | _wiki/2016-05-07-flipchess.md | Markdown | mit | 1,972 | [
30522,
1011,
1011,
1011,
9621,
1024,
2695,
2516,
1024,
100,
1816,
100,
100,
1006,
1935,
100,
1007,
7236,
1024,
1039,
1796,
1039,
1009,
1009,
100,
100,
6412,
1024,
100,
100,
100,
100,
1636,
3145,
22104,
1024,
1039,
1009,
1009,
1989,
100,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package net.jsunit.utility;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
public class FileUtility {
public static void delete(File file) {
if (file.exists())
file.delete();
}
public static void write(File file, String contents) {
try {
if (file.exists())
file.delete();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
out.write(contents.getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| wesmaldonado/test-driven-javascript-example-application | public/js-common/jsunit/java/source_core/net/jsunit/utility/FileUtility.java | Java | mit | 658 | [
30522,
7427,
5658,
1012,
1046,
19729,
4183,
1012,
9710,
1025,
12324,
9262,
1012,
22834,
1012,
17698,
26010,
4904,
18780,
21422,
1025,
12324,
9262,
1012,
22834,
1012,
5371,
1025,
12324,
9262,
1012,
22834,
1012,
5371,
5833,
18780,
21422,
1025,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Infinite Scroll Grid Example</title>
<link rel="stylesheet" href="https://static.rasc.ch/ext-6.5.2/build/examples/classic/shared/examples.css" />
<script src="https://static.rasc.ch/ext-6.5.2/build/examples/classic/shared/include-ext.js"></script>
<script src="https://static.rasc.ch/ext-6.5.2/build/examples/classic/shared/options-toolbar.js"></script>
<script src="../api-debug.js?group=store"></script>
<script type="text/javascript" src="infinite-scroll.js"></script>
</head>
<body>
<h1>Infinite Scrolling</h1>
<p>
Source code: <a href="infinite-scroll.js">infinite-scroll.js</a>
</p>
</body>
</html>
| ralscha/extdirectspring-demo | src/main/resources/static/extjs6classic/infinite-scroll.html | HTML | apache-2.0 | 875 | [
30522,
1026,
999,
9986,
13874,
16129,
1028,
1026,
16129,
1028,
1026,
2132,
1028,
1026,
18804,
8299,
1011,
1041,
15549,
2615,
1027,
1000,
1060,
1011,
25423,
1011,
11892,
1000,
4180,
1027,
1000,
29464,
1027,
3341,
1000,
1028,
1026,
18804,
217... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
namespace N98\Magento\Command\System\Cron;
use Symfony\Component\Console\Helper\DialogHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Cron\Model\Schedule;
class RunCommand extends AbstractCronCommand
{
const REGEX_RUN_MODEL = '#^([a-z0-9_]+/[a-z0-9_]+)::([a-z0-9_]+)$#i';
/**
* @var array
*/
protected $infos;
protected function configure()
{
$this
->setName('sys:cron:run')
->addArgument('job', InputArgument::OPTIONAL, 'Job code')
->setDescription('Runs a cronjob by job code');
$help = <<<HELP
If no `job` argument is passed you can select a job from a list.
See it in action: http://www.youtube.com/watch?v=QkzkLgrfNaM
HELP;
$this->setHelp($help);
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @throws \Exception
* @return int|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$jobCode = $input->getArgument('job');
$jobs = $this->getJobs();
if (!$jobCode) {
$this->writeSection($output, 'Cronjob');
$jobCode = $this->askJobCode($input, $output, $jobs);
}
$jobConfig = $this->getJobConfig($jobCode);
if (empty($jobCode) || !isset($jobConfig['instance'])) {
throw new \InvalidArgumentException('No job config found!');
}
$model = $this->getObjectManager()->get($jobConfig['instance']);
if (!$model || !is_callable(array($model, $jobConfig['method']))) {
throw new \RuntimeException(
sprintf(
'Invalid callback: %s::%s does not exist',
$jobConfig['instance'],
$jobConfig['method']
)
);
}
$callback = array($model, $jobConfig['method']);
$output->write(
'<info>Run </info><comment>' . $jobConfig['instance'] . '::' . $jobConfig['method'] . '</comment> '
);
try {
$schedule = $this->_cronScheduleCollection->getNewEmptyItem();
$schedule
->setJobCode($jobCode)
->setStatus(Schedule::STATUS_RUNNING)
->setExecutedAt(strftime('%Y-%m-%d %H:%M:%S', time()))
->save();
$this->_state->emulateAreaCode('crontab', $callback, array($schedule));
$schedule
->setStatus(Schedule::STATUS_SUCCESS)
->setFinishedAt(strftime('%Y-%m-%d %H:%M:%S', time()))
->save();
} catch (Exception $e) {
$schedule
->setStatus(Schedule::STATUS_ERROR)
->setMessages($e->getMessage())
->setFinishedAt(strftime('%Y-%m-%d %H:%M:%S', time()))
->save();
}
$output->writeln('<info>done</info>');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @param array $jobs
* @return string
* @throws \InvalidArgumentException
* @throws \Exception
*/
protected function askJobCode(InputInterface $input, OutputInterface $output, $jobs)
{
foreach ($jobs as $key => $job) {
$question[] = '<comment>[' . ($key + 1) . ']</comment> ' . $job['Job'] . PHP_EOL;
}
$question[] = '<question>Please select job: </question>' . PHP_EOL;
/** @var $dialog DialogHelper */
$dialog = $this->getHelper('dialog');
$jobCode = $dialog->askAndValidate(
$output,
$question,
function ($typeInput) use ($jobs) {
if (!isset($jobs[$typeInput - 1])) {
throw new \InvalidArgumentException('Invalid job');
}
return $jobs[$typeInput - 1]['Job'];
}
);
return $jobCode;
}
}
| p-makowski/n98-magerun2 | src/N98/Magento/Command/System/Cron/RunCommand.php | PHP | mit | 4,044 | [
30522,
1026,
1029,
25718,
3415,
15327,
1050,
2683,
2620,
1032,
17454,
13663,
1032,
3094,
1032,
2291,
1032,
13675,
2239,
1025,
2224,
25353,
2213,
14876,
4890,
1032,
6922,
1032,
10122,
1032,
2393,
2121,
1032,
13764,
8649,
16001,
4842,
1025,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- integrating.qdoc -->
<title>Qt 4.8: Integrating QML Code with Existing Qt UI Code</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/functions.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style/superfish.css" />
<link rel="stylesheet" type="text/css" href="style/narrow.css" />
<!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->
<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>
</head>
<body class="" onload="CheckEmptyAndLoadList();">
<div class="header" id="qtdocheader">
<div class="content">
<div id="nav-logo">
<a href="index.html">Home</a></div>
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
<div id="narrowsearch"></div>
<div id="nav-topright">
<ul>
<li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
<li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
<li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
DOC</a></li>
<li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
</ul>
</div>
<div id="shortCut">
<ul>
<li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
<li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li>
</ul>
</div>
<ul class="sf-menu" id="narrowmenu">
<li><a href="#">API Lookup</a>
<ul>
<li><a href="classes.html">Class index</a></li>
<li><a href="functions.html">Function index</a></li>
<li><a href="modules.html">Modules</a></li>
<li><a href="namespaces.html">Namespaces</a></li>
<li><a href="qtglobal.html">Global Declarations</a></li>
<li><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</li>
<li><a href="#">Qt Topics</a>
<ul>
<li><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li><a href="supported-platforms.html">Supported Platforms</a></li>
<li><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</li>
<li><a href="#">Examples</a>
<ul>
<li><a href="all-examples.html">Examples</a></li>
<li><a href="tutorials.html">Tutorials</a></li>
<li><a href="demos.html">Demos</a></li>
<li><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="wrapper">
<div class="hd">
<span></span>
</div>
<div class="bd group">
<div class="sidebar">
<div class="searchlabel">
Search index:</div>
<div class="search" id="sidebarsearch">
<form id="qtdocsearch" action="" onsubmit="return false;">
<fieldset>
<input type="text" name="searchstring" id="pageType" value="" />
<div id="resultdialog">
<a href="#" id="resultclose">Close</a>
<p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p>
<p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span> results:</p>
<ul id="resultlist" class="all">
</ul>
</div>
</fieldset>
</form>
</div>
<div class="box first bottombar" id="lookup">
<h2 title="API Lookup"><span></span>
API Lookup</h2>
<div id="list001" class="list">
<ul id="ul001" >
<li class="defaultLink"><a href="classes.html">Class index</a></li>
<li class="defaultLink"><a href="functions.html">Function index</a></li>
<li class="defaultLink"><a href="modules.html">Modules</a></li>
<li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
<li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
<li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</div>
</div>
<div class="box bottombar" id="topics">
<h2 title="Qt Topics"><span></span>
Qt Topics</h2>
<div id="list002" class="list">
<ul id="ul002" >
<li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li class="defaultLink"><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>
<li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</div>
</div>
<div class="box" id="examples">
<h2 title="Examples"><span></span>
Examples</h2>
<div id="list003" class="list">
<ul id="ul003">
<li class="defaultLink"><a href="all-examples.html">Examples</a></li>
<li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
<li class="defaultLink"><a href="demos.html">Demos</a></li>
<li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</div>
</div>
</div>
<div class="wrap">
<div class="toolbar">
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Breadcrumbs go here -->
<li>Integrating QML Code with Existing Qt UI Code</li>
</ul>
</div>
<div class="toolbuttons toolblock">
<ul>
<li id="smallA" class="t_button">A</li>
<li id="medA" class="t_button active">A</li>
<li id="bigA" class="t_button">A</li>
<li id="print" class="t_button"><a href="javascript:this.print();">
<span>Print</span></a></li>
</ul>
</div>
</div>
<div class="content mainContent">
<link rel="prev" href="qtbinding.html" />
<link rel="next" href="qdeclarativedynamicobjects.html" />
<p class="naviNextPrevious headerNavi">
<a class="prevPage" href="qtbinding.html">Using QML Bindings in C++ Applications</a>
<a class="nextPage" href="qdeclarativedynamicobjects.html">Dynamic Object Management</a>
</p><p/>
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#integrating-with-a-qwidget-based-ui">Integrating with a <a href="qwidget.html">QWidget</a>-based UI</a></li>
<li class="level1"><a href="#integrating-with-a-qgraphicsview-based-ui">Integrating with a QGraphicsView-based UI</a></li>
<li class="level2"><a href="#adding-qml-widgets-to-a-qgraphicsscene">Adding QML widgets to a QGraphicsScene</a></li>
<li class="level2"><a href="#loading-qgraphicswidget-objects-in-qml">Loading QGraphicsWidget objects in QML</a></li>
</ul>
</div>
<h1 class="title">Integrating QML Code with Existing Qt UI Code</h1>
<span class="subtitle"></span>
<!-- $$$qml-integration.html-description -->
<div class="descr"> <a name="details"></a>
<p>There are a number of ways to integrate QML into <a href="qwidget.html">QWidget</a>-based UI applications, depending on the characteristics of your existing UI code.</p>
<a name="integrating-with-a-qwidget-based-ui"></a>
<h2>Integrating with a <a href="qwidget.html">QWidget</a>-based UI</h2>
<p>If you have an existing <a href="qwidget.html">QWidget</a>-based UI, QML widgets can be integrated into it using <a href="qdeclarativeview.html">QDeclarativeView</a>. <a href="qdeclarativeview.html">QDeclarativeView</a> is a subclass of <a href="qwidget.html">QWidget</a> so you can add it to your user interface like any other <a href="qwidget.html">QWidget</a>. Use <a href="qdeclarativeview.html#source-prop">QDeclarativeView::setSource</a>() to load a QML file into the view, then add the view to your UI:</p>
<pre class="cpp"> <span class="type"><a href="qdeclarativeview.html">QDeclarativeView</a></span> <span class="operator">*</span>qmlView <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qdeclarativeview.html">QDeclarativeView</a></span>;
qmlView<span class="operator">-</span><span class="operator">></span>setSource(<span class="type"><a href="qurl.html">QUrl</a></span><span class="operator">::</span>fromLocalFile(<span class="string">"myqml.qml"</span>));
<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>widget <span class="operator">=</span> myExistingWidget();
<span class="type"><a href="qvboxlayout.html">QVBoxLayout</a></span> <span class="operator">*</span>layout <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qvboxlayout.html">QVBoxLayout</a></span>(widget);
layout<span class="operator">-</span><span class="operator">></span>addWidget(qmlView);</pre>
<p>The one drawback to this approach is that <a href="qdeclarativeview.html">QDeclarativeView</a> is slower to initialize and uses more memory than a <a href="qwidget.html">QWidget</a>, and creating large numbers of <a href="qdeclarativeview.html">QDeclarativeView</a> objects may lead to performance degradation. If this is the case, it may be better to rewrite your widgets in QML, and load the widgets from a main QML widget instead of using <a href="qdeclarativeview.html">QDeclarativeView</a>.</p>
<p>Keep in mind that QWidgets were designed for a different type of user interface than QML, so it is not always a good idea to port a <a href="qwidget.html">QWidget</a>-based application to QML. QWidgets are a better choice if your UI is comprised of a small number of complex and static elements, and QML is a better choice if your UI is comprised of a large number of simple and dynamic elements.</p>
<a name="integrating-with-a-qgraphicsview-based-ui"></a>
<h2>Integrating with a QGraphicsView-based UI</h2>
<a name="adding-qml-widgets-to-a-qgraphicsscene"></a>
<h3>Adding QML widgets to a QGraphicsScene</h3>
<p>If you have an existing UI based on the <a href="graphicsview.html">Graphics View Framework</a>, you can integrate QML widgets directly into your <a href="qgraphicsscene.html">QGraphicsScene</a>. Use <a href="qdeclarativecomponent.html">QDeclarativeComponent</a> to create a <a href="qgraphicsobject.html">QGraphicsObject</a> from a QML file, and place the graphics object into your scene using <a href="qgraphicsscene.html#addItem">QGraphicsScene::addItem</a>(), or reparent it to an item already in the <a href="qgraphicsscene.html">QGraphicsScene</a>.</p>
<p>For example:</p>
<pre class="cpp"> <span class="type"><a href="qgraphicsscene.html">QGraphicsScene</a></span><span class="operator">*</span> scene <span class="operator">=</span> myExistingGraphicsScene();
<span class="type"><a href="qdeclarativeengine.html">QDeclarativeEngine</a></span> <span class="operator">*</span>engine <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qdeclarativeengine.html">QDeclarativeEngine</a></span>;
<span class="type"><a href="qdeclarativecomponent.html">QDeclarativeComponent</a></span> component(engine<span class="operator">,</span> <span class="type"><a href="qurl.html">QUrl</a></span><span class="operator">::</span>fromLocalFile(<span class="string">"myqml.qml"</span>));
<span class="type"><a href="qgraphicsobject.html">QGraphicsObject</a></span> <span class="operator">*</span>object <span class="operator">=</span>
qobject_cast<span class="operator"><</span><span class="type"><a href="qgraphicsobject.html">QGraphicsObject</a></span> <span class="operator">*</span><span class="operator">></span>(component<span class="operator">.</span>create());
scene<span class="operator">-</span><span class="operator">></span>addItem(object);</pre>
<p>The following <a href="qgraphicsview.html">QGraphicsView</a> options are recommended for optimal performance of QML UIs:</p>
<ul>
<li>QGraphicsView::setOptimizationFlags(<a href="qgraphicsview.html#OptimizationFlag-enum">QGraphicsView::DontSavePainterState</a>)</li>
<li>QGraphicsView::setViewportUpdateMode(<a href="qgraphicsview.html#ViewportUpdateMode-enum">QGraphicsView::BoundingRectViewportUpdate</a>)</li>
<li>QGraphicsScene::setItemIndexMethod(<a href="qgraphicsscene.html#ItemIndexMethod-enum">QGraphicsScene::NoIndex</a>)</li>
</ul>
<a name="loading-qgraphicswidget-objects-in-qml"></a>
<h3>Loading QGraphicsWidget objects in QML</h3>
<p>An alternative approach is to expose your existing <a href="qgraphicswidget.html">QGraphicsWidget</a> objects to QML and construct your scene in QML instead. See the <a href="declarative-cppextensions-qgraphicslayouts.html">graphics layouts example</a> which shows how to expose Qt's graphics layout classes to QML in order to use <a href="qgraphicswidget.html">QGraphicsWidget</a> with classes like <a href="qgraphicslinearlayout.html">QGraphicsLinearLayout</a> and <a href="qgraphicsgridlayout.html">QGraphicsGridLayout</a>.</p>
<p>To expose your existing <a href="qgraphicswidget.html">QGraphicsWidget</a> classes to QML, use <a href="qdeclarativeengine.html#qmlRegisterType">qmlRegisterType</a>(). See <a href="qml-extending.html">Extending QML Functionalities using C++</a> for further information on how to use C++ types in QML.</p>
</div>
<!-- @@@qml-integration.html -->
<p class="naviNextPrevious footerNavi">
<a class="prevPage" href="qtbinding.html">Using QML Bindings in C++ Applications</a>
<a class="nextPage" href="qdeclarativedynamicobjects.html">Dynamic Object Management</a>
</p>
</div>
</div>
</div>
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2012 Digia Plc and/or its
subsidiaries. Documentation contributions included herein are the copyrights of
their respective owners.</p>
<br />
<p>
The documentation provided herein is licensed under the terms of the
<a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
License version 1.3</a> as published by the Free Software Foundation.</p>
<p>
Documentation sources may be obtained from <a href="http://www.qt-project.org">
www.qt-project.org</a>.</p>
<br />
<p>
Digia, Qt and their respective logos are trademarks of Digia Plc
in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. <a title="Privacy Policy"
href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
</div>
<script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>
| sicily/qt4.8.4 | doc/html/qml-integration.html | HTML | lgpl-2.1 | 16,643 | [
30522,
1026,
1029,
20950,
2544,
1027,
1000,
1015,
1012,
1014,
1000,
17181,
1027,
1000,
21183,
2546,
1011,
1022,
1000,
1029,
1028,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
1060,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Copyright 2021 The Pigweed 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
//
// https://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.
#pragma once
#include "pw_assert/check.h"
// Optional short CHECK name definitions
// clang-format off
// Checks that always run even in production.
#define CRASH PW_CRASH
#define CHECK PW_CHECK
#define CHECK_PTR_LE PW_CHECK_PTR_LE
#define CHECK_PTR_LT PW_CHECK_PTR_LT
#define CHECK_PTR_GE PW_CHECK_PTR_GE
#define CHECK_PTR_GT PW_CHECK_PTR_GT
#define CHECK_PTR_EQ PW_CHECK_PTR_EQ
#define CHECK_PTR_NE PW_CHECK_PTR_NE
#define CHECK_NOTNULL PW_CHECK_NOTNULL
#define CHECK_INT_LE PW_CHECK_INT_LE
#define CHECK_INT_LT PW_CHECK_INT_LT
#define CHECK_INT_GE PW_CHECK_INT_GE
#define CHECK_INT_GT PW_CHECK_INT_GT
#define CHECK_INT_EQ PW_CHECK_INT_EQ
#define CHECK_INT_NE PW_CHECK_INT_NE
#define CHECK_UINT_LE PW_CHECK_UINT_LE
#define CHECK_UINT_LT PW_CHECK_UINT_LT
#define CHECK_UINT_GE PW_CHECK_UINT_GE
#define CHECK_UINT_GT PW_CHECK_UINT_GT
#define CHECK_UINT_EQ PW_CHECK_UINT_EQ
#define CHECK_UINT_NE PW_CHECK_UINT_NE
#define CHECK_FLOAT_NEAR PW_CHECK_FLOAT_NEAR
#define CHECK_FLOAT_EXACT_LE PW_CHECK_FLOAT_EXACT_LE
#define CHECK_FLOAT_EXACT_LT PW_CHECK_FLOAT_EXACT_LT
#define CHECK_FLOAT_EXACT_GE PW_CHECK_FLOAT_EXACT_GE
#define CHECK_FLOAT_EXACT_GT PW_CHECK_FLOAT_EXACT_GT
#define CHECK_FLOAT_EXACT_EQ PW_CHECK_FLOAT_EXACT_EQ
#define CHECK_FLOAT_EXACT_NE PW_CHECK_FLOAT_EXACT_NE
#define CHECK_OK PW_CHECK_OK
// Checks that are disabled if NDEBUG is not defined.
#define DCHECK PW_DCHECK
#define DCHECK_PTR_LE PW_DCHECK_PTR_LE
#define DCHECK_PTR_LT PW_DCHECK_PTR_LT
#define DCHECK_PTR_GE PW_DCHECK_PTR_GE
#define DCHECK_PTR_GT PW_DCHECK_PTR_GT
#define DCHECK_PTR_EQ PW_DCHECK_PTR_EQ
#define DCHECK_PTR_NE PW_DCHECK_PTR_NE
#define DCHECK_NOTNULL PW_DCHECK_NOTNULL
#define DCHECK_INT_LE PW_DCHECK_INT_LE
#define DCHECK_INT_LT PW_DCHECK_INT_LT
#define DCHECK_INT_GE PW_DCHECK_INT_GE
#define DCHECK_INT_GT PW_DCHECK_INT_GT
#define DCHECK_INT_EQ PW_DCHECK_INT_EQ
#define DCHECK_INT_NE PW_DCHECK_INT_NE
#define DCHECK_UINT_LE PW_DCHECK_UINT_LE
#define DCHECK_UINT_LT PW_DCHECK_UINT_LT
#define DCHECK_UINT_GE PW_DCHECK_UINT_GE
#define DCHECK_UINT_GT PW_DCHECK_UINT_GT
#define DCHECK_UINT_EQ PW_DCHECK_UINT_EQ
#define DCHECK_UINT_NE PW_DCHECK_UINT_NE
#define DCHECK_FLOAT_NEAR PW_DCHECK_FLOAT_NEAR
#define DCHECK_FLOAT_EXACT_LT PW_DCHECK_FLOAT_EXACT_LT
#define DCHECK_FLOAT_EXACT_LE PW_DCHECK_FLOAT_EXACT_LE
#define DCHECK_FLOAT_EXACT_GT PW_DCHECK_FLOAT_EXACT_GT
#define DCHECK_FLOAT_EXACT_GE PW_DCHECK_FLOAT_EXACT_GE
#define DCHECK_FLOAT_EXACT_EQ PW_DCHECK_FLOAT_EXACT_EQ
#define DCHECK_FLOAT_EXACT_NE PW_DCHECK_FLOAT_EXACT_NE
#define DCHECK_OK PW_DCHECK_OK
// clang-format on
| google/pigweed | pw_assert/public/pw_assert/short.h | C | apache-2.0 | 3,562 | [
30522,
1013,
1013,
9385,
25682,
1996,
10369,
18041,
6048,
1013,
1013,
1013,
1013,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
2017,
2089,
2025,
1013,
1013,
2224,
2023,
5371,
3272,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
var elt;
var canvas;
var gl;
var program;
var NumVertices = 36;
var pointsArray = [];
var normalsArray = [];
var colorsArray = [];
var framebuffer;
var flag = true;
var color = new Uint8Array(4);
var vertices = [
vec4( -0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, -0.5, -0.5, 1.0 ),
vec4( -0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, -0.5, -0.5, 1.0 ),
];
var vertexColors = [
vec4( 0.0, 0.0, 0.0, 1.0 ), // black
vec4( 1.0, 0.0, 0.0, 1.0 ), // red
vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow
vec4( 0.0, 1.0, 0.0, 1.0 ), // green
vec4( 0.0, 0.0, 1.0, 1.0 ), // blue
vec4( 1.0, 0.0, 1.0, 1.0 ), // magenta
vec4( 0.0, 1.0, 1.0, 1.0 ), // cyan
vec4( 1.0, 1.0, 1.0, 1.0 ), // white
];
var lightPosition = vec4(1.0, 1.0, 1.0, 0.0 );
var lightAmbient = vec4(0.2, 0.2, 0.2, 1.0 );
var lightDiffuse = vec4( 1.0, 1.0, 1.0, 1.0 );
var lightSpecular = vec4( 1.0, 1.0, 1.0, 1.0 );
//var materialAmbient = vec4( 1.0, 0.0, 1.0, 1.0 );
var materialAmbient = vec4( 1.0, 1.0, 1.0, 1.0 );
//var materialDiffuse = vec4( 1.0, 0.8, 0.0, 1.0);
var materialDiffuse = vec4( 0.5, 0.5, 0.5, 1.0);
var materialSpecular = vec4( 1.0, 0.8, 0.0, 1.0 );
var materialShininess = 10.0;
var ctm;
var ambientColor, diffuseColor, specularColor;
var modelView, projection;
var viewerPos;
var program;
var xAxis = 0;
var yAxis = 1;
var zAxis = 2;
var axis = xAxis;
var theta = [45.0, 45.0, 45.0];
var thetaLoc;
var Index = 0;
function quad(a, b, c, d) {
var t1 = subtract(vertices[b], vertices[a]);
var t2 = subtract(vertices[c], vertices[b]);
var normal = cross(t1, t2);
var normal = vec3(normal);
normal = normalize(normal);
pointsArray.push(vertices[a]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[b]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[c]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[a]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[c]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[d]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
}
function colorCube()
{
quad( 1, 0, 3, 2 );
quad( 2, 3, 7, 6 );
quad( 3, 0, 4, 7 );
quad( 6, 5, 1, 2 );
quad( 4, 5, 6, 7 );
quad( 5, 4, 0, 1 );
}
window.onload = function init() {
canvas = document.getElementById( "gl-canvas" );
var ctx = canvas.getContext("experimental-webgl", {preserveDrawingBuffer: true});
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
elt = document.getElementById("test");
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 0.5, 0.5, 0.5, 1.0 );
gl.enable(gl.CULL_FACE);
var texture = gl.createTexture();
gl.bindTexture( gl.TEXTURE_2D, texture );
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 512, 512, 0,
gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.generateMipmap(gl.TEXTURE_2D);
// Allocate a frame buffer object
framebuffer = gl.createFramebuffer();
gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer);
// Attach color buffer
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
// check for completeness
//var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
//if(status != gl.FRAMEBUFFER_COMPLETE) alert('Frame Buffer Not Complete');
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
//
// Load shaders and initialize attribute buffers
//
program = initShaders( gl, "vertex-shader", "fragment-shader" );
gl.useProgram( program );
colorCube();
var cBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(colorsArray), gl.STATIC_DRAW );
var vColor = gl.getAttribLocation( program, "vColor" );
gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vColor );
var nBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, nBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(normalsArray), gl.STATIC_DRAW );
var vNormal = gl.getAttribLocation( program, "vNormal" );
gl.vertexAttribPointer( vNormal, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vNormal );
var vBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(pointsArray), gl.STATIC_DRAW );
var vPosition = gl.getAttribLocation(program, "vPosition");
gl.vertexAttribPointer(vPosition, 4, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vPosition);
thetaLoc = gl.getUniformLocation(program, "theta");
viewerPos = vec3(0.0, 0.0, -20.0 );
projection = ortho(-1, 1, -1, 1, -100, 100);
ambientProduct = mult(lightAmbient, materialAmbient);
diffuseProduct = mult(lightDiffuse, materialDiffuse);
specularProduct = mult(lightSpecular, materialSpecular);
document.getElementById("ButtonX").onclick = function(){axis = xAxis;};
document.getElementById("ButtonY").onclick = function(){axis = yAxis;};
document.getElementById("ButtonZ").onclick = function(){axis = zAxis;};
document.getElementById("ButtonT").onclick = function(){flag = !flag};
gl.uniform4fv(gl.getUniformLocation(program, "ambientProduct"),
flatten(ambientProduct));
gl.uniform4fv(gl.getUniformLocation(program, "diffuseProduct"),
flatten(diffuseProduct) );
gl.uniform4fv(gl.getUniformLocation(program, "specularProduct"),
flatten(specularProduct) );
gl.uniform4fv(gl.getUniformLocation(program, "lightPosition"),
flatten(lightPosition) );
gl.uniform1f(gl.getUniformLocation(program,
"shininess"),materialShininess);
gl.uniformMatrix4fv( gl.getUniformLocation(program, "projectionMatrix"),
false, flatten(projection));
canvas.addEventListener("mousedown", function(event){
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
gl.clear( gl.COLOR_BUFFER_BIT);
gl.uniform3fv(thetaLoc, theta);
for(var i=0; i<6; i++) {
gl.uniform1i(gl.getUniformLocation(program, "i"), i+1);
gl.drawArrays( gl.TRIANGLES, 6*i, 6 );
}
var x = event.clientX;
var y = canvas.height -event.clientY;
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, color);
if(color[0]==255)
if(color[1]==255) elt.innerHTML = "<div> cyan </div>";
else if(color[2]==255) elt.innerHTML = "<div> magenta </div>";
else elt.innerHTML = "<div> red </div>";
else if(color[1]==255)
if(color[2]==255) elt.innerHTML = "<div> blue </div>";
else elt.innerHTML = "<div> yellow </div>";
else if(color[2]==255) elt.innerHTML = "<div> green </div>";
else elt.innerHTML = "<div> background </div>";
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.uniform1i(gl.getUniformLocation(program, "i"), 0);
gl.clear( gl.COLOR_BUFFER_BIT );
gl.uniform3fv(thetaLoc, theta);
gl.drawArrays(gl.TRIANGLES, 0, 36);
});
render();
}
var render = function(){
gl.clear( gl.COLOR_BUFFER_BIT );
if(flag) theta[axis] += 2.0;
modelView = mat4();
modelView = mult(modelView, rotate(theta[xAxis], [1, 0, 0] ));
modelView = mult(modelView, rotate(theta[yAxis], [0, 1, 0] ));
modelView = mult(modelView, rotate(theta[zAxis], [0, 0, 1] ));
gl.uniformMatrix4fv( gl.getUniformLocation(program,
"modelViewMatrix"), false, flatten(modelView) );
gl.uniform1i(gl.getUniformLocation(program, "i"),0);
gl.drawArrays( gl.TRIANGLES, 0, 36 );
requestAnimFrame(render);
}
| llucbrell/WebGL | Chap7/pickCube3.js | JavaScript | mit | 8,258 | [
30522,
13075,
3449,
2102,
1025,
13075,
10683,
1025,
13075,
1043,
2140,
1025,
13075,
2565,
1025,
13075,
16371,
2213,
16874,
23522,
1027,
4029,
1025,
13075,
2685,
2906,
9447,
1027,
1031,
1033,
1025,
13075,
3671,
10286,
9447,
1027,
1031,
1033,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (https://www.boxbilling.org)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
namespace Box\Mod\Kb;
class Service
{
protected $di;
/**
* @param mixed $di
*/
public function setDi($di)
{
$this->di = $di;
}
public function searchArticles($status = null, $search = null, $cat = null, $per_page = 100, $page = null)
{
$filter = array();
$sql = "
SELECT *
FROM kb_article
WHERE 1
";
if ($cat) {
$sql .= " AND kb_article_category_id = :cid";
$filter[':cid'] = $cat;
}
if ($status) {
$sql .= " AND status = :status";
$filter[':status'] = $status;
}
if ($search) {
$sql .= " AND title LIKE :q OR content LIKE :q";
$filter[':q'] = "%$search%";
}
$sql .= " ORDER BY kb_article_category_id DESC, views DESC";
return $this->di['pager']->getSimpleResultSet($sql, $filter, $per_page, $page);
}
public function findActiveArticleById($id)
{
$bindings = array(
':id' => $id,
':status' => \Model_KbArticle::ACTIVE
);
return $this->di['db']->findOne('KbArticle', 'id = :id AND status=:status', $bindings);
}
public function findActiveArticleBySlug($slug)
{
$bindings = array(
':slug' => $slug,
':status' => \Model_KbArticle::ACTIVE
);
return $this->di['db']->findOne('KbArticle', 'slug = :slug AND status=:status', $bindings);
}
public function findActive()
{
return $this->di['db']->find('KbArticle', 'status=:status', array(':status' => \Model_KbArticle::ACTIVE));
}
public function hitView(\Model_KbArticle $model)
{
$model->views++;
$this->di['db']->store($model);
}
public function rm(\Model_KbArticle $model)
{
$id = $model->id;
$this->di['db']->trash($model);
$this->di['logger']->info('Deleted knowledge base article #%s', $id);
}
public function toApiArray(\Model_KbArticle $model, $deep = false, $identity = null)
{
$data = array(
'id' => $model->id,
'slug' => $model->slug,
'title' => $model->title,
'views' => $model->views,
'created_at' => $model->created_at,
'status' => $model->status,
'updated_at' => $model->updated_at,
);
$cat = $this->di['db']->getExistingModelById('KbArticleCategory', $model->kb_article_category_id, 'Knowledge Base category not found');
$data['category'] = array(
'id' => $cat->id,
'slug' => $cat->slug,
'title' => $cat->title,
);
if ($deep) {
$data['content'] = $model->content;
}
if ($identity instanceof \Model_Admin) {
$data['status'] = $model->status;
$data['kb_article_category_id'] = $model->kb_article_category_id;
}
return $data;
}
public function createArticle($articleCategoryId, $title, $status = null, $content = null)
{
if(!isset($status)){
$status = \Model_KbArticle::DRAFT;
}
$model = $this->di['db']->dispense('KbArticle');
$model->kb_article_category_id = $articleCategoryId;
$model->title = $title;
$model->slug = $this->di['tools']->slug($title);
$model->status = $status;
$model->content = $content;
$model->updated_at = date('Y-m-d H:i:s');
$model->created_at = date('Y-m-d H:i:s');
$id = $this->di['db']->store($model);
$this->di['logger']->info('Created new knowledge base article #%s', $id);
return $id;
}
public function updateArticle($id, $articleCategoryId = null, $title = null, $slug = null, $status = null, $content = null, $views = null)
{
$model = $this->di['db']->findOne('KbArticle', 'id = ?', array($id));
if (!$model instanceof \Model_KbArticle) {
throw new \Box_Exception('Article not found');
}
if (isset($articleCategoryId)) {
$model->kb_article_category_id = $articleCategoryId;
}
if (isset($title)) {
$model->title = $title;
}
if (isset($slug)) {
$model->slug = $slug;
}
if (isset($status)) {
$model->status = $status;
}
if (isset($content)) {
$model->content = $content;
}
if (isset($views)) {
$model->views = $views;
}
$model->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($model);
$this->di['logger']->info('Updated knowledge base article #%s', $id);
return true;
}
public function categoryGetSearchQuery($data)
{
$sql = "
SELECT kac.*
FROM kb_article_category kac
LEFT JOIN kb_article ka ON kac.id = ka.kb_article_category_id";
$article_status = $this->di['array_get']($data, 'article_status', NULL);
$query = $this->di['array_get']($data, 'q', NULL);
$where = array();
$bindings = array();
if ($article_status) {
$where[] = "ka.status = :status";
$bindings[':status'] = $article_status;
}
if ($query) {
$where[] = "(ka.title LIKE :title OR ka.content LIKE :content)";
$bindings[':title'] = "%$query%";
$bindings[':content'] = "%$query%";
}
if (!empty($where)) {
$sql = $sql . ' WHERE ' . implode(' AND ', $where);
}
$sql = $sql . " GROUP BY kac.id ORDER BY kac.id DESC";
return array($sql, $bindings);
}
public function categoryFindAll()
{
$sql = "SELECT kac.*, a.*
FROM kb_article_category kac
LEFT JOIN kb_article ka
ON kac.id = ka.kb_article_category_id
";
return $this->di['db']->getAll($sql);
}
public function categoryGetPairs()
{
$sql = "SELECT id, title FROM kb_article_category";
$pairs = $this->di['db']->getAssoc($sql);
return $pairs;
}
public function categoryRm(\Model_KbArticleCategory $model)
{
$bindings = array(
':kb_article_category_id' => $model->id
);
$articlesCount = $this->di['db']->getCell("SELECT count(*) as cnt FROM kb_article WHERE kb_article_category_id = :kb_article_category_id", $bindings);
if ($articlesCount > 0) {
throw new \Box_Exception('Can not remove category which has articles');
}
$id = $model->id;
$this->di['db']->trash($model);
$this->di['logger']->info('Deleted knowledge base category #%s', $id);
return true;
}
public function categoryToApiArray(\Model_KbArticleCategory $model, $identity = null, $query = null)
{
$data = $this->di['db']->toArray($model);
$sql = "kb_article_category_id = :category_id";
$bindings = array(
':category_id' => $model->id
);
if (!$identity instanceof \Model_Admin){
$sql .= " AND status = 'active'";
}
if ($query){
$sql .= "AND (title LIKE :title OR content LIKE :content)";
$query = "%$query%";
$bindings[':content'] = $query;
$bindings[':title'] = $query;
}
$articles = $this->di['db']->find('KbArticle', $sql, $bindings);
foreach ($articles as $article) {
$data['articles'][] = $this->toApiArray($article, false, $identity);
}
return $data;
}
public function createCategory($title, $description = null)
{
$systemService = $this->di['mod_service']('system');
$systemService->checkLimits('Model_KbArticleCategory', 2);
$model = $this->di['db']->dispense('KbArticleCategory');
$model->title = $title;
$model->description = $description;
$model->slug = $this->di['tools']->slug($title);
$model->updated_at = date('Y-m-d H:i:s');
$model->created_at = date('Y-m-d H:i:s');
$id = $this->di['db']->store($model);
$this->di['logger']->info('Created new knowledge base category #%s', $id);
return $id;
}
public function updateCategory(\Model_KbArticleCategory $model, $title = null, $slug = null, $description = null)
{
if (isset($title)) {
$model->title = $title;
}
if (isset($slug)) {
$model->slug = $slug;
}
if (isset($description)) {
$model->description = $description;
}
$model->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($model);
$this->di['logger']->info('Updated knowledge base category #%s', $model->id);
return true;
}
public function findCategoryById($id)
{
return $this->di['db']->getExistingModelById('KbArticleCategory', $id, 'Knowledge base category not found');
}
public function findCategoryBySlug($slug)
{
$bindings = array(
':slug' => $slug,
);
return $this->di['db']->findOne('KbArticleCategory', 'slug = :slug', $bindings);
}
} | boxbilling/boxbilling | src/bb-modules/Kb/Service.php | PHP | apache-2.0 | 9,832 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
3482,
24457,
2075,
1008,
1008,
1030,
9385,
3482,
24457,
2075,
1010,
4297,
1006,
16770,
1024,
1013,
1013,
7479,
1012,
3482,
24457,
2075,
1012,
8917,
1007,
1008,
1030,
6105,
15895,
1011,
1016,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using MicroOrm.Dapper.Repositories.Extensions;
namespace MicroOrm.Dapper.Repositories
{
/// <summary>
/// Base Repository
/// </summary>
public partial class DapperRepository<TEntity>
where TEntity : class
{
/// <inheritdoc />
public bool BulkUpdate(IEnumerable<TEntity> instances)
{
return BulkUpdate(instances, null);
}
/// <inheritdoc />
public bool BulkUpdate(IEnumerable<TEntity> instances, IDbTransaction transaction)
{
var queryResult = SqlGenerator.GetBulkUpdate(instances);
var result = TransientDapperExtentions.ExecuteWithRetry(() => Connection.Execute(queryResult.GetSql(), queryResult.Param, transaction)) > 0;
return result;
}
/// <inheritdoc />
public Task<bool> BulkUpdateAsync(IEnumerable<TEntity> instances)
{
return BulkUpdateAsync(instances, null);
}
/// <inheritdoc />
public async Task<bool> BulkUpdateAsync(IEnumerable<TEntity> instances, IDbTransaction transaction)
{
var queryResult = SqlGenerator.GetBulkUpdate(instances);
var result = (await TransientDapperExtentions.ExecuteWithRetryAsync(() => Connection.ExecuteAsync(queryResult.GetSql(), queryResult.Param, transaction))) > 0;
return result;
}
}
} | digitalmedia34/MicroOrm.Dapper.Repositories | src/MicroOrm.Dapper.Repositories/DapperRepository.BulkUpdate.cs | C# | mit | 1,489 | [
30522,
2478,
2291,
1012,
6407,
1012,
12391,
1025,
2478,
2291,
1012,
2951,
1025,
2478,
2291,
1012,
11689,
2075,
1012,
8518,
1025,
2478,
4830,
18620,
1025,
2478,
12702,
2953,
2213,
1012,
4830,
18620,
1012,
16360,
20049,
29469,
2229,
1012,
143... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
from Tools.Profile import profile
profile("LOAD:ElementTree")
import xml.etree.cElementTree
import os
profile("LOAD:enigma_skin")
from enigma import eSize, ePoint, eRect, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, addFont, gRGB, eWindowStyleSkinned, getDesktop
from Components.config import ConfigSubsection, ConfigText, config
from Components.Converter.Converter import Converter
from Components.Sources.Source import Source, ObsoleteSource
from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_FONTS, SCOPE_CURRENT_SKIN, SCOPE_CONFIG, fileExists, SCOPE_SKIN_IMAGE
from Tools.Import import my_import
from Tools.LoadPixmap import LoadPixmap
from Components.RcModel import rc_model
from Components.SystemInfo import SystemInfo
colorNames = {}
# Predefined fonts, typically used in built-in screens and for components like
# the movie list and so.
fonts = {
"Body": ("Regular", 18, 22, 16),
"ChoiceList": ("Regular", 20, 24, 18),
}
parameters = {}
def dump(x, i=0):
print " " * i + str(x)
try:
for n in x.childNodes:
dump(n, i + 1)
except:
None
class SkinError(Exception):
def __init__(self, message):
self.msg = message
def __str__(self):
return "{%s}: %s. Please contact the skin's author!" % (config.skin.primary_skin.value, self.msg)
dom_skins = [ ]
def addSkin(name, scope = SCOPE_SKIN):
# read the skin
filename = resolveFilename(scope, name)
if fileExists(filename):
mpath = os.path.dirname(filename) + "/"
try:
dom_skins.append((mpath, xml.etree.cElementTree.parse(filename).getroot()))
except:
print "[SKIN ERROR] error in %s" % filename
return False
else:
return True
return False
# get own skin_user_skinname.xml file, if exist
def skin_user_skinname():
name = "skin_user_" + config.skin.primary_skin.value[:config.skin.primary_skin.value.rfind('/')] + ".xml"
filename = resolveFilename(SCOPE_CONFIG, name)
if fileExists(filename):
return name
return None
# we do our best to always select the "right" value
# skins are loaded in order of priority: skin with
# highest priority is loaded last, usually the user-provided
# skin.
# currently, loadSingleSkinData (colors, bordersets etc.)
# are applied one-after-each, in order of ascending priority.
# the dom_skin will keep all screens in descending priority,
# so the first screen found will be used.
# example: loadSkin("nemesis_greenline/skin.xml")
config.skin = ConfigSubsection()
DEFAULT_SKIN = SystemInfo["HasFullHDSkinSupport"] and "PLi-FullNightHD/skin.xml" or "PLi-HD/skin.xml"
# on SD hardware, PLi-HD will not be available
if not fileExists(resolveFilename(SCOPE_SKIN, DEFAULT_SKIN)):
# in that case, fallback to Magic (which is an SD skin)
DEFAULT_SKIN = "Magic/skin.xml"
if not fileExists(resolveFilename(SCOPE_SKIN, DEFAULT_SKIN)):
DEFAULT_SKIN = "skin.xml"
config.skin.primary_skin = ConfigText(default=DEFAULT_SKIN)
profile("LoadSkin")
res = None
name = skin_user_skinname()
if name:
res = addSkin(name, SCOPE_CONFIG)
if not name or not res:
addSkin('skin_user.xml', SCOPE_CONFIG)
# some boxes lie about their dimensions
addSkin('skin_box.xml')
# add optional discrete second infobar
addSkin('skin_second_infobar.xml')
display_skin_id = 1
addSkin('skin_display.xml')
addSkin('skin_text.xml')
addSkin('skin_subtitles.xml')
try:
if not addSkin(config.skin.primary_skin.value):
raise SkinError, "primary skin not found"
except Exception, err:
print "SKIN ERROR:", err
skin = DEFAULT_SKIN
if config.skin.primary_skin.value == skin:
skin = 'skin.xml'
print "defaulting to standard skin...", skin
config.skin.primary_skin.value = skin
addSkin(skin)
del skin
addSkin('skin_default.xml')
profile("LoadSkinDefaultDone")
#
# Convert a string into a number. Used to convert object position and size attributes into a number
# s is the input string.
# e is the the parent object size to do relative calculations on parent
# size is the size of the object size (e.g. width or height)
# font is a font object to calculate relative to font sizes
# Note some constructs for speeding # up simple cases that are very common.
# Can do things like: 10+center-10w+4%
# To center the widget on the parent widget,
# but move forward 10 pixels and 4% of parent width
# and 10 character widths backward
# Multiplication, division and subexprsssions are also allowed: 3*(e-c/2)
#
# Usage: center : center the object on parent based on parent size and object size
# e : take the parent size/width
# c : take the center point of parent size/width
# % : take given percentag of parent size/width
# w : multiply by current font width
# h : multiply by current font height
#
def parseCoordinate(s, e, size=0, font=None):
s = s.strip()
if s == "center": # for speed, can be common case
val = (e - size)/2
elif s == '*':
return None
else:
try:
val = int(s) # for speed
except:
if 't' in s:
s = s.replace("center", str((e-size)/2.0))
if 'e' in s:
s = s.replace("e", str(e))
if 'c' in s:
s = s.replace("c", str(e/2.0))
if 'w' in s:
s = s.replace("w", "*" + str(fonts[font][3]))
if 'h' in s:
s = s.replace("h", "*" + str(fonts[font][2]))
if '%' in s:
s = s.replace("%", "*" + str(e/100.0))
try:
val = int(s) # for speed
except:
val = eval(s)
if val < 0:
return 0
return int(val) # make sure an integer value is returned
def getParentSize(object, desktop):
size = eSize()
if object:
parent = object.getParent()
# For some widgets (e.g. ScrollLabel) the skin attributes are applied to
# a child widget, instead of to the widget itself. In that case, the parent
# we have here is not the real parent, but it is the main widget.
# We have to go one level higher to get the actual parent.
# We can detect this because the 'parent' will not have a size yet
# (the main widget's size will be calculated internally, as soon as the child
# widget has parsed the skin attributes)
if parent and parent.size().isEmpty():
parent = parent.getParent()
if parent:
size = parent.size()
elif desktop:
#widget has no parent, use desktop size instead for relative coordinates
size = desktop.size()
return size
def parseValuePair(s, scale, object = None, desktop = None, size = None):
x, y = s.split(',')
parentsize = eSize()
if object and ('c' in x or 'c' in y or 'e' in x or 'e' in y or
'%' in x or '%' in y): # need parent size for ce%
parentsize = getParentSize(object, desktop)
xval = parseCoordinate(x, parentsize.width(), size and size.width() or 0)
yval = parseCoordinate(y, parentsize.height(), size and size.height() or 0)
return (xval * scale[0][0] / scale[0][1], yval * scale[1][0] / scale[1][1])
def parsePosition(s, scale, object = None, desktop = None, size = None):
(x, y) = parseValuePair(s, scale, object, desktop, size)
return ePoint(x, y)
def parseSize(s, scale, object = None, desktop = None):
(x, y) = parseValuePair(s, scale, object, desktop)
return eSize(x, y)
def parseFont(s, scale):
try:
f = fonts[s]
name = f[0]
size = f[1]
except:
name, size = s.split(';')
return gFont(name, int(size) * scale[0][0] / scale[0][1])
def parseColor(s):
if s[0] != '#':
try:
return colorNames[s]
except:
raise SkinError("color '%s' must be #aarrggbb or valid named color" % s)
return gRGB(int(s[1:], 0x10))
def collectAttributes(skinAttributes, node, context, skin_path_prefix=None, ignore=(), filenames=frozenset(("pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap", "sliderPixmap", "scrollbarbackgroundPixmap"))):
# walk all attributes
size = None
pos = None
font = None
for attrib, value in node.items():
if attrib not in ignore:
if attrib in filenames:
value = resolveFilename(SCOPE_CURRENT_SKIN, value, path_prefix=skin_path_prefix)
# Bit of a hack this, really. When a window has a flag (e.g. wfNoBorder)
# it needs to be set at least before the size is set, in order for the
# window dimensions to be calculated correctly in all situations.
# If wfNoBorder is applied after the size has been set, the window will fail to clear the title area.
# Similar situation for a scrollbar in a listbox; when the scrollbar setting is applied after
# the size, a scrollbar will not be shown until the selection moves for the first time
if attrib == 'size':
size = value.encode("utf-8")
elif attrib == 'position':
pos = value.encode("utf-8")
elif attrib == 'font':
font = value.encode("utf-8")
skinAttributes.append((attrib, font))
else:
skinAttributes.append((attrib, value.encode("utf-8")))
if pos is not None:
pos, size = context.parse(pos, size, font)
skinAttributes.append(('position', pos))
if size is not None:
skinAttributes.append(('size', size))
def morphRcImagePath(value):
if rc_model.rcIsDefault() is False:
if value == '/usr/share/enigma2/skin_default/rc.png' or value == '/usr/share/enigma2/skin_default/rcold.png':
value = rc_model.getRcImg()
return value
def loadPixmap(path, desktop):
option = path.find("#")
if option != -1:
path = path[:option]
ptr = LoadPixmap(morphRcImagePath(path), desktop)
if ptr is None:
raise SkinError("pixmap file %s not found!" % path)
return ptr
class AttributeParser:
def __init__(self, guiObject, desktop, scale=((1,1),(1,1))):
self.guiObject = guiObject
self.desktop = desktop
self.scaleTuple = scale
def applyOne(self, attrib, value):
try:
getattr(self, attrib)(value)
except AttributeError:
print "[Skin] Attribute not implemented:", attrib, "value:", value
except SkinError, ex:
print "[Skin] Error:", ex
def applyAll(self, attrs):
for attrib, value in attrs:
self.applyOne(attrib, value)
def conditional(self, value):
pass
def position(self, value):
if isinstance(value, tuple):
self.guiObject.move(ePoint(*value))
else:
self.guiObject.move(parsePosition(value, self.scaleTuple, self.guiObject, self.desktop, self.guiObject.csize()))
def size(self, value):
if isinstance(value, tuple):
self.guiObject.resize(eSize(*value))
else:
self.guiObject.resize(parseSize(value, self.scaleTuple, self.guiObject, self.desktop))
def title(self, value):
self.guiObject.setTitle(_(value))
def text(self, value):
self.guiObject.setText(_(value))
def font(self, value):
self.guiObject.setFont(parseFont(value, self.scaleTuple))
def zPosition(self, value):
self.guiObject.setZPosition(int(value))
def itemHeight(self, value):
self.guiObject.setItemHeight(int(value))
def pixmap(self, value):
ptr = loadPixmap(value, self.desktop)
self.guiObject.setPixmap(ptr)
def backgroundPixmap(self, value):
ptr = loadPixmap(value, self.desktop)
self.guiObject.setBackgroundPicture(ptr)
def selectionPixmap(self, value):
ptr = loadPixmap(value, self.desktop)
self.guiObject.setSelectionPicture(ptr)
def sliderPixmap(self, value):
ptr = loadPixmap(value, self.desktop)
self.guiObject.setSliderPicture(ptr)
def scrollbarbackgroundPixmap(self, value):
ptr = loadPixmap(value, self.desktop)
self.guiObject.setScrollbarBackgroundPicture(ptr)
def alphatest(self, value):
self.guiObject.setAlphatest(
{ "on": 1,
"off": 0,
"blend": 2,
}[value])
def scale(self, value):
self.guiObject.setScale(1)
def orientation(self, value): # used by eSlider
try:
self.guiObject.setOrientation(*
{ "orVertical": (self.guiObject.orVertical, False),
"orTopToBottom": (self.guiObject.orVertical, False),
"orBottomToTop": (self.guiObject.orVertical, True),
"orHorizontal": (self.guiObject.orHorizontal, False),
"orLeftToRight": (self.guiObject.orHorizontal, False),
"orRightToLeft": (self.guiObject.orHorizontal, True),
}[value])
except KeyError:
print "oprientation must be either orVertical or orHorizontal!"
def valign(self, value):
try:
self.guiObject.setVAlign(
{ "top": self.guiObject.alignTop,
"center": self.guiObject.alignCenter,
"bottom": self.guiObject.alignBottom
}[value])
except KeyError:
print "valign must be either top, center or bottom!"
def halign(self, value):
try:
self.guiObject.setHAlign(
{ "left": self.guiObject.alignLeft,
"center": self.guiObject.alignCenter,
"right": self.guiObject.alignRight,
"block": self.guiObject.alignBlock
}[value])
except KeyError:
print "halign must be either left, center, right or block!"
def textOffset(self, value):
x, y = value.split(',')
self.guiObject.setTextOffset(ePoint(int(x) * self.scaleTuple[0][0] / self.scaleTuple[0][1], int(y) * self.scaleTuple[1][0] / self.scaleTuple[1][1]))
def flags(self, value):
flags = value.split(',')
for f in flags:
try:
fv = eWindow.__dict__[f]
self.guiObject.setFlag(fv)
except KeyError:
print "illegal flag %s!" % f
def backgroundColor(self, value):
self.guiObject.setBackgroundColor(parseColor(value))
def backgroundColorSelected(self, value):
self.guiObject.setBackgroundColorSelected(parseColor(value))
def foregroundColor(self, value):
self.guiObject.setForegroundColor(parseColor(value))
def foregroundColorSelected(self, value):
self.guiObject.setForegroundColorSelected(parseColor(value))
def shadowColor(self, value):
self.guiObject.setShadowColor(parseColor(value))
def selectionDisabled(self, value):
self.guiObject.setSelectionEnable(0)
def transparent(self, value):
self.guiObject.setTransparent(int(value))
def borderColor(self, value):
self.guiObject.setBorderColor(parseColor(value))
def borderWidth(self, value):
self.guiObject.setBorderWidth(int(value))
def scrollbarMode(self, value):
self.guiObject.setScrollbarMode(getattr(self.guiObject, value))
# { "showOnDemand": self.guiObject.showOnDemand,
# "showAlways": self.guiObject.showAlways,
# "showNever": self.guiObject.showNever,
# "showLeft": self.guiObject.showLeft
# }[value])
def enableWrapAround(self, value):
self.guiObject.setWrapAround(True)
def itemHeight(self, value):
self.guiObject.setItemHeight(int(value))
def pointer(self, value):
(name, pos) = value.split(':')
pos = parsePosition(pos, self.scaleTuple)
ptr = loadPixmap(name, self.desktop)
self.guiObject.setPointer(0, ptr, pos)
def seek_pointer(self, value):
(name, pos) = value.split(':')
pos = parsePosition(pos, self.scaleTuple)
ptr = loadPixmap(name, self.desktop)
self.guiObject.setPointer(1, ptr, pos)
def shadowOffset(self, value):
self.guiObject.setShadowOffset(parsePosition(value, self.scaleTuple))
def noWrap(self, value):
self.guiObject.setNoWrap(1)
def applySingleAttribute(guiObject, desktop, attrib, value, scale = ((1,1),(1,1))):
# Someone still using applySingleAttribute?
AttributeParser(guiObject, desktop, scale).applyOne(attrib, value)
def applyAllAttributes(guiObject, desktop, attributes, scale):
AttributeParser(guiObject, desktop, scale).applyAll(attributes)
def loadSingleSkinData(desktop, skin, path_prefix):
"""loads skin data like colors, windowstyle etc."""
assert skin.tag == "skin", "root element in skin must be 'skin'!"
for c in skin.findall("output"):
id = c.attrib.get('id')
if id:
id = int(id)
else:
id = 0
if id == 0: # framebuffer
for res in c.findall("resolution"):
get_attr = res.attrib.get
xres = get_attr("xres")
if xres:
xres = int(xres)
else:
xres = 720
yres = get_attr("yres")
if yres:
yres = int(yres)
else:
yres = 576
bpp = get_attr("bpp")
if bpp:
bpp = int(bpp)
else:
bpp = 32
#print "Resolution:", xres,yres,bpp
from enigma import gMainDC
gMainDC.getInstance().setResolution(xres, yres)
desktop.resize(eSize(xres, yres))
if bpp != 32:
# load palette (not yet implemented)
pass
if yres >= 1080:
parameters["FileListName"] = (68,4,1000,34)
parameters["FileListIcon"] = (7,4,52,37)
parameters["FileListMultiName"] = (90,3,1000,32)
parameters["FileListMultiIcon"] = (45, 4, 30, 30)
parameters["FileListMultiLock"] = (2,0,36,36)
parameters["ChoicelistDash"] = (0,3,1000,30)
parameters["ChoicelistName"] = (68,3,1000,30)
parameters["ChoicelistIcon"] = (7,0,52,38)
parameters["PluginBrowserName"] = (180,8,38)
parameters["PluginBrowserDescr"] = (180,42,25)
parameters["PluginBrowserIcon"] = (15,8,150,60)
parameters["PluginBrowserDownloadName"] = (120,8,38)
parameters["PluginBrowserDownloadDescr"] = (120,42,25)
parameters["PluginBrowserDownloadIcon"] = (15,0,90,76)
parameters["ServiceInfo"] = (0,0,450,50)
parameters["ServiceInfoLeft"] = (0,0,450,45)
parameters["ServiceInfoRight"] = (450,0,1000,45)
parameters["SelectionListDescr"] = (45,3,1000,32)
parameters["SelectionListLock"] = (0,2,36,36)
parameters["ConfigListSeperator"] = 300
parameters["VirtualKeyboard"] = (68,68)
parameters["PartnerBoxEntryListName"] = (8,2,225,38)
parameters["PartnerBoxEntryListIP"] = (180,2,225,38)
parameters["PartnerBoxEntryListPort"] = (405,2,150,38)
parameters["PartnerBoxEntryListType"] = (615,2,150,38)
parameters["PartnerBoxTimerServicename"] = (0,0,45)
parameters["PartnerBoxTimerName"] = (0,42,30)
parameters["PartnerBoxE1TimerTime"] = (0,78,255,30)
parameters["PartnerBoxE1TimerState"] = (255,78,255,30)
parameters["PartnerBoxE2TimerTime"] = (0,78,225,30)
parameters["PartnerBoxE2TimerState"] = (225,78,225,30)
parameters["PartnerBoxE2TimerIcon"] = (1050,8,20,20)
parameters["PartnerBoxE2TimerIconRepeat"] = (1050,38,20,20)
parameters["PartnerBoxBouquetListName"] = (0,0,45)
parameters["PartnerBoxChannelListName"] = (0,0,45)
parameters["PartnerBoxChannelListTitle"] = (0,42,30)
parameters["PartnerBoxChannelListTime"] = (0,78,225,30)
parameters["HelpMenuListHlp"] = (0,0,900,42)
parameters["HelpMenuListExtHlp0"] = (0,0,900,39)
parameters["HelpMenuListExtHlp1"] = (0,42,900,30)
parameters["AboutHddSplit"] = 1
parameters["DreamexplorerName"] = (62,0,1200,38)
parameters["DreamexplorerIcon"] = (15,4,30,30)
parameters["PicturePlayerThumb"] = (30,285,45,300,30,25)
parameters["PlayListName"] = (38,2,1000,34)
parameters["PlayListIcon"] = (7,7,24,24)
parameters["SHOUTcastListItem"] = (30,27,35,96,35,33,60,32)
for skininclude in skin.findall("include"):
filename = skininclude.attrib.get("filename")
if filename:
skinfile = resolveFilename(SCOPE_CURRENT_SKIN, filename, path_prefix=path_prefix)
if not fileExists(skinfile):
skinfile = resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix)
if fileExists(skinfile):
print "[SKIN] loading include:", skinfile
loadSkin(skinfile)
for c in skin.findall("colors"):
for color in c.findall("color"):
get_attr = color.attrib.get
name = get_attr("name")
color = get_attr("value")
if name and color:
colorNames[name] = parseColor(color)
#print "Color:", name, color
else:
raise SkinError("need color and name, got %s %s" % (name, color))
for c in skin.findall("fonts"):
for font in c.findall("font"):
get_attr = font.attrib.get
filename = get_attr("filename", "<NONAME>")
name = get_attr("name", "Regular")
scale = get_attr("scale")
if scale:
scale = int(scale)
else:
scale = 100
is_replacement = get_attr("replacement") and True or False
render = get_attr("render")
if render:
render = int(render)
else:
render = 0
resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
if not fileExists(resolved_font): #when font is not available look at current skin path
skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
if fileExists(skin_path):
resolved_font = skin_path
addFont(resolved_font, name, scale, is_replacement, render)
#print "Font: ", resolved_font, name, scale, is_replacement
for alias in c.findall("alias"):
get = alias.attrib.get
try:
name = get("name")
font = get("font")
size = int(get("size"))
height = int(get("height", size)) # to be calculated some day
width = int(get("width", size))
global fonts
fonts[name] = (font, size, height, width)
except Exception, ex:
print "[SKIN] bad font alias", ex
for c in skin.findall("parameters"):
for parameter in c.findall("parameter"):
get = parameter.attrib.get
try:
name = get("name")
value = get("value")
parameters[name] = "," in value and map(int, value.split(",")) or int(value)
except Exception, ex:
print "[SKIN] bad parameter", ex
for c in skin.findall("subtitles"):
from enigma import eSubtitleWidget
scale = ((1,1),(1,1))
for substyle in c.findall("sub"):
get_attr = substyle.attrib.get
font = parseFont(get_attr("font"), scale)
col = get_attr("foregroundColor")
if col:
foregroundColor = parseColor(col)
haveColor = 1
else:
foregroundColor = gRGB(0xFFFFFF)
haveColor = 0
col = get_attr("borderColor")
if col:
borderColor = parseColor(col)
else:
borderColor = gRGB(0)
borderwidth = get_attr("borderWidth")
if borderwidth is None:
# default: use a subtitle border
borderWidth = 3
else:
borderWidth = int(borderwidth)
face = eSubtitleWidget.__dict__[get_attr("name")]
eSubtitleWidget.setFontStyle(face, font, haveColor, foregroundColor, borderColor, borderWidth)
for windowstyle in skin.findall("windowstyle"):
style = eWindowStyleSkinned()
style_id = windowstyle.attrib.get("id")
if style_id:
style_id = int(style_id)
else:
style_id = 0
# defaults
font = gFont("Regular", 20)
offset = eSize(20, 5)
for title in windowstyle.findall("title"):
get_attr = title.attrib.get
offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
font = parseFont(get_attr("font"), ((1,1),(1,1)))
style.setTitleFont(font);
style.setTitleOffset(offset)
#print " ", font, offset
for borderset in windowstyle.findall("borderset"):
bsName = str(borderset.attrib.get("name"))
for pixmap in borderset.findall("pixmap"):
get_attr = pixmap.attrib.get
bpName = get_attr("pos")
filename = get_attr("filename")
if filename and bpName:
png = loadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, filename, path_prefix=path_prefix), desktop)
style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
#print " borderset:", bpName, filename
for color in windowstyle.findall("color"):
get_attr = color.attrib.get
colorType = get_attr("name")
color = parseColor(get_attr("color"))
try:
style.setColor(eWindowStyleSkinned.__dict__["col" + colorType], color)
except:
raise SkinError("Unknown color %s" % colorType)
#pass
#print " color:", type, color
x = eWindowStyleManager.getInstance()
x.setStyle(style_id, style)
for margin in skin.findall("margin"):
style_id = margin.attrib.get("id")
if style_id:
style_id = int(style_id)
else:
style_id = 0
r = eRect(0,0,0,0)
v = margin.attrib.get("left")
if v:
r.setLeft(int(v))
v = margin.attrib.get("top")
if v:
r.setTop(int(v))
v = margin.attrib.get("right")
if v:
r.setRight(int(v))
v = margin.attrib.get("bottom")
if v:
r.setBottom(int(v))
# the "desktop" parameter is hardcoded to the UI screen, so we must ask
# for the one that this actually applies to.
getDesktop(style_id).setMargins(r)
dom_screens = {}
def loadSkin(name, scope = SCOPE_SKIN):
# Now a utility for plugins to add skin data to the screens
global dom_screens, display_skin_id
filename = resolveFilename(scope, name)
if fileExists(filename):
path = os.path.dirname(filename) + "/"
for elem in xml.etree.cElementTree.parse(filename).getroot():
if elem.tag == 'screen':
name = elem.attrib.get('name', None)
if name:
sid = elem.attrib.get('id', None)
if sid and (sid != display_skin_id):
# not for this display
elem.clear()
continue
if name in dom_screens:
print "loadSkin: Screen already defined elsewhere:", name
elem.clear()
else:
dom_screens[name] = (elem, path)
else:
elem.clear()
else:
elem.clear()
def loadSkinData(desktop):
# Kinda hackish, but this is called once by mytest.py
global dom_skins
skins = dom_skins[:]
skins.reverse()
for (path, dom_skin) in skins:
loadSingleSkinData(desktop, dom_skin, path)
for elem in dom_skin:
if elem.tag == 'screen':
name = elem.attrib.get('name', None)
if name:
sid = elem.attrib.get('id', None)
if sid and (sid != display_skin_id):
# not for this display
elem.clear()
continue
if name in dom_screens:
# Kill old versions, save memory
dom_screens[name][0].clear()
dom_screens[name] = (elem, path)
else:
# without name, it's useless!
elem.clear()
else:
# non-screen element, no need for it any longer
elem.clear()
# no longer needed, we know where the screens are now.
del dom_skins
class additionalWidget:
pass
# Class that makes a tuple look like something else. Some plugins just assume
# that size is a string and try to parse it. This class makes that work.
class SizeTuple(tuple):
def split(self, *args):
return (str(self[0]), str(self[1]))
def strip(self, *args):
return '%s,%s' % self
def __str__(self):
return '%s,%s' % self
class SkinContext:
def __init__(self, parent=None, pos=None, size=None, font=None):
if parent is not None:
if pos is not None:
pos, size = parent.parse(pos, size, font)
self.x, self.y = pos
self.w, self.h = size
else:
self.x = None
self.y = None
self.w = None
self.h = None
def __str__(self):
return "Context (%s,%s)+(%s,%s) " % (self.x, self.y, self.w, self.h)
def parse(self, pos, size, font):
if pos == "fill":
pos = (self.x, self.y)
size = (self.w, self.h)
self.w = 0
self.h = 0
else:
w,h = size.split(',')
w = parseCoordinate(w, self.w, 0, font)
h = parseCoordinate(h, self.h, 0, font)
if pos == "bottom":
pos = (self.x, self.y + self.h - h)
size = (self.w, h)
self.h -= h
elif pos == "top":
pos = (self.x, self.y)
size = (self.w, h)
self.h -= h
self.y += h
elif pos == "left":
pos = (self.x, self.y)
size = (w, self.h)
self.x += w
self.w -= w
elif pos == "right":
pos = (self.x + self.w - w, self.y)
size = (w, self.h)
self.w -= w
else:
size = (w, h)
pos = pos.split(',')
pos = (self.x + parseCoordinate(pos[0], self.w, size[0], font), self.y + parseCoordinate(pos[1], self.h, size[1], font))
return (SizeTuple(pos), SizeTuple(size))
class SkinContextStack(SkinContext):
# A context that stacks things instead of aligning them
def parse(self, pos, size, font):
if pos == "fill":
pos = (self.x, self.y)
size = (self.w, self.h)
else:
w,h = size.split(',')
w = parseCoordinate(w, self.w, 0, font)
h = parseCoordinate(h, self.h, 0, font)
if pos == "bottom":
pos = (self.x, self.y + self.h - h)
size = (self.w, h)
elif pos == "top":
pos = (self.x, self.y)
size = (self.w, h)
elif pos == "left":
pos = (self.x, self.y)
size = (w, self.h)
elif pos == "right":
pos = (self.x + self.w - w, self.y)
size = (w, self.h)
else:
size = (w, h)
pos = pos.split(',')
pos = (self.x + parseCoordinate(pos[0], self.w, size[0], font), self.y + parseCoordinate(pos[1], self.h, size[1], font))
return (SizeTuple(pos), SizeTuple(size))
def readSkin(screen, skin, names, desktop):
if not isinstance(names, list):
names = [names]
# try all skins, first existing one have priority
global dom_screens
for n in names:
myscreen, path = dom_screens.get(n, (None,None))
if myscreen is not None:
# use this name for debug output
name = n
break
else:
name = "<embedded-in-'%s'>" % screen.__class__.__name__
# otherwise try embedded skin
if myscreen is None:
myscreen = getattr(screen, "parsedSkin", None)
# try uncompiled embedded skin
if myscreen is None and getattr(screen, "skin", None):
skin = screen.skin
print "[SKIN] Parsing embedded skin", name
if isinstance(skin, tuple):
for s in skin:
candidate = xml.etree.cElementTree.fromstring(s)
if candidate.tag == 'screen':
sid = candidate.attrib.get('id', None)
if (not sid) or (int(sid) == display_skin_id):
myscreen = candidate
break;
else:
print "[SKIN] Hey, no suitable screen!"
else:
myscreen = xml.etree.cElementTree.fromstring(skin)
if myscreen:
screen.parsedSkin = myscreen
if myscreen is None:
print "[SKIN] No skin to read..."
myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring("<screen></screen>")
screen.skinAttributes = [ ]
skin_path_prefix = getattr(screen, "skin_path", path)
context = SkinContextStack()
s = desktop.bounds()
context.x = s.left()
context.y = s.top()
context.w = s.width()
context.h = s.height()
del s
collectAttributes(screen.skinAttributes, myscreen, context, skin_path_prefix, ignore=("name",))
context = SkinContext(context, myscreen.attrib.get('position'), myscreen.attrib.get('size'))
screen.additionalWidgets = [ ]
screen.renderer = [ ]
visited_components = set()
# now walk all widgets and stuff
def process_none(widget, context):
pass
def process_widget(widget, context):
get_attr = widget.attrib.get
# ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
# widgets (source->renderer).
wname = get_attr('name')
wsource = get_attr('source')
if wname is None and wsource is None:
print "widget has no name and no source!"
return
if wname:
#print "Widget name=", wname
visited_components.add(wname)
# get corresponding 'gui' object
try:
attributes = screen[wname].skinAttributes = [ ]
except:
raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
# assert screen[wname] is not Source
collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('name',))
elif wsource:
# get corresponding source
#print "Widget source=", wsource
while True: # until we found a non-obsolete source
# parse our current "wsource", which might specifiy a "related screen" before the dot,
# for example to reference a parent, global or session-global screen.
scr = screen
# resolve all path components
path = wsource.split('.')
while len(path) > 1:
scr = screen.getRelatedScreen(path[0])
if scr is None:
#print wsource
#print name
raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
path = path[1:]
# resolve the source.
source = scr.get(path[0])
if isinstance(source, ObsoleteSource):
# however, if we found an "obsolete source", issue warning, and resolve the real source.
print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
if source.description:
print source.description
wsource = source.new_source
else:
# otherwise, use that source.
break
if source is None:
raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
wrender = get_attr('render')
if not wrender:
raise SkinError("you must define a renderer with render= for source '%s'" % wsource)
for converter in widget.findall("convert"):
ctype = converter.get('type')
assert ctype, "'convert'-tag needs a 'type'-attribute"
#print "Converter:", ctype
try:
parms = converter.text.strip()
except:
parms = ""
#print "Params:", parms
converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
c = None
for i in source.downstream_elements:
if isinstance(i, converter_class) and i.converter_arguments == parms:
c = i
if c is None:
c = converter_class(parms)
c.connect(source)
source = c
renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender)
renderer = renderer_class() # instantiate renderer
renderer.connect(source) # connect to source
attributes = renderer.skinAttributes = [ ]
collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('render', 'source'))
screen.renderer.append(renderer)
def process_applet(widget, context):
try:
codeText = widget.text.strip()
widgetType = widget.attrib.get('type')
code = compile(codeText, "skin applet", "exec")
except Exception, ex:
raise SkinError("applet failed to compile: " + str(ex))
if widgetType == "onLayoutFinish":
screen.onLayoutFinish.append(code)
else:
raise SkinError("applet type '%s' unknown!" % widgetType)
def process_elabel(widget, context):
w = additionalWidget()
w.widget = eLabel
w.skinAttributes = [ ]
collectAttributes(w.skinAttributes, widget, context, skin_path_prefix, ignore=('name',))
screen.additionalWidgets.append(w)
def process_epixmap(widget, context):
w = additionalWidget()
w.widget = ePixmap
w.skinAttributes = [ ]
collectAttributes(w.skinAttributes, widget, context, skin_path_prefix, ignore=('name',))
screen.additionalWidgets.append(w)
def process_screen(widget, context):
for w in widget.getchildren():
conditional = w.attrib.get('conditional')
if conditional and not [i for i in conditional.split(",") if i in screen.keys()]:
continue
p = processors.get(w.tag, process_none)
try:
p(w, context)
except SkinError, e:
print "[Skin] SKIN ERROR in screen '%s' widget '%s':" % (name, w.tag), e
def process_panel(widget, context):
n = widget.attrib.get('name')
if n:
try:
s = dom_screens[n]
except KeyError:
print "[SKIN] Unable to find screen '%s' referred in screen '%s'" % (n, name)
else:
process_screen(s[0], context)
layout = widget.attrib.get('layout')
if layout == 'stack':
cc = SkinContextStack
else:
cc = SkinContext
try:
c = cc(context, widget.attrib.get('position'), widget.attrib.get('size'), widget.attrib.get('font'))
except Exception, ex:
raise SkinError("Failed to create skincontext (%s,%s,%s) in %s: %s" % (widget.attrib.get('position'), widget.attrib.get('size'), widget.attrib.get('font'), context, ex) )
process_screen(widget, c)
processors = {
None: process_none,
"widget": process_widget,
"applet": process_applet,
"eLabel": process_elabel,
"ePixmap": process_epixmap,
"panel": process_panel
}
try:
context.x = 0 # reset offsets, all components are relative to screen
context.y = 0 # coordinates.
process_screen(myscreen, context)
except Exception, e:
print "[Skin] SKIN ERROR in %s:" % name, e
from Components.GUIComponent import GUIComponent
nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
# This may look pointless, but it unbinds 'screen' from the nested scope. A better
# solution is to avoid the nested scope above and use the context object to pass
# things around.
screen = None
visited_components = None
| isslayne/enigma2 | skin.py | Python | gpl-2.0 | 35,736 | [
30522,
2013,
5906,
1012,
6337,
12324,
6337,
6337,
1006,
1000,
7170,
1024,
5783,
13334,
1000,
1007,
12324,
20950,
1012,
3802,
9910,
1012,
8292,
16930,
4765,
13334,
12324,
9808,
6337,
1006,
1000,
7170,
1024,
26757,
1035,
3096,
1000,
1007,
201... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Generic helpers for smp ipi calls
*
* (C) Jens Axboe <jens.axboe@oracle.com> 2008
*/
#include <linux/rcupdate.h>
#include <linux/rculist.h>
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/percpu.h>
#include <linux/init.h>
#include <linux/gfp.h>
#include <linux/smp.h>
#include <linux/cpu.h>
#ifdef CONFIG_USE_GENERIC_SMP_HELPERS
static struct {
struct list_head queue;
raw_spinlock_t lock;
} call_function __cacheline_aligned_in_smp =
{
.queue = LIST_HEAD_INIT(call_function.queue),
.lock = __RAW_SPIN_LOCK_UNLOCKED(call_function.lock),
};
enum {
CSD_FLAG_LOCK = 0x01,
};
struct call_function_data {
struct call_single_data csd;
atomic_t refs;
cpumask_var_t cpumask;
};
static DEFINE_PER_CPU_SHARED_ALIGNED(struct call_function_data, cfd_data);
struct call_single_queue {
struct list_head list;
raw_spinlock_t lock;
};
static DEFINE_PER_CPU_SHARED_ALIGNED(struct call_single_queue, call_single_queue);
static int
hotplug_cfd(struct notifier_block *nfb, unsigned long action, void *hcpu)
{
long cpu = (long)hcpu;
struct call_function_data *cfd = &per_cpu(cfd_data, cpu);
switch (action) {
case CPU_UP_PREPARE:
case CPU_UP_PREPARE_FROZEN:
if (!zalloc_cpumask_var_node(&cfd->cpumask, GFP_KERNEL,
cpu_to_node(cpu)))
return notifier_from_errno(-ENOMEM);
break;
#ifdef CONFIG_HOTPLUG_CPU
case CPU_UP_CANCELED:
case CPU_UP_CANCELED_FROZEN:
case CPU_DEAD:
case CPU_DEAD_FROZEN:
free_cpumask_var(cfd->cpumask);
break;
#endif
};
return NOTIFY_OK;
}
static struct notifier_block __cpuinitdata hotplug_cfd_notifier = {
.notifier_call = hotplug_cfd,
};
void __init call_function_init(void)
{
void *cpu = (void *)(long)smp_processor_id();
int i;
for_each_possible_cpu(i) {
struct call_single_queue *q = &per_cpu(call_single_queue, i);
raw_spin_lock_init(&q->lock);
INIT_LIST_HEAD(&q->list);
}
hotplug_cfd(&hotplug_cfd_notifier, CPU_UP_PREPARE, cpu);
register_cpu_notifier(&hotplug_cfd_notifier);
}
/*
* csd_lock/csd_unlock used to serialize access to per-cpu csd resources
*
* For non-synchronous ipi calls the csd can still be in use by the
* previous function call. For multi-cpu calls its even more interesting
* as we'll have to ensure no other cpu is observing our csd.
*/
static void csd_lock_wait(struct call_single_data *data)
{
while (data->flags & CSD_FLAG_LOCK)
cpu_relax();
}
static void csd_lock(struct call_single_data *data)
{
csd_lock_wait(data);
data->flags = CSD_FLAG_LOCK;
/*
* prevent CPU from reordering the above assignment
* to ->flags with any subsequent assignments to other
* fields of the specified call_single_data structure:
*/
smp_mb();
}
static void csd_unlock(struct call_single_data *data)
{
WARN_ON(!(data->flags & CSD_FLAG_LOCK));
/*
* ensure we're all done before releasing data:
*/
smp_mb();
data->flags &= ~CSD_FLAG_LOCK;
}
/*
* Insert a previously allocated call_single_data element
* for execution on the given CPU. data must already have
* ->func, ->info, and ->flags set.
*/
static
void generic_exec_single(int cpu, struct call_single_data *data, int wait)
{
struct call_single_queue *dst = &per_cpu(call_single_queue, cpu);
unsigned long flags;
int ipi;
raw_spin_lock_irqsave(&dst->lock, flags);
ipi = list_empty(&dst->list);
list_add_tail(&data->list, &dst->list);
raw_spin_unlock_irqrestore(&dst->lock, flags);
/*
* The list addition should be visible before sending the IPI
* handler locks the list to pull the entry off it because of
* normal cache coherency rules implied by spinlocks.
*
* If IPIs can go out of order to the cache coherency protocol
* in an architecture, sufficient synchronisation should be added
* to arch code to make it appear to obey cache coherency WRT
* locking and barrier primitives. Generic code isn't really
* equipped to do the right thing...
*/
if (ipi)
arch_send_call_function_single_ipi(cpu);
if (wait)
csd_lock_wait(data);
}
/*
* Invoked by arch to handle an IPI for call function. Must be called with
* interrupts disabled.
*/
void generic_smp_call_function_interrupt(void)
{
struct call_function_data *data;
int cpu = smp_processor_id();
/*
* Shouldn't receive this interrupt on a cpu that is not yet online.
*/
WARN_ON_ONCE(!cpu_online(cpu));
/*
* Ensure entry is visible on call_function_queue after we have
* entered the IPI. See comment in smp_call_function_many.
* If we don't have this, then we may miss an entry on the list
* and never get another IPI to process it.
*/
smp_mb();
/*
* It's ok to use list_for_each_rcu() here even though we may
* delete 'pos', since list_del_rcu() doesn't clear ->next
*/
list_for_each_entry_rcu(data, &call_function.queue, csd.list) {
int refs;
smp_call_func_t func;
/*
* Since we walk the list without any locks, we might
* see an entry that was completed, removed from the
* list and is in the process of being reused.
*
* We must check that the cpu is in the cpumask before
* checking the refs, and both must be set before
* executing the callback on this cpu.
*/
if (!cpumask_test_cpu(cpu, data->cpumask))
continue;
smp_rmb();
if (atomic_read(&data->refs) == 0)
continue;
func = data->csd.func; /* save for later warn */
func(data->csd.info);
/*
* If the cpu mask is not still set then func enabled
* interrupts (BUG), and this cpu took another smp call
* function interrupt and executed func(info) twice
* on this cpu. That nested execution decremented refs.
*/
if (!cpumask_test_and_clear_cpu(cpu, data->cpumask)) {
WARN(1, "%pf enabled interrupts and double executed\n", func);
continue;
}
refs = atomic_dec_return(&data->refs);
WARN_ON(refs < 0);
if (refs)
continue;
WARN_ON(!cpumask_empty(data->cpumask));
raw_spin_lock(&call_function.lock);
list_del_rcu(&data->csd.list);
raw_spin_unlock(&call_function.lock);
csd_unlock(&data->csd);
}
}
/*
* Invoked by arch to handle an IPI for call function single. Must be
* called from the arch with interrupts disabled.
*/
void generic_smp_call_function_single_interrupt(void)
{
struct call_single_queue *q = &__get_cpu_var(call_single_queue);
unsigned int data_flags;
LIST_HEAD(list);
/*
* Shouldn't receive this interrupt on a cpu that is not yet online.
*/
WARN_ON_ONCE(!cpu_online(smp_processor_id()));
raw_spin_lock(&q->lock);
list_replace_init(&q->list, &list);
raw_spin_unlock(&q->lock);
while (!list_empty(&list)) {
struct call_single_data *data;
data = list_entry(list.next, struct call_single_data, list);
list_del(&data->list);
/*
* 'data' can be invalid after this call if flags == 0
* (when called through generic_exec_single()),
* so save them away before making the call:
*/
data_flags = data->flags;
data->func(data->info);
/*
* Unlocked CSDs are valid through generic_exec_single():
*/
if (data_flags & CSD_FLAG_LOCK)
csd_unlock(data);
}
}
static DEFINE_PER_CPU_SHARED_ALIGNED(struct call_single_data, csd_data);
/*
* smp_call_function_single - Run a function on a specific CPU
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait until function has completed on other CPUs.
*
* Returns 0 on success, else a negative status code.
*/
int smp_call_function_single(int cpu, smp_call_func_t func, void *info,
int wait)
{
struct call_single_data d = {
.flags = 0,
};
unsigned long flags;
int this_cpu;
int err = 0;
/*
* prevent preemption and reschedule on another processor,
* as well as CPU removal
*/
this_cpu = get_cpu();
/*
* Can deadlock when called with interrupts disabled.
* We allow cpu's that are not yet online though, as no one else can
* send smp call function interrupt to this cpu and as such deadlocks
* can't happen.
*/
WARN_ON_ONCE(cpu_online(this_cpu) && irqs_disabled()
&& !oops_in_progress);
if (cpu == this_cpu) {
local_irq_save(flags);
func(info);
local_irq_restore(flags);
} else {
if ((unsigned)cpu < nr_cpu_ids && cpu_online(cpu)) {
struct call_single_data *data = &d;
if (!wait)
data = &__get_cpu_var(csd_data);
csd_lock(data);
data->func = func;
data->info = info;
generic_exec_single(cpu, data, wait);
} else {
err = -ENXIO; /* CPU not online */
}
}
put_cpu();
return err;
}
EXPORT_SYMBOL(smp_call_function_single);
/*
* smp_call_function_any - Run a function on any of the given cpus
* @mask: The mask of cpus it can run on.
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait until function has completed.
*
* Returns 0 on success, else a negative status code (if no cpus were online).
* Note that @wait will be implicitly turned on in case of allocation failures,
* since we fall back to on-stack allocation.
*
* Selection preference:
* 1) current cpu if in @mask
* 2) any cpu of current node if in @mask
* 3) any other online cpu in @mask
*/
int smp_call_function_any(const struct cpumask *mask,
smp_call_func_t func, void *info, int wait)
{
unsigned int cpu;
const struct cpumask *nodemask;
int ret;
/* Try for same CPU (cheapest) */
cpu = get_cpu();
if (cpumask_test_cpu(cpu, mask))
goto call;
/* Try for same node. */
nodemask = cpumask_of_node(cpu_to_node(cpu));
for (cpu = cpumask_first_and(nodemask, mask); cpu < nr_cpu_ids;
cpu = cpumask_next_and(cpu, nodemask, mask)) {
if (cpu_online(cpu))
goto call;
}
/* Any online will do: smp_call_function_single handles nr_cpu_ids. */
cpu = cpumask_any_and(mask, cpu_online_mask);
call:
ret = smp_call_function_single(cpu, func, info, wait);
put_cpu();
return ret;
}
EXPORT_SYMBOL_GPL(smp_call_function_any);
/**
* __smp_call_function_single(): Run a function on a specific CPU
* @cpu: The CPU to run on.
* @data: Pre-allocated and setup data structure
* @wait: If true, wait until function has completed on specified CPU.
*
* Like smp_call_function_single(), but allow caller to pass in a
* pre-allocated data structure. Useful for embedding @data inside
* other structures, for instance.
*/
void __smp_call_function_single(int cpu, struct call_single_data *data,
int wait)
{
unsigned int this_cpu;
unsigned long flags;
this_cpu = get_cpu();
/*
* Can deadlock when called with interrupts disabled.
* We allow cpu's that are not yet online though, as no one else can
* send smp call function interrupt to this cpu and as such deadlocks
* can't happen.
*/
WARN_ON_ONCE(cpu_online(smp_processor_id()) && wait && irqs_disabled()
&& !oops_in_progress);
if (cpu == this_cpu) {
local_irq_save(flags);
data->func(data->info);
local_irq_restore(flags);
} else {
csd_lock(data);
generic_exec_single(cpu, data, wait);
}
put_cpu();
}
/**
* smp_call_function_many(): Run a function on a set of other CPUs.
* @mask: The set of cpus to run on (only runs on online subset).
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait (atomically) until function has completed
* on other CPUs.
*
* If @wait is true, then returns once @func has returned.
*
* You must not call this function with disabled interrupts or from a
* hardware interrupt handler or from a bottom half handler. Preemption
* must be disabled when calling this function.
*/
void smp_call_function_many(const struct cpumask *mask,
smp_call_func_t func, void *info, bool wait)
{
struct call_function_data *data;
unsigned long flags;
int refs, cpu, next_cpu, this_cpu = smp_processor_id();
/*
* Can deadlock when called with interrupts disabled.
* We allow cpu's that are not yet online though, as no one else can
* send smp call function interrupt to this cpu and as such deadlocks
* can't happen.
*/
WARN_ON_ONCE(cpu_online(this_cpu) && irqs_disabled()
&& !oops_in_progress && !early_boot_irqs_disabled);
/* Try to fastpath. So, what's a CPU they want? Ignoring this one. */
cpu = cpumask_first_and(mask, cpu_online_mask);
if (cpu == this_cpu)
cpu = cpumask_next_and(cpu, mask, cpu_online_mask);
/* No online cpus? We're done. */
if (cpu >= nr_cpu_ids)
return;
/* Do we have another CPU which isn't us? */
next_cpu = cpumask_next_and(cpu, mask, cpu_online_mask);
if (next_cpu == this_cpu)
next_cpu = cpumask_next_and(next_cpu, mask, cpu_online_mask);
/* Fastpath: do that cpu by itself. */
if (next_cpu >= nr_cpu_ids) {
smp_call_function_single(cpu, func, info, wait);
return;
}
data = &__get_cpu_var(cfd_data);
csd_lock(&data->csd);
/* This BUG_ON verifies our reuse assertions and can be removed */
BUG_ON(atomic_read(&data->refs) || !cpumask_empty(data->cpumask));
/*
* The global call function queue list add and delete are protected
* by a lock, but the list is traversed without any lock, relying
* on the rcu list add and delete to allow safe concurrent traversal.
* We reuse the call function data without waiting for any grace
* period after some other cpu removes it from the global queue.
* This means a cpu might find our data block as it is being
* filled out.
*
* We hold off the interrupt handler on the other cpu by
* ordering our writes to the cpu mask vs our setting of the
* refs counter. We assert only the cpu owning the data block
* will set a bit in cpumask, and each bit will only be cleared
* by the subject cpu. Each cpu must first find its bit is
* set and then check that refs is set indicating the element is
* ready to be processed, otherwise it must skip the entry.
*
* On the previous iteration refs was set to 0 by another cpu.
* To avoid the use of transitivity, set the counter to 0 here
* so the wmb will pair with the rmb in the interrupt handler.
*/
atomic_set(&data->refs, 0); /* convert 3rd to 1st party write */
data->csd.func = func;
data->csd.info = info;
/* Ensure 0 refs is visible before mask. Also orders func and info */
smp_wmb();
/* We rely on the "and" being processed before the store */
cpumask_and(data->cpumask, mask, cpu_online_mask);
cpumask_clear_cpu(this_cpu, data->cpumask);
refs = cpumask_weight(data->cpumask);
/* Some callers race with other cpus changing the passed mask */
if (unlikely(!refs)) {
csd_unlock(&data->csd);
return;
}
raw_spin_lock_irqsave(&call_function.lock, flags);
/*
* Place entry at the _HEAD_ of the list, so that any cpu still
* observing the entry in generic_smp_call_function_interrupt()
* will not miss any other list entries:
*/
list_add_rcu(&data->csd.list, &call_function.queue);
/*
* We rely on the wmb() in list_add_rcu to complete our writes
* to the cpumask before this write to refs, which indicates
* data is on the list and is ready to be processed.
*/
atomic_set(&data->refs, refs);
raw_spin_unlock_irqrestore(&call_function.lock, flags);
/*
* Make the list addition visible before sending the ipi.
* (IPIs must obey or appear to obey normal Linux cache
* coherency rules -- see comment in generic_exec_single).
*/
smp_mb();
/* Send a message to all CPUs in the map */
arch_send_call_function_ipi_mask(data->cpumask);
/* Optionally wait for the CPUs to complete */
if (wait)
csd_lock_wait(&data->csd);
}
EXPORT_SYMBOL(smp_call_function_many);
/**
* smp_call_function(): Run a function on all other CPUs.
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait (atomically) until function has completed
* on other CPUs.
*
* Returns 0.
*
* If @wait is true, then returns once @func has returned; otherwise
* it returns just before the target cpu calls @func.
*
* You must not call this function with disabled interrupts or from a
* hardware interrupt handler or from a bottom half handler.
*/
int smp_call_function(smp_call_func_t func, void *info, int wait)
{
preempt_disable();
smp_call_function_many(cpu_online_mask, func, info, wait);
preempt_enable();
return 0;
}
EXPORT_SYMBOL(smp_call_function);
void ipi_call_lock(void)
{
raw_spin_lock(&call_function.lock);
}
void ipi_call_unlock(void)
{
raw_spin_unlock(&call_function.lock);
}
void ipi_call_lock_irq(void)
{
raw_spin_lock_irq(&call_function.lock);
}
void ipi_call_unlock_irq(void)
{
raw_spin_unlock_irq(&call_function.lock);
}
#endif /* USE_GENERIC_SMP_HELPERS */
/* Setup configured maximum number of CPUs to activate */
unsigned int setup_max_cpus = NR_CPUS;
EXPORT_SYMBOL(setup_max_cpus);
/*
* Setup routine for controlling SMP activation
*
* Command-line option of "nosmp" or "maxcpus=0" will disable SMP
* activation entirely (the MPS table probe still happens, though).
*
* Command-line option of "maxcpus=<NUM>", where <NUM> is an integer
* greater than 0, limits the maximum number of CPUs activated in
* SMP mode to <NUM>.
*/
void __weak arch_disable_smp_support(void) { }
static int __init nosmp(char *str)
{
setup_max_cpus = 0;
arch_disable_smp_support();
return 0;
}
early_param("nosmp", nosmp);
/* this is hard limit */
static int __init nrcpus(char *str)
{
int nr_cpus;
printk("=================");
get_option(&str, &nr_cpus);
if (nr_cpus > 0 && nr_cpus < nr_cpu_ids)
nr_cpu_ids = nr_cpus;
printk("nr_cpu = %d\n",nr_cpus);
return 0;
}
early_param("nr_cpus", nrcpus);
static int __init maxcpus(char *str)
{
get_option(&str, &setup_max_cpus);
if (setup_max_cpus == 0)
arch_disable_smp_support();
return 0;
}
early_param("maxcpus", maxcpus);
/* Setup number of possible processor ids */
int nr_cpu_ids __read_mostly = NR_CPUS;
EXPORT_SYMBOL(nr_cpu_ids);
/* An arch may set nr_cpu_ids earlier if needed, so this would be redundant */
void __init setup_nr_cpu_ids(void)
{
nr_cpu_ids = find_last_bit(cpumask_bits(cpu_possible_mask),NR_CPUS) + 1;
}
/* Called by boot processor to activate the rest. */
void __init smp_init(void)
{
unsigned int cpu;
/* FIXME: This should be done in userspace --RR */
for_each_present_cpu(cpu) {
if (num_online_cpus() >= setup_max_cpus)
break;
if (!cpu_online(cpu))
cpu_up(cpu);
}
/* Any cleanup work */
printk(KERN_INFO "Brought up %ld CPUs\n", (long)num_online_cpus());
smp_cpus_done(setup_max_cpus);
}
/*
* Call a function on all processors. May be used during early boot while
* early_boot_irqs_disabled is set. Use local_irq_save/restore() instead
* of local_irq_disable/enable().
*/
int on_each_cpu(void (*func) (void *info), void *info, int wait)
{
unsigned long flags;
int ret = 0;
preempt_disable();
ret = smp_call_function(func, info, wait);
local_irq_save(flags);
func(info);
local_irq_restore(flags);
preempt_enable();
return ret;
}
EXPORT_SYMBOL(on_each_cpu);
/**
* on_each_cpu_mask(): Run a function on processors specified by
* cpumask, which may include the local processor.
* @mask: The set of cpus to run on (only runs on online subset).
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait (atomically) until function has completed
* on other CPUs.
*
* If @wait is true, then returns once @func has returned.
*
* You must not call this function with disabled interrupts or
* from a hardware interrupt handler or from a bottom half handler.
*/
void on_each_cpu_mask(const struct cpumask *mask, smp_call_func_t func,
void *info, bool wait)
{
int cpu = get_cpu();
smp_call_function_many(mask, func, info, wait);
if (cpumask_test_cpu(cpu, mask)) {
local_irq_disable();
func(info);
local_irq_enable();
}
put_cpu();
}
EXPORT_SYMBOL(on_each_cpu_mask);
/*
* on_each_cpu_cond(): Call a function on each processor for which
* the supplied function cond_func returns true, optionally waiting
* for all the required CPUs to finish. This may include the local
* processor.
* @cond_func: A callback function that is passed a cpu id and
* the the info parameter. The function is called
* with preemption disabled. The function should
* return a blooean value indicating whether to IPI
* the specified CPU.
* @func: The function to run on all applicable CPUs.
* This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to both functions.
* @wait: If true, wait (atomically) until function has
* completed on other CPUs.
* @gfp_flags: GFP flags to use when allocating the cpumask
* used internally by the function.
*
* The function might sleep if the GFP flags indicates a non
* atomic allocation is allowed.
*
* Preemption is disabled to protect against CPUs going offline but not online.
* CPUs going online during the call will not be seen or sent an IPI.
*
* You must not call this function with disabled interrupts or
* from a hardware interrupt handler or from a bottom half handler.
*/
void on_each_cpu_cond(bool (*cond_func)(int cpu, void *info),
smp_call_func_t func, void *info, bool wait,
gfp_t gfp_flags)
{
cpumask_var_t cpus;
int cpu, ret;
might_sleep_if(gfp_flags & __GFP_WAIT);
if (likely(zalloc_cpumask_var(&cpus, (gfp_flags|__GFP_NOWARN)))) {
preempt_disable();
for_each_online_cpu(cpu)
if (cond_func(cpu, info))
cpumask_set_cpu(cpu, cpus);
on_each_cpu_mask(cpus, func, info, wait);
preempt_enable();
free_cpumask_var(cpus);
} else {
/*
* No free cpumask, bother. No matter, we'll
* just have to IPI them one by one.
*/
preempt_disable();
for_each_online_cpu(cpu)
if (cond_func(cpu, info)) {
ret = smp_call_function_single(cpu, func,
info, wait);
WARN_ON_ONCE(!ret);
}
preempt_enable();
}
}
EXPORT_SYMBOL(on_each_cpu_cond);
| burstlam/pantech_kernel_A850 | kernel/smp.c | C | gpl-2.0 | 21,846 | [
30522,
1013,
1008,
1008,
12391,
2393,
2545,
2005,
15488,
2361,
12997,
2072,
4455,
1008,
1008,
1006,
1039,
1007,
25093,
22260,
5092,
2063,
1026,
25093,
1012,
22260,
5092,
2063,
1030,
14721,
1012,
4012,
1028,
2263,
1008,
1013,
1001,
2421,
102... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-258.js
* @description Object.create - 'get' property of one property in 'Properties' is the primitive value null (8.10.5 step 7.b)
*/
function testcase() {
try {
Object.create({}, {
prop: {
get: null
}
});
return false;
} catch (e) {
return (e instanceof TypeError);
}
}
runTestCase(testcase);
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-258.js | JavaScript | bsd-3-clause | 543 | [
30522,
1013,
1013,
1013,
9385,
1006,
1039,
1007,
2262,
14925,
2863,
2248,
1012,
2035,
2916,
9235,
1012,
1013,
1008,
1008,
1008,
1030,
4130,
10381,
16068,
1013,
2321,
1012,
1016,
1013,
2321,
1012,
1016,
1012,
1017,
1013,
2321,
1012,
1016,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* The MIT License
*
* Copyright 2020 Intuit Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.intuit.karate.robot.mac;
import com.intuit.karate.StringUtils;
import com.intuit.karate.robot.Element;
import com.intuit.karate.robot.ImageElement;
import com.intuit.karate.robot.RobotBase;
import com.intuit.karate.robot.Window;
import com.intuit.karate.core.ScenarioEngine;
import com.intuit.karate.core.ScenarioRuntime;
import com.intuit.karate.shell.Command;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
/**
*
* @author pthomas3
*/
public class MacRobot extends RobotBase {
public MacRobot(ScenarioRuntime runtime, Map<String, Object> options) {
super(runtime, options);
}
@Override
public Map<String, Object> afterScenario() {
return Collections.EMPTY_MAP;
}
private static final String MAC_GET_PROCS
= " tell application \"System Events\""
+ "\n set procs to (processes whose background only is false)"
+ "\n set results to {}"
+ "\n repeat with n from 1 to the length of procs"
+ "\n set p to item n of procs"
+ "\n set entry to { name of p as text,\"|\"}"
+ "\n set end of results to entry"
+ "\n end repeat"
+ "\n end tell"
+ "\n results";
public static List<String> getAppsMacOs() {
String res = Command.exec(true, null, "osascript", "-e", MAC_GET_PROCS);
res = res + ", ";
res = res.replace(", |, ", "\n");
return StringUtils.split(res, '\n', false);
}
@Override
public Element windowInternal(String title) {
Command.exec(true, null, "osascript", "-e", "tell app \"" + title + "\" to activate");
return new ImageElement(screen); // TODO
}
@Override
public Element windowInternal(Predicate<String> condition) {
List<String> list = getAppsMacOs();
for (String s : list) {
if (condition.test(s)) {
Command.exec(true, null, "osascript", "-e", "tell app \"" + s + "\" to activate");
return new ImageElement(screen); // TODO
}
}
return null;
}
@Override
public List<Element> locateAllInternal(Element searchRoot, String locator) {
throw new UnsupportedOperationException("not supported yet.");
}
@Override
public Element locateInternal(Element root, String locator) {
throw new UnsupportedOperationException("not supported yet.");
}
@Override
public Element getRoot() {
return new ImageElement(screen);
}
@Override
public Element getFocused() {
return new ImageElement(screen);
}
@Override
public List<Window> getAllWindows() {
throw new UnsupportedOperationException("not supported yet.");
}
}
| intuit/karate | karate-robot/src/main/java/com/intuit/karate/robot/mac/MacRobot.java | Java | mit | 3,998 | [
30522,
1013,
1008,
1008,
1996,
10210,
6105,
1008,
1008,
9385,
12609,
20014,
14663,
4297,
1012,
1008,
1008,
6656,
2003,
2182,
3762,
4379,
1010,
2489,
1997,
3715,
1010,
2000,
2151,
2711,
11381,
1037,
6100,
1008,
1997,
2023,
4007,
1998,
3378,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "reverselock.h"
#include "test/test_vivo.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(reverselock_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(reverselock_basics)
{
boost::mutex mutex;
boost::unique_lock<boost::mutex> lock(mutex);
BOOST_CHECK(lock.owns_lock());
{
reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);
BOOST_CHECK(!lock.owns_lock());
}
BOOST_CHECK(lock.owns_lock());
}
BOOST_AUTO_TEST_CASE(reverselock_errors)
{
boost::mutex mutex;
boost::unique_lock<boost::mutex> lock(mutex);
// Make sure trying to reverse lock an unlocked lock fails
lock.unlock();
BOOST_CHECK(!lock.owns_lock());
bool failed = false;
try {
reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);
} catch(...) {
failed = true;
}
BOOST_CHECK(failed);
BOOST_CHECK(!lock.owns_lock());
// Make sure trying to lock a lock after it has been reverse locked fails
failed = false;
bool locked = false;
lock.lock();
BOOST_CHECK(lock.owns_lock());
try {
reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);
lock.lock();
locked = true;
} catch(...) {
failed = true;
}
BOOST_CHECK(locked && failed);
BOOST_CHECK(lock.owns_lock());
}
BOOST_AUTO_TEST_SUITE_END()
| vivocoin/vivo | src/test/reverselock_tests.cpp | C++ | mit | 1,560 | [
30522,
1013,
1013,
9385,
1006,
1039,
1007,
2325,
1996,
2978,
3597,
2378,
4563,
9797,
1013,
1013,
5500,
2104,
1996,
10210,
4007,
6105,
1010,
2156,
1996,
10860,
1013,
1013,
5371,
24731,
2030,
8299,
1024,
1013,
1013,
7479,
1012,
7480,
8162,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* @file
* @brief shared alias model loading code (md2, md3)
*/
/*
Copyright (C) 1997-2001 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "r_local.h"
#include "../../shared/parse.h"
#include "r_state.h"
/*
==============================================================================
ALIAS MODELS
==============================================================================
*/
void R_ModLoadAnims (mAliasModel_t *mod, const char *animname)
{
const char *text, *token;
mAliasAnim_t *anim;
int n;
/* load the tags */
byte *animbuf = NULL;
const char *buffer;
FS_LoadFile(animname, &animbuf);
buffer = (const char *)animbuf;
/* count the animations */
n = Com_CountTokensInBuffer(buffer);
if ((n % 4) != 0) {
FS_FreeFile(animbuf);
Com_Error(ERR_DROP, "invalid syntax: %s", animname);
}
/* each animation definition is made out of 4 tokens */
n /= 4;
if (n > MAX_ANIMS)
n = MAX_ANIMS;
mod->animdata = Mem_PoolAllocTypeN(mAliasAnim_t, n, vid_modelPool);
anim = mod->animdata;
text = buffer;
mod->num_anims = 0;
do {
/* get the name */
token = Com_Parse(&text);
if (!text)
break;
Q_strncpyz(anim->name, token, sizeof(anim->name));
/* get the start */
token = Com_Parse(&text);
if (!text)
break;
anim->from = atoi(token);
if (anim->from < 0)
Com_Error(ERR_FATAL, "R_ModLoadAnims: negative start frame for %s", animname);
else if (anim->from > mod->num_frames)
Com_Error(ERR_FATAL, "R_ModLoadAnims: start frame is higher than models frame count (%i) (model: %s)",
mod->num_frames, animname);
/* get the end */
token = Com_Parse(&text);
if (!text)
break;
anim->to = atoi(token);
if (anim->to < 0)
Com_Error(ERR_FATAL, "R_ModLoadAnims: negative end frame for %s", animname);
else if (anim->to > mod->num_frames)
Com_Error(ERR_FATAL, "R_ModLoadAnims: end frame is higher than models frame count (%i) (model: %s)",
mod->num_frames, animname);
/* get the fps */
token = Com_Parse(&text);
if (!text)
break;
anim->time = (atof(token) > 0.01) ? (1000.0 / atof(token)) : (1000.0 / 0.01);
/* add it */
mod->num_anims++;
anim++;
} while (mod->num_anims < n);
FS_FreeFile(animbuf);
}
/**
* @brief Calculates a per-vertex tangentspace basis and stores it in GL arrays attached to the mesh
* @param mesh The mesh to calculate normals for
* @param framenum The animation frame to calculate normals for
* @param translate The frame translation for the given animation frame
* @param backlerp Whether to store the results in the GL arrays for the previous keyframe or the next keyframe
* @sa R_ModCalcUniqueNormalsAndTangents
*/
static void R_ModCalcNormalsAndTangents (mAliasMesh_t *mesh, int framenum, const vec3_t translate, bool backlerp)
{
int i, j;
mAliasVertex_t *vertexes = &mesh->vertexes[framenum * mesh->num_verts];
mAliasCoord_t *stcoords = mesh->stcoords;
const int numIndexes = mesh->num_tris * 3;
const int32_t *indexArray = mesh->indexes;
vec3_t triangleNormals[MAX_ALIAS_TRIS];
vec3_t triangleTangents[MAX_ALIAS_TRIS];
vec3_t triangleBitangents[MAX_ALIAS_TRIS];
float *texcoords, *verts, *normals, *tangents;
/* set up array pointers for either the previous keyframe or the next keyframe */
texcoords = mesh->texcoords;
if (backlerp) {
verts = mesh->verts;
normals = mesh->normals;
tangents = mesh->tangents;
} else {
verts = mesh->next_verts;
normals = mesh->next_normals;
tangents = mesh->next_tangents;
}
/* calculate per-triangle surface normals and tangents*/
for (i = 0, j = 0; i < numIndexes; i += 3, j++) {
vec3_t dir1, dir2;
vec2_t dir1uv, dir2uv;
/* calculate two mostly perpendicular edge directions */
VectorSubtract(vertexes[indexArray[i + 0]].point, vertexes[indexArray[i + 1]].point, dir1);
VectorSubtract(vertexes[indexArray[i + 2]].point, vertexes[indexArray[i + 1]].point, dir2);
Vector2Subtract(stcoords[indexArray[i + 0]], stcoords[indexArray[i + 1]], dir1uv);
Vector2Subtract(stcoords[indexArray[i + 2]], stcoords[indexArray[i + 1]], dir2uv);
/* we have two edge directions, we can calculate a third vector from
* them, which is the direction of the surface normal */
CrossProduct(dir1, dir2, triangleNormals[j]);
/* normalize */
VectorNormalizeFast(triangleNormals[j]);
/* then we use the texture coordinates to calculate a tangent space */
if ((dir1uv[1] * dir2uv[0] - dir1uv[0] * dir2uv[1]) != 0.0) {
const float frac = 1.0 / (dir1uv[1] * dir2uv[0] - dir1uv[0] * dir2uv[1]);
vec3_t tmp1, tmp2;
/* calculate tangent */
VectorMul(-1.0 * dir2uv[1] * frac, dir1, tmp1);
VectorMul(dir1uv[1] * frac, dir2, tmp2);
VectorAdd(tmp1, tmp2, triangleTangents[j]);
/* calculate bitangent */
VectorMul(-1.0 * dir2uv[0] * frac, dir1, tmp1);
VectorMul(dir1uv[0] * frac, dir2, tmp2);
VectorAdd(tmp1, tmp2, triangleBitangents[j]);
/* normalize */
VectorNormalizeFast(triangleTangents[j]);
VectorNormalizeFast(triangleBitangents[j]);
} else {
VectorClear(triangleTangents[j]);
VectorClear(triangleBitangents[j]);
}
}
/* for each vertex */
for (i = 0; i < mesh->num_verts; i++) {
vec3_t n, b, v;
vec4_t t;
const int len = mesh->revIndexes[i].length;
const int32_t *list = mesh->revIndexes[i].list;
VectorClear(n);
VectorClear(t);
VectorClear(b);
/* for each vertex that got mapped to this one (ie. for each triangle this vertex is a part of) */
for (j = 0; j < len; j++) {
const int32_t idx = list[j] / 3;
VectorAdd(n, triangleNormals[idx], n);
VectorAdd(t, triangleTangents[idx], t);
VectorAdd(b, triangleBitangents[idx], b);
}
/* normalization here does shared-vertex smoothing */
VectorNormalizeFast(n);
VectorNormalizeFast(t);
VectorNormalizeFast(b);
/* Grahm-Schmidt orthogonalization */
Orthogonalize(t, n);
/* calculate handedness */
CrossProduct(n, t, v);
t[3] = (DotProduct(v, b) < 0.0) ? -1.0 : 1.0;
/* copy this vertex's info to all the right places in the arrays */
for (j = 0; j < len; j++) {
const int32_t idx = list[j];
const int meshIndex = mesh->indexes[list[j]];
Vector2Copy(stcoords[meshIndex], (texcoords + (2 * idx)));
VectorAdd(vertexes[meshIndex].point, translate, (verts + (3 * idx)));
VectorCopy(n, (normals + (3 * idx)));
Vector4Copy(t, (tangents + (4 * idx)));
}
}
}
/**
* @brief Tries to load a mdx file that contains the normals and the tangents for a model.
* @sa R_ModCalcNormalsAndTangents
* @sa R_ModCalcUniqueNormalsAndTangents
* @param mod The model to load the mdx file for
*/
bool R_ModLoadMDX (model_t *mod)
{
int i;
for (i = 0; i < mod->alias.num_meshes; i++) {
mAliasMesh_t *mesh = &mod->alias.meshes[i];
char mdxFileName[MAX_QPATH];
byte *buffer = NULL, *buf;
const int32_t *intbuf;
uint32_t version;
int sharedTris[MAX_ALIAS_VERTS];
Com_StripExtension(mod->name, mdxFileName, sizeof(mdxFileName));
Com_DefaultExtension(mdxFileName, sizeof(mdxFileName), ".mdx");
if (FS_LoadFile(mdxFileName, &buffer) == -1)
return false;
buf = buffer;
if (strncmp((const char *) buf, IDMDXHEADER, strlen(IDMDXHEADER))) {
FS_FreeFile(buf);
Com_Error(ERR_DROP, "No mdx file buffer given");
}
buffer += strlen(IDMDXHEADER) * sizeof(char);
version = LittleLong(*(uint32_t*) buffer);
if (version != MDX_VERSION) {
FS_FreeFile(buf);
Com_Error(ERR_DROP, "Invalid version of the mdx file, expected %i, found %i",
MDX_VERSION, version);
}
buffer += sizeof(uint32_t);
intbuf = (const int32_t *) buffer;
mesh->num_verts = LittleLong(*intbuf);
if (mesh->num_verts <= 0 || mesh->num_verts > MAX_ALIAS_VERTS) {
FS_FreeFile(buf);
Com_Error(ERR_DROP, "mdx file for %s has to many (or no) vertices: %i", mod->name, mesh->num_verts);
}
intbuf++;
mesh->num_indexes = LittleLong(*intbuf);
intbuf++;
mesh->indexes = Mem_PoolAllocTypeN(int32_t, mesh->num_indexes, vid_modelPool);
mesh->revIndexes = Mem_PoolAllocTypeN(mIndexList_t, mesh->num_verts, vid_modelPool);
mesh->vertexes = Mem_PoolAllocTypeN(mAliasVertex_t, mesh->num_verts * mod->alias.num_frames, vid_modelPool);
/* load index that maps triangle verts to Vertex objects */
for (i = 0; i < mesh->num_indexes; i++) {
mesh->indexes[i] = LittleLong(*intbuf);
intbuf++;
}
for (i = 0; i < mesh->num_verts; i++)
sharedTris[i] = 0;
/* set up reverse-index that maps Vertex objects to a list of triangle verts */
for (i = 0; i < mesh->num_indexes; i++)
sharedTris[mesh->indexes[i]]++;
for (i = 0; i < mesh->num_verts; i++) {
mesh->revIndexes[i].length = 0;
mesh->revIndexes[i].list = Mem_PoolAllocTypeN(int32_t, sharedTris[i], vid_modelPool);
}
for (i = 0; i < mesh->num_indexes; i++)
mesh->revIndexes[mesh->indexes[i]].list[mesh->revIndexes[mesh->indexes[i]].length++] = i;
FS_FreeFile(buf);
}
return true;
}
/**
* @brief Calculates normals and tangents for all frames and does vertex merging based on smoothness
* @param mesh The mesh to calculate normals for
* @param nFrames How many frames the mesh has
* @param smoothness How aggressively should normals be smoothed; value is compared with dotproduct of vectors to decide if they should be merged
* @sa R_ModCalcNormalsAndTangents
*/
void R_ModCalcUniqueNormalsAndTangents (mAliasMesh_t *mesh, int nFrames, float smoothness)
{
int i, j;
vec3_t triangleNormals[MAX_ALIAS_TRIS];
vec3_t triangleTangents[MAX_ALIAS_TRIS];
vec3_t triangleBitangents[MAX_ALIAS_TRIS];
const mAliasVertex_t *vertexes = mesh->vertexes;
mAliasCoord_t *stcoords = mesh->stcoords;
mAliasComplexVertex_t tmpVertexes[MAX_ALIAS_VERTS];
vec3_t tmpBitangents[MAX_ALIAS_VERTS];
const int numIndexes = mesh->num_tris * 3;
const int32_t *indexArray = mesh->indexes;
int indRemap[MAX_ALIAS_VERTS];
int sharedTris[MAX_ALIAS_VERTS];
int numVerts = 0;
if (numIndexes >= MAX_ALIAS_VERTS)
Com_Error(ERR_DROP, "model %s has too many tris", mesh->name);
int32_t* const newIndexArray = Mem_PoolAllocTypeN(int32_t, numIndexes, vid_modelPool);
/* calculate per-triangle surface normals */
for (i = 0, j = 0; i < numIndexes; i += 3, j++) {
vec3_t dir1, dir2;
vec2_t dir1uv, dir2uv;
/* calculate two mostly perpendicular edge directions */
VectorSubtract(vertexes[indexArray[i + 0]].point, vertexes[indexArray[i + 1]].point, dir1);
VectorSubtract(vertexes[indexArray[i + 2]].point, vertexes[indexArray[i + 1]].point, dir2);
Vector2Subtract(stcoords[indexArray[i + 0]], stcoords[indexArray[i + 1]], dir1uv);
Vector2Subtract(stcoords[indexArray[i + 2]], stcoords[indexArray[i + 1]], dir2uv);
/* we have two edge directions, we can calculate a third vector from
* them, which is the direction of the surface normal */
CrossProduct(dir1, dir2, triangleNormals[j]);
/* then we use the texture coordinates to calculate a tangent space */
if ((dir1uv[1] * dir2uv[0] - dir1uv[0] * dir2uv[1]) != 0.0) {
const float frac = 1.0 / (dir1uv[1] * dir2uv[0] - dir1uv[0] * dir2uv[1]);
vec3_t tmp1, tmp2;
/* calculate tangent */
VectorMul(-1.0 * dir2uv[1] * frac, dir1, tmp1);
VectorMul(dir1uv[1] * frac, dir2, tmp2);
VectorAdd(tmp1, tmp2, triangleTangents[j]);
/* calculate bitangent */
VectorMul(-1.0 * dir2uv[0] * frac, dir1, tmp1);
VectorMul(dir1uv[0] * frac, dir2, tmp2);
VectorAdd(tmp1, tmp2, triangleBitangents[j]);
} else {
const float frac = 1.0 / (0.00001);
vec3_t tmp1, tmp2;
/* calculate tangent */
VectorMul(-1.0 * dir2uv[1] * frac, dir1, tmp1);
VectorMul(dir1uv[1] * frac, dir2, tmp2);
VectorAdd(tmp1, tmp2, triangleTangents[j]);
/* calculate bitangent */
VectorMul(-1.0 * dir2uv[0] * frac, dir1, tmp1);
VectorMul(dir1uv[0] * frac, dir2, tmp2);
VectorAdd(tmp1, tmp2, triangleBitangents[j]);
}
/* normalize */
VectorNormalizeFast(triangleNormals[j]);
VectorNormalizeFast(triangleTangents[j]);
VectorNormalizeFast(triangleBitangents[j]);
Orthogonalize(triangleTangents[j], triangleBitangents[j]);
}
/* do smoothing */
for (i = 0; i < numIndexes; i++) {
const int idx = (i - i % 3) / 3;
VectorCopy(triangleNormals[idx], tmpVertexes[i].normal);
VectorCopy(triangleTangents[idx], tmpVertexes[i].tangent);
VectorCopy(triangleBitangents[idx], tmpBitangents[i]);
for (j = 0; j < numIndexes; j++) {
const int idx2 = (j - j % 3) / 3;
/* don't add a vertex with itself */
if (j == i)
continue;
/* only average normals if vertices have the same position
* and the normals aren't too far apart to start with */
if (VectorEqual(vertexes[indexArray[i]].point, vertexes[indexArray[j]].point)
&& DotProduct(triangleNormals[idx], triangleNormals[idx2]) > smoothness) {
/* average the normals */
VectorAdd(tmpVertexes[i].normal, triangleNormals[idx2], tmpVertexes[i].normal);
/* if the tangents match as well, average them too.
* Note that having matching normals without matching tangents happens
* when the order of vertices in two triangles sharing the vertex
* in question is different. This happens quite frequently if the
* modeler does not go out of their way to avoid it. */
if (Vector2Equal(stcoords[indexArray[i]], stcoords[indexArray[j]])
&& DotProduct(triangleTangents[idx], triangleTangents[idx2]) > smoothness
&& DotProduct(triangleBitangents[idx], triangleBitangents[idx2]) > smoothness) {
/* average the tangents */
VectorAdd(tmpVertexes[i].tangent, triangleTangents[idx2], tmpVertexes[i].tangent);
VectorAdd(tmpBitangents[i], triangleBitangents[idx2], tmpBitangents[i]);
}
}
}
VectorNormalizeFast(tmpVertexes[i].normal);
VectorNormalizeFast(tmpVertexes[i].tangent);
VectorNormalizeFast(tmpBitangents[i]);
}
/* assume all vertices are unique until proven otherwise */
for (i = 0; i < numIndexes; i++)
indRemap[i] = -1;
/* merge vertices that have become identical */
for (i = 0; i < numIndexes; i++) {
vec3_t n, b, t, v;
if (indRemap[i] != -1)
continue;
for (j = i + 1; j < numIndexes; j++) {
if (Vector2Equal(stcoords[indexArray[i]], stcoords[indexArray[j]])
&& VectorEqual(vertexes[indexArray[i]].point, vertexes[indexArray[j]].point)
&& (DotProduct(tmpVertexes[i].normal, tmpVertexes[j].normal) > smoothness)
&& (DotProduct(tmpVertexes[i].tangent, tmpVertexes[j].tangent) > smoothness)) {
indRemap[j] = i;
newIndexArray[j] = numVerts;
}
}
VectorCopy(tmpVertexes[i].normal, n);
VectorCopy(tmpVertexes[i].tangent, t);
VectorCopy(tmpBitangents[i], b);
/* normalization here does shared-vertex smoothing */
VectorNormalizeFast(n);
VectorNormalizeFast(t);
VectorNormalizeFast(b);
/* Grahm-Schmidt orthogonalization */
VectorMul(DotProduct(t, n), n, v);
VectorSubtract(t, v, t);
VectorNormalizeFast(t);
/* calculate handedness */
CrossProduct(n, t, v);
tmpVertexes[i].tangent[3] = (DotProduct(v, b) < 0.0) ? -1.0 : 1.0;
VectorCopy(n, tmpVertexes[i].normal);
VectorCopy(t, tmpVertexes[i].tangent);
newIndexArray[i] = numVerts++;
indRemap[i] = i;
}
for (i = 0; i < numVerts; i++)
sharedTris[i] = 0;
for (i = 0; i < numIndexes; i++)
sharedTris[newIndexArray[i]]++;
/* set up reverse-index that maps Vertex objects to a list of triangle verts */
mesh->revIndexes = Mem_PoolAllocTypeN(mIndexList_t, numVerts, vid_modelPool);
for (i = 0; i < numVerts; i++) {
mesh->revIndexes[i].length = 0;
mesh->revIndexes[i].list = Mem_PoolAllocTypeN(int32_t, sharedTris[i], vid_modelPool);
}
/* merge identical vertexes, storing only unique ones */
mAliasVertex_t* const newVertexes = Mem_PoolAllocTypeN(mAliasVertex_t, numVerts * nFrames, vid_modelPool);
mAliasCoord_t* const newStcoords = Mem_PoolAllocTypeN(mAliasCoord_t, numVerts, vid_modelPool);
for (i = 0; i < numIndexes; i++) {
const int idx = indexArray[indRemap[i]];
const int idx2 = newIndexArray[i];
/* add vertex to new vertex array */
VectorCopy(vertexes[idx].point, newVertexes[idx2].point);
Vector2Copy(stcoords[idx], newStcoords[idx2]);
mesh->revIndexes[idx2].list[mesh->revIndexes[idx2].length++] = i;
}
/* copy over the points from successive frames */
for (i = 1; i < nFrames; i++) {
for (j = 0; j < numIndexes; j++) {
const int idx = indexArray[indRemap[j]] + (mesh->num_verts * i);
const int idx2 = newIndexArray[j] + (numVerts * i);
VectorCopy(vertexes[idx].point, newVertexes[idx2].point);
}
}
/* copy new arrays back into original mesh */
Mem_Free(mesh->stcoords);
Mem_Free(mesh->indexes);
Mem_Free(mesh->vertexes);
mesh->num_verts = numVerts;
mesh->vertexes = newVertexes;
mesh->stcoords = newStcoords;
mesh->indexes = newIndexArray;
}
image_t* R_AliasModelGetSkin (const char *modelFileName, const char *skin)
{
image_t* result;
if (skin[0] != '.')
result = R_FindImage(skin, it_skin);
else {
char path[MAX_QPATH];
Com_ReplaceFilename(modelFileName, skin + 1, path, sizeof(path));
result = R_FindImage(path, it_skin);
}
return result;
}
image_t* R_AliasModelState (const model_t *mod, int *mesh, int *frame, int *oldFrame, int *skin)
{
/* check animations */
if ((*frame >= mod->alias.num_frames) || *frame < 0) {
Com_Printf("R_AliasModelState %s: no such frame %d (# %i)\n", mod->name, *frame, mod->alias.num_frames);
*frame = 0;
}
if ((*oldFrame >= mod->alias.num_frames) || *oldFrame < 0) {
Com_Printf("R_AliasModelState %s: no such oldframe %d (# %i)\n", mod->name, *oldFrame, mod->alias.num_frames);
*oldFrame = 0;
}
if (*mesh < 0 || *mesh >= mod->alias.num_meshes)
*mesh = 0;
if (!mod->alias.meshes)
return NULL;
/* use default skin - this is never null - but maybe the placeholder texture */
if (*skin < 0 || *skin >= mod->alias.meshes[*mesh].num_skins)
*skin = 0;
if (!mod->alias.meshes[*mesh].num_skins)
Com_Error(ERR_DROP, "Model with no skins");
if (mod->alias.meshes[*mesh].skins[*skin].skin->texnum <= 0)
Com_Error(ERR_DROP, "Texture is already freed and no longer uploaded, texnum is invalid for model %s",
mod->name);
return mod->alias.meshes[*mesh].skins[*skin].skin;
}
/**
* @brief Converts the model data into the opengl arrays
* @param mod The model to convert
* @param mesh The particular mesh of the model to convert
* @param backlerp The linear back interpolation when loading the data
* @param framenum The frame number of the mesh to load (if animated)
* @param oldframenum The old frame number (used to interpolate)
* @param prerender If this is @c true, all data is filled to the arrays. If @c false, then
* e.g. the normals are only filled to the arrays if the lighting is activated.
*
* @note If GLSL programs are enabled, the actual interpolation will be done on the GPU, but
* this function is still needed to fill the GL arrays for the keyframes
*/
void R_FillArrayData (mAliasModel_t* mod, mAliasMesh_t *mesh, float backlerp, int framenum, int oldframenum, bool prerender)
{
const mAliasFrame_t *frame, *oldframe;
vec3_t move;
const float frontlerp = 1.0 - backlerp;
vec3_t r_mesh_verts[MAX_ALIAS_VERTS];
vec_t *texcoord_array, *vertex_array_3d;
frame = mod->frames + framenum;
oldframe = mod->frames + oldframenum;
/* try to do keyframe-interpolation on the GPU if possible*/
if (r_state.lighting_enabled) {
/* we only need to change the array data if we've switched to a new keyframe */
if (mod->curFrame != framenum) {
/* if we're rendering frames in order, the "next" keyframe from the previous
* time through will be our "previous" keyframe now, so we can swap pointers
* instead of generating it again from scratch */
if (mod->curFrame == oldframenum) {
vec_t *tmp1 = mesh->verts;
vec_t *tmp2 = mesh->normals;
vec_t *tmp3 = mesh->tangents;
mesh->verts = mesh->next_verts;
mesh->next_verts = tmp1;
mesh->normals = mesh->next_normals;
mesh->next_normals = tmp2;
mesh->tangents = mesh->next_tangents;
mesh->next_tangents = tmp3;
/* if we're alternating between two keyframes, we don't need to generate
* anything; otherwise, generate the "next" keyframe*/
if (mod->oldFrame != framenum)
R_ModCalcNormalsAndTangents(mesh, framenum, frame->translate, false);
} else {
/* if we're starting a new animation or otherwise not rendering keyframes
* in order, we need to fill the arrays for both keyframes */
R_ModCalcNormalsAndTangents(mesh, oldframenum, oldframe->translate, true);
R_ModCalcNormalsAndTangents(mesh, framenum, frame->translate, false);
}
/* keep track of which keyframes are currently stored in our arrays */
mod->oldFrame = oldframenum;
mod->curFrame = framenum;
}
} else { /* otherwise, we have to do it on the CPU */
const mAliasVertex_t *v, *ov;
int i;
assert(mesh->num_verts < lengthof(r_mesh_verts));
v = &mesh->vertexes[framenum * mesh->num_verts];
ov = &mesh->vertexes[oldframenum * mesh->num_verts];
if (prerender)
R_ModCalcNormalsAndTangents(mesh, 0, oldframe->translate, true);
for (i = 0; i < 3; i++)
move[i] = backlerp * oldframe->translate[i] + frontlerp * frame->translate[i];
for (i = 0; i < mesh->num_verts; i++, v++, ov++) { /* lerp the verts */
VectorSet(r_mesh_verts[i],
move[0] + ov->point[0] * backlerp + v->point[0] * frontlerp,
move[1] + ov->point[1] * backlerp + v->point[1] * frontlerp,
move[2] + ov->point[2] * backlerp + v->point[2] * frontlerp);
}
R_ReallocateStateArrays(mesh->num_tris * 3);
R_ReallocateTexunitArray(&texunit_diffuse, mesh->num_tris * 3);
texcoord_array = texunit_diffuse.texcoord_array;
vertex_array_3d = r_state.vertex_array_3d;
/** @todo damn slow - optimize this */
for (i = 0; i < mesh->num_tris; i++) { /* draw the tris */
int j;
for (j = 0; j < 3; j++) {
const int arrayIndex = 3 * i + j;
const int meshIndex = mesh->indexes[arrayIndex];
Vector2Copy(mesh->stcoords[meshIndex], texcoord_array);
VectorCopy(r_mesh_verts[meshIndex], vertex_array_3d);
texcoord_array += 2;
vertex_array_3d += 3;
}
}
}
}
/**
* @brief Allocates data arrays for animated models. Only called once at loading time.
*/
void R_ModLoadArrayData (mAliasModel_t *mod, mAliasMesh_t *mesh, bool loadNormals)
{
const int v = mesh->num_tris * 3 * 3;
const int t = mesh->num_tris * 3 * 4;
const int st = mesh->num_tris * 3 * 2;
assert(mesh->verts == NULL);
assert(mesh->texcoords == NULL);
assert(mesh->normals == NULL);
assert(mesh->tangents == NULL);
assert(mesh->next_verts == NULL);
assert(mesh->next_normals == NULL);
assert(mesh->next_tangents == NULL);
mesh->verts = Mem_PoolAllocTypeN(float, v, vid_modelPool);
mesh->normals = Mem_PoolAllocTypeN(float, v, vid_modelPool);
mesh->tangents = Mem_PoolAllocTypeN(float, t, vid_modelPool);
mesh->texcoords = Mem_PoolAllocTypeN(float, st, vid_modelPool);
if (mod->num_frames == 1) {
R_FillArrayData(mod, mesh, 0.0, 0, 0, loadNormals);
} else {
mesh->next_verts = Mem_PoolAllocTypeN(float, v, vid_modelPool);
mesh->next_normals = Mem_PoolAllocTypeN(float, v, vid_modelPool);
mesh->next_tangents = Mem_PoolAllocTypeN(float, t, vid_modelPool);
mod->curFrame = -1;
mod->oldFrame = -1;
}
}
| Qazzian/ufoai_suspend | src/client/renderer/r_model_alias.cpp | C++ | gpl-2.0 | 23,883 | [
30522,
1013,
1008,
1008,
1008,
1030,
5371,
1008,
1030,
4766,
4207,
14593,
2944,
10578,
3642,
1006,
9108,
2475,
1010,
9108,
2509,
1007,
1008,
1013,
1013,
1008,
9385,
1006,
1039,
1007,
2722,
1011,
2541,
8909,
4007,
1010,
4297,
1012,
2023,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* Themes: Velonic Admin theme
*
**/
! function($) {
"use strict";
/**
Sidebar Module
*/
var SideBar = function() {
this.$body = $("body"),
this.$sideBar = $('aside.left-panel'),
this.$navbarToggle = $(".navbar-toggle"),
this.$navbarItem = $("aside.left-panel nav.navigation > ul > li:has(ul) > a")
};
//initilizing
SideBar.prototype.init = function() {
//on toggle side menu bar
var $this = this;
$(document).on('click', '.navbar-toggle', function () {
$this.$sideBar.toggleClass('collapsed');
});
//on menu item clicking
this.$navbarItem.click(function () {
if ($this.$sideBar.hasClass('collapsed') == false || $(window).width() < 768) {
$("aside.left-panel nav.navigation > ul > li > ul").slideUp(300);
$("aside.left-panel nav.navigation > ul > li").removeClass('active');
if (!$(this).next().is(":visible")) {
$(this).next().slideToggle(300, function () {
$("aside.left-panel:not(.collapsed)").getNiceScroll().resize();
});
$(this).closest('li').addClass('active');
}
return false;
}
});
//adding nicescroll to sidebar
if ($.isFunction($.fn.niceScroll)) {
$("aside.left-panel:not(.collapsed)").niceScroll({
cursorcolor: '#8e909a',
cursorborder: '0px solid #fff',
cursoropacitymax: '0.5',
cursorborderradius: '0px'
});
}
},
//exposing the sidebar module
$.SideBar = new SideBar, $.SideBar.Constructor = SideBar
}(window.jQuery),
//portlets
function($) {
"use strict";
/**
Portlet Widget
*/
var Portlet = function() {
this.$body = $("body"),
this.$portletIdentifier = ".portlet",
this.$portletCloser = '.portlet a[data-toggle="remove"]',
this.$portletRefresher = '.portlet a[data-toggle="reload"]'
};
//on init
Portlet.prototype.init = function() {
// Panel closest
var $this = this;
$(document).on("click",this.$portletCloser, function (ev) {
ev.preventDefault();
var $portlet = $(this).closest($this.$portletIdentifier);
var $portlet_parent = $portlet.parent();
$portlet.remove();
if ($portlet_parent.children().length == 0) {
$portlet_parent.remove();
}
});
// Panel Reload
$(document).on("click",this.$portletRefresher, function (ev) {
ev.preventDefault();
var $portlet = $(this).closest($this.$portletIdentifier);
// This is just a simulation, nothing is going to be reloaded
$portlet.append('<div class="panel-disabled"><div class="loader-1"></div></div>');
var $pd = $portlet.find('.panel-disabled');
setTimeout(function () {
$pd.fadeOut('fast', function () {
$pd.remove();
});
}, 500 + 300 * (Math.random() * 5));
});
},
//
$.Portlet = new Portlet, $.Portlet.Constructor = Portlet
}(window.jQuery),
//main app module
function($) {
"use strict";
var VelonicApp = function() {
this.VERSION = "1.0.0",
this.AUTHOR = "Coderthemes",
this.SUPPORT = "coderthemes@gmail.com",
this.pageScrollElement = "html, body",
this.$body = $("body")
};
//initializing tooltip
VelonicApp.prototype.initTooltipPlugin = function() {
$.fn.tooltip && $('[data-toggle="tooltip"]').tooltip()
},
//initializing popover
VelonicApp.prototype.initPopoverPlugin = function() {
$.fn.popover && $('[data-toggle="popover"]').popover()
},
//initializing nicescroll
VelonicApp.prototype.initNiceScrollPlugin = function() {
//You can change the color of scroll bar here
$.fn.niceScroll && $(".nicescroll").niceScroll({ cursorcolor: '#9d9ea5', cursorborderradius: '0px'});
},
//initializing knob
VelonicApp.prototype.initKnob = function() {
if ($(".knob").length > 0) {
$(".knob").knob();
}
},
//initilizing
VelonicApp.prototype.init = function() {
this.initTooltipPlugin(),
this.initPopoverPlugin(),
this.initNiceScrollPlugin(),
this.initKnob(),
//creating side bar
$.SideBar.init(),
//creating portles
$.Portlet.init();
},
$.VelonicApp = new VelonicApp, $.VelonicApp.Constructor = VelonicApp
}(window.jQuery),
//initializing main application module
function($) {
"use strict";
$.VelonicApp.init()
}(window.jQuery);
/* ==============================================
7.WOW plugin triggers animate.css on scroll
=============================================== */
var wow = new WOW(
{
boxClass: 'wow', // animated element css class (default is wow)
animateClass: 'animated', // animation css class (default is animated)
offset: 50, // distance to the element when triggering the animation (default is 0)
mobile: false // trigger animations on mobile devices (true is default)
}
);
wow.init();
| proyectobufete/ProyectoBufete | web/asst/js/jquery.app.js | JavaScript | mit | 5,422 | [
30522,
1013,
1008,
1008,
1008,
6991,
1024,
2310,
7811,
2594,
4748,
10020,
4323,
1008,
1008,
1008,
1013,
999,
3853,
1006,
1002,
1007,
1063,
1000,
2224,
9384,
1000,
1025,
1013,
1008,
1008,
2217,
8237,
11336,
1008,
1013,
13075,
2217,
8237,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import {Component, ViewChild, HostListener, Input, ElementRef} from '@angular/core';
@Component({
selector: 'ba-back-top',
styleUrls: ['./baBackTop.scss'],
template: `
<i #baBackTop class="fa fa-angle-up back-top ba-back-top" title="Back to Top"></i>
`
})
export class BaBackTop {
@Input() position:number = 400;
@Input() showSpeed:number = 500;
@Input() moveSpeed:number = 1000;
@ViewChild('baBackTop') _selector:ElementRef;
ngAfterViewInit () {
this._onWindowScroll();
}
@HostListener('click')
_onClick():boolean {
jQuery('html, body').animate({scrollTop:0}, {duration:this.moveSpeed});
return false;
}
@HostListener('window:scroll')
_onWindowScroll():void {
let el = this._selector.nativeElement;
window.scrollY > this.position ? jQuery(el).fadeIn(this.showSpeed) : jQuery(el).fadeOut(this.showSpeed);
}
}
| civiclee/Hack4Cause2017 | src/urban-insight/src/app/theme/components/baBackTop/baBackTop.component.ts | TypeScript | mit | 871 | [
30522,
12324,
1063,
6922,
1010,
3193,
19339,
1010,
3677,
9863,
24454,
1010,
7953,
1010,
5783,
2890,
2546,
1065,
2013,
1005,
1030,
16108,
1013,
4563,
1005,
1025,
1030,
6922,
1006,
1063,
27000,
1024,
1005,
8670,
1011,
2067,
1011,
2327,
1005,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
******************************************************************************
* @file stm32f4xx_ll_dma.c
* @author MCD Application Team
* @brief DMA LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_ll_dma.h"
#include "stm32f4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F4xx_LL_Driver
* @{
*/
#if defined (DMA1) || defined (DMA2)
/** @defgroup DMA_LL DMA
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup DMA_LL_Private_Macros
* @{
*/
#define IS_LL_DMA_DIRECTION(__VALUE__) (((__VALUE__) == LL_DMA_DIRECTION_PERIPH_TO_MEMORY) || \
((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_PERIPH) || \
((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_MEMORY))
#define IS_LL_DMA_MODE(__VALUE__) (((__VALUE__) == LL_DMA_MODE_NORMAL) || \
((__VALUE__) == LL_DMA_MODE_CIRCULAR) || \
((__VALUE__) == LL_DMA_MODE_PFCTRL))
#define IS_LL_DMA_PERIPHINCMODE(__VALUE__) (((__VALUE__) == LL_DMA_PERIPH_INCREMENT) || \
((__VALUE__) == LL_DMA_PERIPH_NOINCREMENT))
#define IS_LL_DMA_MEMORYINCMODE(__VALUE__) (((__VALUE__) == LL_DMA_MEMORY_INCREMENT) || \
((__VALUE__) == LL_DMA_MEMORY_NOINCREMENT))
#define IS_LL_DMA_PERIPHDATASIZE(__VALUE__) (((__VALUE__) == LL_DMA_PDATAALIGN_BYTE) || \
((__VALUE__) == LL_DMA_PDATAALIGN_HALFWORD) || \
((__VALUE__) == LL_DMA_PDATAALIGN_WORD))
#define IS_LL_DMA_MEMORYDATASIZE(__VALUE__) (((__VALUE__) == LL_DMA_MDATAALIGN_BYTE) || \
((__VALUE__) == LL_DMA_MDATAALIGN_HALFWORD) || \
((__VALUE__) == LL_DMA_MDATAALIGN_WORD))
#define IS_LL_DMA_NBDATA(__VALUE__) ((__VALUE__) <= 0x0000FFFFU)
#define IS_LL_DMA_CHANNEL(__VALUE__) (((__VALUE__) == LL_DMA_CHANNEL_0) || \
((__VALUE__) == LL_DMA_CHANNEL_1) || \
((__VALUE__) == LL_DMA_CHANNEL_2) || \
((__VALUE__) == LL_DMA_CHANNEL_3) || \
((__VALUE__) == LL_DMA_CHANNEL_4) || \
((__VALUE__) == LL_DMA_CHANNEL_5) || \
((__VALUE__) == LL_DMA_CHANNEL_6) || \
((__VALUE__) == LL_DMA_CHANNEL_7))
#define IS_LL_DMA_PRIORITY(__VALUE__) (((__VALUE__) == LL_DMA_PRIORITY_LOW) || \
((__VALUE__) == LL_DMA_PRIORITY_MEDIUM) || \
((__VALUE__) == LL_DMA_PRIORITY_HIGH) || \
((__VALUE__) == LL_DMA_PRIORITY_VERYHIGH))
#define IS_LL_DMA_ALL_STREAM_INSTANCE(INSTANCE, STREAM) ((((INSTANCE) == DMA1) && \
(((STREAM) == LL_DMA_STREAM_0) || \
((STREAM) == LL_DMA_STREAM_1) || \
((STREAM) == LL_DMA_STREAM_2) || \
((STREAM) == LL_DMA_STREAM_3) || \
((STREAM) == LL_DMA_STREAM_4) || \
((STREAM) == LL_DMA_STREAM_5) || \
((STREAM) == LL_DMA_STREAM_6) || \
((STREAM) == LL_DMA_STREAM_7) || \
((STREAM) == LL_DMA_STREAM_ALL))) ||\
(((INSTANCE) == DMA2) && \
(((STREAM) == LL_DMA_STREAM_0) || \
((STREAM) == LL_DMA_STREAM_1) || \
((STREAM) == LL_DMA_STREAM_2) || \
((STREAM) == LL_DMA_STREAM_3) || \
((STREAM) == LL_DMA_STREAM_4) || \
((STREAM) == LL_DMA_STREAM_5) || \
((STREAM) == LL_DMA_STREAM_6) || \
((STREAM) == LL_DMA_STREAM_7) || \
((STREAM) == LL_DMA_STREAM_ALL))))
#define IS_LL_DMA_FIFO_MODE_STATE(STATE) (((STATE) == LL_DMA_FIFOMODE_DISABLE ) || \
((STATE) == LL_DMA_FIFOMODE_ENABLE))
#define IS_LL_DMA_FIFO_THRESHOLD(THRESHOLD) (((THRESHOLD) == LL_DMA_FIFOTHRESHOLD_1_4) || \
((THRESHOLD) == LL_DMA_FIFOTHRESHOLD_1_2) || \
((THRESHOLD) == LL_DMA_FIFOTHRESHOLD_3_4) || \
((THRESHOLD) == LL_DMA_FIFOTHRESHOLD_FULL))
#define IS_LL_DMA_MEMORY_BURST(BURST) (((BURST) == LL_DMA_MBURST_SINGLE) || \
((BURST) == LL_DMA_MBURST_INC4) || \
((BURST) == LL_DMA_MBURST_INC8) || \
((BURST) == LL_DMA_MBURST_INC16))
#define IS_LL_DMA_PERIPHERAL_BURST(BURST) (((BURST) == LL_DMA_PBURST_SINGLE) || \
((BURST) == LL_DMA_PBURST_INC4) || \
((BURST) == LL_DMA_PBURST_INC8) || \
((BURST) == LL_DMA_PBURST_INC16))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup DMA_LL_Exported_Functions
* @{
*/
/** @addtogroup DMA_LL_EF_Init
* @{
*/
/**
* @brief De-initialize the DMA registers to their default reset values.
* @param DMAx DMAx Instance
* @param Stream This parameter can be one of the following values:
* @arg @ref LL_DMA_STREAM_0
* @arg @ref LL_DMA_STREAM_1
* @arg @ref LL_DMA_STREAM_2
* @arg @ref LL_DMA_STREAM_3
* @arg @ref LL_DMA_STREAM_4
* @arg @ref LL_DMA_STREAM_5
* @arg @ref LL_DMA_STREAM_6
* @arg @ref LL_DMA_STREAM_7
* @arg @ref LL_DMA_STREAM_ALL
* @retval An ErrorStatus enumeration value:
* - SUCCESS: DMA registers are de-initialized
* - ERROR: DMA registers are not de-initialized
*/
uint32_t LL_DMA_DeInit(DMA_TypeDef *DMAx, uint32_t Stream)
{
DMA_Stream_TypeDef *tmp = (DMA_Stream_TypeDef *)DMA1_Stream0;
ErrorStatus status = SUCCESS;
/* Check the DMA Instance DMAx and Stream parameters*/
assert_param(IS_LL_DMA_ALL_STREAM_INSTANCE(DMAx, Stream));
if (Stream == LL_DMA_STREAM_ALL)
{
if (DMAx == DMA1)
{
/* Force reset of DMA clock */
LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_DMA1);
/* Release reset of DMA clock */
LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_DMA1);
}
else if (DMAx == DMA2)
{
/* Force reset of DMA clock */
LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_DMA2);
/* Release reset of DMA clock */
LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_DMA2);
}
else
{
status = ERROR;
}
}
else
{
/* Disable the selected Stream */
LL_DMA_DisableStream(DMAx,Stream);
/* Get the DMA Stream Instance */
tmp = (DMA_Stream_TypeDef *)(__LL_DMA_GET_STREAM_INSTANCE(DMAx, Stream));
/* Reset DMAx_Streamy configuration register */
LL_DMA_WriteReg(tmp, CR, 0U);
/* Reset DMAx_Streamy remaining bytes register */
LL_DMA_WriteReg(tmp, NDTR, 0U);
/* Reset DMAx_Streamy peripheral address register */
LL_DMA_WriteReg(tmp, PAR, 0U);
/* Reset DMAx_Streamy memory address register */
LL_DMA_WriteReg(tmp, M0AR, 0U);
/* Reset DMAx_Streamy memory address register */
LL_DMA_WriteReg(tmp, M1AR, 0U);
/* Reset DMAx_Streamy FIFO control register */
LL_DMA_WriteReg(tmp, FCR, 0x00000021U);
/* Reset Channel register field for DMAx Stream*/
LL_DMA_SetChannelSelection(DMAx, Stream, LL_DMA_CHANNEL_0);
if(Stream == LL_DMA_STREAM_0)
{
/* Reset the Stream0 pending flags */
DMAx->LIFCR = 0x0000003FU;
}
else if(Stream == LL_DMA_STREAM_1)
{
/* Reset the Stream1 pending flags */
DMAx->LIFCR = 0x00000F40U;
}
else if(Stream == LL_DMA_STREAM_2)
{
/* Reset the Stream2 pending flags */
DMAx->LIFCR = 0x003F0000U;
}
else if(Stream == LL_DMA_STREAM_3)
{
/* Reset the Stream3 pending flags */
DMAx->LIFCR = 0x0F400000U;
}
else if(Stream == LL_DMA_STREAM_4)
{
/* Reset the Stream4 pending flags */
DMAx->HIFCR = 0x0000003FU;
}
else if(Stream == LL_DMA_STREAM_5)
{
/* Reset the Stream5 pending flags */
DMAx->HIFCR = 0x00000F40U;
}
else if(Stream == LL_DMA_STREAM_6)
{
/* Reset the Stream6 pending flags */
DMAx->HIFCR = 0x003F0000U;
}
else if(Stream == LL_DMA_STREAM_7)
{
/* Reset the Stream7 pending flags */
DMAx->HIFCR = 0x0F400000U;
}
else
{
status = ERROR;
}
}
return status;
}
/**
* @brief Initialize the DMA registers according to the specified parameters in DMA_InitStruct.
* @note To convert DMAx_Streamy Instance to DMAx Instance and Streamy, use helper macros :
* @arg @ref __LL_DMA_GET_INSTANCE
* @arg @ref __LL_DMA_GET_STREAM
* @param DMAx DMAx Instance
* @param Stream This parameter can be one of the following values:
* @arg @ref LL_DMA_STREAM_0
* @arg @ref LL_DMA_STREAM_1
* @arg @ref LL_DMA_STREAM_2
* @arg @ref LL_DMA_STREAM_3
* @arg @ref LL_DMA_STREAM_4
* @arg @ref LL_DMA_STREAM_5
* @arg @ref LL_DMA_STREAM_6
* @arg @ref LL_DMA_STREAM_7
* @param DMA_InitStruct pointer to a @ref LL_DMA_InitTypeDef structure.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: DMA registers are initialized
* - ERROR: Not applicable
*/
uint32_t LL_DMA_Init(DMA_TypeDef *DMAx, uint32_t Stream, LL_DMA_InitTypeDef *DMA_InitStruct)
{
/* Check the DMA Instance DMAx and Stream parameters*/
assert_param(IS_LL_DMA_ALL_STREAM_INSTANCE(DMAx, Stream));
/* Check the DMA parameters from DMA_InitStruct */
assert_param(IS_LL_DMA_DIRECTION(DMA_InitStruct->Direction));
assert_param(IS_LL_DMA_MODE(DMA_InitStruct->Mode));
assert_param(IS_LL_DMA_PERIPHINCMODE(DMA_InitStruct->PeriphOrM2MSrcIncMode));
assert_param(IS_LL_DMA_MEMORYINCMODE(DMA_InitStruct->MemoryOrM2MDstIncMode));
assert_param(IS_LL_DMA_PERIPHDATASIZE(DMA_InitStruct->PeriphOrM2MSrcDataSize));
assert_param(IS_LL_DMA_MEMORYDATASIZE(DMA_InitStruct->MemoryOrM2MDstDataSize));
assert_param(IS_LL_DMA_NBDATA(DMA_InitStruct->NbData));
assert_param(IS_LL_DMA_CHANNEL(DMA_InitStruct->Channel));
assert_param(IS_LL_DMA_PRIORITY(DMA_InitStruct->Priority));
assert_param(IS_LL_DMA_FIFO_MODE_STATE(DMA_InitStruct->FIFOMode));
/* Check the memory burst, peripheral burst and FIFO threshold parameters only
when FIFO mode is enabled */
if(DMA_InitStruct->FIFOMode != LL_DMA_FIFOMODE_DISABLE)
{
assert_param(IS_LL_DMA_FIFO_THRESHOLD(DMA_InitStruct->FIFOThreshold));
assert_param(IS_LL_DMA_MEMORY_BURST(DMA_InitStruct->MemBurst));
assert_param(IS_LL_DMA_PERIPHERAL_BURST(DMA_InitStruct->PeriphBurst));
}
/*---------------------------- DMAx SxCR Configuration ------------------------
* Configure DMAx_Streamy: data transfer direction, data transfer mode,
* peripheral and memory increment mode,
* data size alignment and priority level with parameters :
* - Direction: DMA_SxCR_DIR[1:0] bits
* - Mode: DMA_SxCR_CIRC bit
* - PeriphOrM2MSrcIncMode: DMA_SxCR_PINC bit
* - MemoryOrM2MDstIncMode: DMA_SxCR_MINC bit
* - PeriphOrM2MSrcDataSize: DMA_SxCR_PSIZE[1:0] bits
* - MemoryOrM2MDstDataSize: DMA_SxCR_MSIZE[1:0] bits
* - Priority: DMA_SxCR_PL[1:0] bits
*/
LL_DMA_ConfigTransfer(DMAx, Stream, DMA_InitStruct->Direction | \
DMA_InitStruct->Mode | \
DMA_InitStruct->PeriphOrM2MSrcIncMode | \
DMA_InitStruct->MemoryOrM2MDstIncMode | \
DMA_InitStruct->PeriphOrM2MSrcDataSize | \
DMA_InitStruct->MemoryOrM2MDstDataSize | \
DMA_InitStruct->Priority
);
if(DMA_InitStruct->FIFOMode != LL_DMA_FIFOMODE_DISABLE)
{
/*---------------------------- DMAx SxFCR Configuration ------------------------
* Configure DMAx_Streamy: fifo mode and fifo threshold with parameters :
* - FIFOMode: DMA_SxFCR_DMDIS bit
* - FIFOThreshold: DMA_SxFCR_FTH[1:0] bits
*/
LL_DMA_ConfigFifo(DMAx, Stream, DMA_InitStruct->FIFOMode, DMA_InitStruct->FIFOThreshold);
/*---------------------------- DMAx SxCR Configuration --------------------------
* Configure DMAx_Streamy: memory burst transfer with parameters :
* - MemBurst: DMA_SxCR_MBURST[1:0] bits
*/
LL_DMA_SetMemoryBurstxfer(DMAx,Stream,DMA_InitStruct->MemBurst);
/*---------------------------- DMAx SxCR Configuration --------------------------
* Configure DMAx_Streamy: peripheral burst transfer with parameters :
* - PeriphBurst: DMA_SxCR_PBURST[1:0] bits
*/
LL_DMA_SetPeriphBurstxfer(DMAx,Stream,DMA_InitStruct->PeriphBurst);
}
/*-------------------------- DMAx SxM0AR Configuration --------------------------
* Configure the memory or destination base address with parameter :
* - MemoryOrM2MDstAddress: DMA_SxM0AR_M0A[31:0] bits
*/
LL_DMA_SetMemoryAddress(DMAx, Stream, DMA_InitStruct->MemoryOrM2MDstAddress);
/*-------------------------- DMAx SxPAR Configuration ---------------------------
* Configure the peripheral or source base address with parameter :
* - PeriphOrM2MSrcAddress: DMA_SxPAR_PA[31:0] bits
*/
LL_DMA_SetPeriphAddress(DMAx, Stream, DMA_InitStruct->PeriphOrM2MSrcAddress);
/*--------------------------- DMAx SxNDTR Configuration -------------------------
* Configure the peripheral base address with parameter :
* - NbData: DMA_SxNDT[15:0] bits
*/
LL_DMA_SetDataLength(DMAx, Stream, DMA_InitStruct->NbData);
/*--------------------------- DMA SxCR_CHSEL Configuration ----------------------
* Configure the peripheral base address with parameter :
* - PeriphRequest: DMA_SxCR_CHSEL[2:0] bits
*/
LL_DMA_SetChannelSelection(DMAx, Stream, DMA_InitStruct->Channel);
return SUCCESS;
}
/**
* @brief Set each @ref LL_DMA_InitTypeDef field to default value.
* @param DMA_InitStruct Pointer to a @ref LL_DMA_InitTypeDef structure.
* @retval None
*/
void LL_DMA_StructInit(LL_DMA_InitTypeDef *DMA_InitStruct)
{
/* Set DMA_InitStruct fields to default values */
DMA_InitStruct->PeriphOrM2MSrcAddress = 0x00000000U;
DMA_InitStruct->MemoryOrM2MDstAddress = 0x00000000U;
DMA_InitStruct->Direction = LL_DMA_DIRECTION_PERIPH_TO_MEMORY;
DMA_InitStruct->Mode = LL_DMA_MODE_NORMAL;
DMA_InitStruct->PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT;
DMA_InitStruct->MemoryOrM2MDstIncMode = LL_DMA_MEMORY_NOINCREMENT;
DMA_InitStruct->PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_BYTE;
DMA_InitStruct->MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_BYTE;
DMA_InitStruct->NbData = 0x00000000U;
DMA_InitStruct->Channel = LL_DMA_CHANNEL_0;
DMA_InitStruct->Priority = LL_DMA_PRIORITY_LOW;
DMA_InitStruct->FIFOMode = LL_DMA_FIFOMODE_DISABLE;
DMA_InitStruct->FIFOThreshold = LL_DMA_FIFOTHRESHOLD_1_4;
DMA_InitStruct->MemBurst = LL_DMA_MBURST_SINGLE;
DMA_InitStruct->PeriphBurst = LL_DMA_PBURST_SINGLE;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* DMA1 || DMA2 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| andrzej-kaczmarek/apache-mynewt-core | hw/mcu/stm/stm32f4xx/src/ext/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_dma.c | C | apache-2.0 | 19,823 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//
// RethinkDBCursors-Private.h
// RethinkDbClient
//
// Created by Daniel Parnell on on 16/05/2015.
// Copyright (c) 2015 Daniel Parnell
//
// 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.
//
#ifndef RethinkDbClient_RethinkDBCursors_Private_h
#define RethinkDbClient_RethinkDBCursors_Private_h
#include "RethinkDbClient.h"
#import <ProtocolBuffers/ProtocolBuffers.h>
#import "Ql2.pb.h"
@interface RethinkDBCursor (Private)
- (instancetype)initWithClient:(RethinkDbClient*)aClient andToken:(int64_t)aToken;
- (BOOL) fetchNextBatch;
- (void) handleBatch;
@property (strong) Response *response;
@property (strong) NSArray *rows;
@end
#endif
| dparnell/rethink-db-client | RethinkDbClient/Internals/RethinkDBCursors-Private.h | C | mit | 1,683 | [
30522,
1013,
1013,
1013,
1013,
2128,
15222,
8950,
18939,
10841,
25301,
2869,
1011,
2797,
1012,
1044,
1013,
1013,
2128,
15222,
8950,
18939,
20464,
11638,
1013,
1013,
1013,
1013,
2580,
2011,
3817,
11968,
9091,
2006,
2006,
2385,
1013,
5709,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php namespace WebEd\Base\Criterias\Filter;
use Illuminate\Database\Eloquent\Builder;
use WebEd\Base\Models\Contracts\BaseModelContract;
use WebEd\Base\Models\EloquentBase;
use WebEd\Base\Repositories\Contracts\AbstractRepositoryContract;
use WebEd\Base\Criterias\AbstractCriteria;
class WithViewTracker extends AbstractCriteria
{
/**
* @var BaseModelContract
*/
protected $relatedModel;
/**
* @var string
*/
protected $screenName;
public function __construct(BaseModelContract $relatedModel, $screenName)
{
$this->relatedModel = $relatedModel;
$this->screenName = $screenName;
}
/**
* @param EloquentBase|Builder $model
* @param AbstractRepositoryContract $repository
* @return mixed
*/
public function apply($model, AbstractRepositoryContract $repository)
{
return $model
->leftJoin(webed_db_prefix() . 'view_trackers', $this->relatedModel->getTable() . '.' . $this->relatedModel->getPrimaryKey(), '=', webed_db_prefix() . 'view_trackers.entity_id')
->where(webed_db_prefix() . 'view_trackers.entity', '=', $this->screenName);
}
}
| sgsoft-studio/base | src/Criterias/Filter/WithViewTracker.php | PHP | mit | 1,172 | [
30522,
1026,
1029,
25718,
3415,
15327,
4773,
2098,
1032,
2918,
1032,
9181,
2015,
1032,
11307,
1025,
2224,
5665,
12717,
12556,
1032,
7809,
1032,
3449,
2080,
15417,
1032,
12508,
1025,
2224,
4773,
2098,
1032,
2918,
1032,
4275,
1032,
8311,
1032... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE html>
<html itemscope lang="en-us">
<head><meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="generator" content="Hugo 0.57.2" />
<meta property="og:title" content="Tom McLaughlin" />
<meta name="twitter:title" content="Tom McLaughlin"/>
<meta itemprop="name" content="Tom McLaughlin"><meta property="og:description" content="As the Community Engineer at CloudZero, Tom uses his experience in cloud infrastructure and systems development to develop and run serverless systems, and engage the engineering community on this coming technology. He loves exploring serverless architecture and AWS services because he feels this architecture paradigm will produce significant changes and have long lasting effects on cloud computing. When not at work he is a proud cat dad to two calicoes and enjoys spending his time drag racing and sailing." />
<meta name="twitter:description" content="As the Community Engineer at CloudZero, Tom uses his experience in cloud infrastructure and systems development to develop and run serverless systems, and engage the engineering community on this coming technology. He loves exploring serverless architecture and AWS services because he feels this architecture paradigm will produce significant changes and have long lasting effects on cloud computing. When not at work he is a proud cat dad to two calicoes and enjoys spending his time drag racing and sailing." />
<meta itemprop="description" content="As the Community Engineer at CloudZero, Tom uses his experience in cloud infrastructure and systems development to develop and run serverless systems, and engage the engineering community on this coming technology. He loves exploring serverless architecture and AWS services because he feels this architecture paradigm will produce significant changes and have long lasting effects on cloud computing. When not at work he is a proud cat dad to two calicoes and enjoys spending his time drag racing and sailing."><meta name="twitter:site" content="@devopsdays">
<meta property="og:type" content="speaker" />
<meta property="og:url" content="/events/2017-nashville/speakers/tom-mclaughlin/" /><meta name="twitter:creator" content="@nashvilledevops" /><meta name="twitter:label1" value="Event" />
<meta name="twitter:data1" value="devopsdays Nashville 2017" /><meta name="twitter:label2" value="Dates" />
<meta name="twitter:data2" value="October 17 - 18, 2017" /><meta property="og:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta itemprop="image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta property="fb:app_id" content="1904065206497317" /><meta itemprop="wordCount" content="89">
<title>Tom McLaughlin - devopsdays Nashville 2017
</title>
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-9713393-1', 'auto');
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<link href="/css/site.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet"><link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<link href="/events/index.xml" rel="alternate" type="application/rss+xml" title="DevOpsDays" />
<link href="/events/index.xml" rel="feed" type="application/rss+xml" title="DevOpsDays" />
<script src=/js/devopsdays-min.js></script></head>
<body lang="">
<nav class="navbar navbar-expand-md navbar-light">
<a class="navbar-brand" href="/">
<img src="/img/devopsdays-brain.png" height="30" class="d-inline-block align-top" alt="devopsdays Logo">
DevOpsDays
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto"><li class="nav-item global-navigation"><a class = "nav-link" href="/events">events</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/blog">blog</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/sponsor">sponsor</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/speaking">speaking</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/organizing">organizing</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/about">about</a></li></ul>
</div>
</nav>
<nav class="navbar event-navigation navbar-expand-md navbar-light">
<a href="/events/2017-nashville" class="nav-link">Nashville</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar2">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse" id="navbar2">
<ul class="navbar-nav"><li class="nav-item active">
<a class="nav-link" href="https://www.papercall.io/devopsdaysnash2017">propose</a>
</li><li class="nav-item active">
<a class="nav-link" href="/events/2017-nashville/location">location</a>
</li><li class="nav-item active">
<a class="nav-link" href="https://www.eventbrite.com/e/devopsdays-nashville-2017-tickets-34515535897">registration</a>
</li><li class="nav-item active">
<a class="nav-link" href="/events/2017-nashville/program">program</a>
</li><li class="nav-item active">
<a class="nav-link" href="/events/2017-nashville/speakers">speakers</a>
</li><li class="nav-item active">
<a class="nav-link" href="/events/2017-nashville/sponsor">sponsor</a>
</li><li class="nav-item active">
<a class="nav-link" href="/events/2017-nashville/contact">contact</a>
</li><li class="nav-item active">
<a class="nav-link" href="/events/2017-nashville/conduct">conduct</a>
</li></ul>
</div>
</nav>
<div class="container-fluid">
<div class="row">
<div class="col-md-12"><div class = "row">
<div class = "col-md-12 offset-md-1">
<h2 class="speaker-page">Tom McLaughlin</h2>
</div>
</div>
<div class = "row">
<div class = "col-md-4 offset-md-1">
<span class="speaker-page content-text">
<p>As the Community Engineer at CloudZero, Tom uses his experience in cloud infrastructure and systems development to develop and run serverless systems, and engage the engineering community on this coming technology. He loves exploring serverless architecture and AWS services because he feels this architecture paradigm will produce significant changes and have long lasting effects on cloud computing. When not at work he is a proud cat dad to two calicoes and enjoys spending his time drag racing and sailing. He is also an amateur thinkfluencer on Twitter at @tmclaughbos.</p>
</span>
<div class="speaker-bio-talks">
<h3>Tom McLaughlin at Nashville 2017</h3>
<ul class="list-group">
<a href = "https://www.devopsdays.org/events/2017-nashville/program/tom-mclaughlin/" class= "list-group-item list-group-item-action">Serverless Ops: What to do when the server goes away</a>
</ul>
</div>
</div>
<div class = "col-md-3 offset-md-1"><img src = "/events/2017-nashville/speakers/tom-mclaughlin.jpg" class="speaker-page" alt="Tom McLaughlin"/><br /><a href = "https://twitter.com/tmclaughbos"><i class="fa fa-twitter fa-2x" aria-hidden="true"></i></a></div>
</div>
<div class="row cta-row">
<div class="col-md-12"><h4 class="sponsor-cta">Gold Sponsors</h4><a href = "/events/2017-nashville/sponsor" class="sponsor-cta"><i>Join as Gold Sponsor!</i>
</a></div>
</div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.contino.io/"><img src = "/img/sponsors/contino.png" alt = "contino" title = "contino" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://data-blue.com/"><img src = "/img/sponsors/datablue.png" alt = "Data Blue" title = "Data Blue" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.dellemc.com"><img src = "/img/sponsors/dellemc.png" alt = "Dell EMC" title = "Dell EMC" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://influxdata.com"><img src = "/img/sponsors/influxdata-before-20171218.png" alt = "InfluxData" title = "InfluxData" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.microsoft.com/"><img src = "/img/sponsors/microsoft.png" alt = "Microsoft" title = "Microsoft" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.netapp.com/us/"><img src = "/img/sponsors/netapp.png" alt = "NetApp" title = "NetApp" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.pivotal.io"><img src = "/img/sponsors/pivotal-before-20190307.png" alt = "Pivotal" title = "Pivotal" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.purestorage.com"><img src = "/img/sponsors/pure-storage-before-20190114.png" alt = "Pure Storage" title = "Pure Storage" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.rubrik.com/product/why-rubrik/"><img src = "/img/sponsors/rubrik.png" alt = "Rubrik" title = "Rubrik" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://sjtechcorp.com/"><img src = "/img/sponsors/sjtechcorp.png" alt = "SJ Technologies, Inc." title = "SJ Technologies, Inc." class="img-fluid"></a>
</div></div><div class="row cta-row">
<div class="col-md-12"><h4 class="sponsor-cta">Silver Sponsors</h4><a href = "/events/2017-nashville/sponsor" class="sponsor-cta"><i>Join as Silver Sponsor!</i>
</a></div>
</div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.appdynamics.com/"><img src = "/img/sponsors/appdynamics-before-20180316.png" alt = "AppDynamics" title = "AppDynamics" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.changehealthcare.com"><img src = "/img/sponsors/changehealthcare.png" alt = "Change Healthcare" title = "Change Healthcare" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://chef.io"><img src = "/img/sponsors/chef.png" alt = "Chef Software, Inc" title = "Chef Software, Inc" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.dynatrace.com/"><img src = "/img/sponsors/dynatrace.png" alt = "Dynatrace" title = "Dynatrace" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.instana.com"><img src = "/img/sponsors/instana-before-20200127.png" alt = "Instana" title = "Instana" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://systemfrontier.com/"><img src = "/img/sponsors/systemfrontier.png" alt = "systemfrontier" title = "systemfrontier" class="img-fluid"></a>
</div></div><div class="row cta-row">
<div class="col-md-12"><h4 class="sponsor-cta">Bronze Sponsors</h4><a href = "/events/2017-nashville/sponsor" class="sponsor-cta"><i>Join as Bronze Sponsor!</i>
</a></div>
</div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://axialhealthcare.com/"><img src = "/img/sponsors/axialhealthcare.png" alt = "axialhealthcare" title = "axialhealthcare" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.cardinalsolutions.com/"><img src = "/img/sponsors/cardinalsolutions.png" alt = "Cardinal Solutions" title = "Cardinal Solutions" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.cbsinteractive.com/"><img src = "/img/sponsors/cbsinteractive.png" alt = "cbsinteractive" title = "cbsinteractive" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.eventbrite.com"><img src = "/img/sponsors/eventbrite.png" alt = "Eventbrite" title = "Eventbrite" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://mesosphere.com/"><img src = "/img/sponsors/mesosphere.png" alt = "Mesosphere" title = "Mesosphere" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.pluralsight.com/"><img src = "/img/sponsors/pluralsight.png" alt = "Pluralsight" title = "Pluralsight" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://shadow-soft.com"><img src = "/img/sponsors/shadow-soft.png" alt = "Shadow-Soft" title = "Shadow-Soft" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://stratasan.com"><img src = "/img/sponsors/stratasan.png" alt = "Stratasan" title = "Stratasan" class="img-fluid"></a>
</div></div><div class="row cta-row">
<div class="col-md-12"><h4 class="sponsor-cta">Alacarte Sponsors</h4><a href = "/events/2017-nashville/sponsor" class="sponsor-cta"><i>Join as Alacarte Sponsor!</i>
</a></div>
</div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.advizex.com"><img src = "/img/sponsors/advizex.png" alt = "AdvizeX" title = "AdvizeX" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://devopsinstitute.com/"><img src = "/img/sponsors/devops-institute.png" alt = "DevOps Institute" title = "DevOps Institute" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://cloud.google.com/"><img src = "/img/sponsors/gcp.png" alt = "gcp" title = "gcp" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.juiceanalytics.com/"><img src = "/img/sponsors/juiceanalytics.png" alt = "juiceanalytics" title = "juiceanalytics" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.roundtower.com/"><img src = "/img/sponsors/roundtowertechnologies.png" alt = "roundtowertechnologies" title = "roundtowertechnologies" class="img-fluid"></a>
</div></div><div class="row cta-row">
<div class="col-md-12"><h4 class="sponsor-cta">Community Sponsors</h4><a href = "/events/2017-nashville/sponsor" class="sponsor-cta"><i>Join as Community Sponsor!</i>
</a></div>
</div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.meetup.com/NashDevOps/"><img src = "/img/sponsors/nashdevops.png" alt = "NashDevOps" title = "NashDevOps" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://technologycouncil.com/"><img src = "/img/sponsors/ntc.png" alt = "Nashville Technology Council" title = "Nashville Technology Council" class="img-fluid"></a>
</div></div><br />
</div></div>
</div>
<nav class="navbar bottom navbar-light footer-nav-row" style="background-color: #bfbfc1;">
<div class = "row">
<div class = "col-md-12 footer-nav-background">
<div class = "row">
<div class = "col-md-6 col-lg-3 footer-nav-col">
<h3 class="footer-nav">@DEVOPSDAYS</h3>
<div>
<a class="twitter-timeline" data-dnt="true" href="https://twitter.com/devopsdays/lists/devopsdays" data-chrome="noheader" height="440"></a>
<script>
! function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
p = /^http:/.test(d.location) ? 'http' : 'https';
if (!d.getElementById(id)) {
js = d.createElement(s);
js.id = id;
js.src = p + "://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
}
}(document, "script", "twitter-wjs");
</script>
</div>
</div>
<div class="col-md-6 col-lg-3 footer-nav-col footer-content">
<h3 class="footer-nav">BLOG</h3><a href = "https://www.devopsdays.org/blog/2019/05/10/10-years-of-devopsdays/"><h1 class = "footer-heading">10 years of devopsdays</h1></a><h2 class="footer-heading">by Kris Buytaert - 10 May, 2019</h2><p class="footer-content">It’s hard to believe but it is almost 10 years ago since #devopsdays happened for the first time in Gent. Back then there were almost 70 of us talking about topics that were of interest to both Operations and Development, we were exchanging our ideas and experiences `on how we were improving the quality of software delivery.
Our ideas got started on the crossroads of Open Source, Agile and early Cloud Adoption.</p><a href = "https://www.devopsdays.org/blog/"><h1 class = "footer-heading">Blogs</h1></a><h2 class="footer-heading">10 May, 2019</h2><p class="footer-content"></p><a href="https://www.devopsdays.org/blog/index.xml">Feed</a>
</div>
<div class="col-md-6 col-lg-3 footer-nav-col">
<h3 class="footer-nav">CFP OPEN</h3><a href = "/events/2019-campinas" class = "footer-content">Campinas</a><br /><a href = "/events/2019-macapa" class = "footer-content">Macapá</a><br /><a href = "/events/2019-shanghai" class = "footer-content">Shanghai</a><br /><a href = "/events/2019-recife" class = "footer-content">Recife</a><br /><a href = "/events/2020-charlotte" class = "footer-content">Charlotte</a><br /><a href = "/events/2020-prague" class = "footer-content">Prague</a><br /><a href = "/events/2020-tokyo" class = "footer-content">Tokyo</a><br /><a href = "/events/2020-salt-lake-city" class = "footer-content">Salt Lake City</a><br />
<br />Propose a talk at an event near you!<br />
</div>
<div class="col-md-6 col-lg-3 footer-nav-col">
<h3 class="footer-nav">About</h3>
devopsdays is a worldwide community conference series for anyone interested in IT improvement.<br /><br />
<a href="/about/" class = "footer-content">About devopsdays</a><br />
<a href="/privacy/" class = "footer-content">Privacy Policy</a><br />
<a href="/conduct/" class = "footer-content">Code of Conduct</a>
<br />
<br />
<a href="https://www.netlify.com">
<img src="/img/netlify-light.png" alt="Deploys by Netlify">
</a>
</div>
</div>
</div>
</div>
</nav>
<script>
$(document).ready(function () {
$("#share").jsSocials({
shares: ["email", {share: "twitter", via: 'nashvilledevops'}, "facebook", "linkedin"],
text: 'devopsdays Nashville - 2017',
showLabel: false,
showCount: false
});
});
</script>
</body>
</html>
| gomex/devopsdays-web | static/events/2017-nashville/speakers/tom-mclaughlin/index.html | HTML | apache-2.0 | 21,675 | [
30522,
1026,
999,
9986,
13874,
16129,
1028,
1026,
16129,
5167,
16186,
11374,
1027,
1000,
4372,
1011,
2149,
1000,
1028,
1026,
2132,
1028,
1026,
18804,
8299,
1011,
1041,
15549,
2615,
1027,
1000,
1060,
1011,
25423,
1011,
11892,
1000,
4180,
102... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package uk.co.vurt.hakken.security.auth;
/**
* Test authenticator that does not rely on any external infrastructure
*
* User will always be authenticated, regardless of credentials passed.
*
*/
public class AllowAlwaysAuthenticator implements Authenticator {
public boolean authenticate(String username, String password) {
return true;
}
public String getErrorMessage() {
return null;
}
}
| gilesp/taskhelper | hakken-server/src/main/java/uk/co/vurt/hakken/security/auth/AllowAlwaysAuthenticator.java | Java | apache-2.0 | 407 | [
30522,
7427,
2866,
1012,
2522,
1012,
24728,
5339,
1012,
5292,
24192,
1012,
3036,
1012,
8740,
2705,
1025,
1013,
1008,
1008,
1008,
3231,
14469,
8844,
2008,
2515,
2025,
11160,
2006,
2151,
6327,
6502,
1008,
1008,
5310,
2097,
2467,
2022,
14469,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
## chrisfinazzo.com
[](https://app.netlify.com/sites/relaxed-meninsky-6eca95/deploys)
My personal website, powered by Jekyll and Netlify
| chrisfinazzo/chrisfinazzo.com | README.md | Markdown | mit | 246 | [
30522,
1001,
1001,
3782,
16294,
10936,
6844,
1012,
4012,
1031,
999,
1031,
5658,
3669,
12031,
3570,
1033,
1006,
16770,
1024,
1013,
1013,
17928,
1012,
5658,
3669,
12031,
1012,
4012,
1013,
17928,
1013,
1058,
2487,
1013,
23433,
1013,
2676,
2546... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package main
import (
"strings"
"time"
"github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/cli"
"github.com/go-check/check"
"github.com/gotestyourself/gotestyourself/icmd"
)
func (s *DockerSuite) TestUpdateRestartPolicy(c *check.C) {
out := cli.DockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "sh", "-c", "sleep 1 && false").Combined()
timeout := 60 * time.Second
if testEnv.DaemonPlatform() == "windows" {
timeout = 180 * time.Second
}
id := strings.TrimSpace(string(out))
// update restart policy to on-failure:5
cli.DockerCmd(c, "update", "--restart=on-failure:5", id)
cli.WaitExited(c, id, timeout)
count := inspectField(c, id, "RestartCount")
c.Assert(count, checker.Equals, "5")
maximumRetryCount := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount")
c.Assert(maximumRetryCount, checker.Equals, "5")
}
func (s *DockerSuite) TestUpdateRestartWithAutoRemoveFlag(c *check.C) {
out := runSleepingContainer(c, "--rm")
id := strings.TrimSpace(out)
// update restart policy for an AutoRemove container
cli.Docker(cli.Args("update", "--restart=always", id)).Assert(c, icmd.Expected{
ExitCode: 1,
Err: "Restart policy cannot be updated because AutoRemove is enabled for the container",
})
}
| diegobernardes/flare | vendor/github.com/docker/docker/integration-cli/docker_cli_update_test.go | GO | bsd-3-clause | 1,303 | [
30522,
7427,
2364,
12324,
1006,
1000,
7817,
1000,
1000,
2051,
1000,
1000,
21025,
2705,
12083,
1012,
4012,
1013,
8946,
2121,
1013,
8946,
2121,
1013,
8346,
1011,
18856,
2072,
1013,
4638,
2121,
1000,
1000,
21025,
2705,
12083,
1012,
4012,
1013,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Multiple Languages</title>
<!-- Ext -->
<script type="text/javascript" src="../../examples/shared/include-ext.js"></script>
<script type="text/javascript" src="../../examples/shared/options-toolbar.js"></script>
<script type="text/javascript" src="languages.js"></script>
<link rel="stylesheet" type="text/css" href="../shared/example.css" />
<!-- GC -->
<script type="text/javascript" src="../shared/examples.js"></script>
<script type="text/javascript" src="multi-lang.js"></script>
</head>
<body class="x-gray">
<h1>Localization with Extjs</h1>
<p>
This demonstrates multiple language with some of the Ext components.<br/>
Select a language from the combobox below (default is english) and try out the components in different languages.
</p>
<p>The js is not minified so it is readable. See <a href="multi-lang.js">multi-lang.js</a>.</p>
<div>
<div style="float:left;padding:3px 5px 0 0;">Language selector: </div>
<div id="languages" style="float:left;"></div>
</div>
<br/><br/>
<h2>Email Field</h2>
<div id="emailfield"></div>
<br/>
<h2>Datepicker</h2>
<div id="datefield"></div>
<br/>
<h2>Grid</h2>
<div id="grid"></div>
</body>
</html>
| rch/flask-openshift | wsgi/container/pkgs/sencha/static/ext-4.2.2.1144/examples/locale/multi-lang.html | HTML | mit | 1,453 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
16129,
1018,
1012,
5890,
1013,
1013,
4372,
1000,
1000,
8299,
1024,
1013,
1013,
7479,
1012,
1059,
2509,
1012,
8917,
1013,
19817,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015 by PyCLibrary Authors, see AUTHORS for more details.
#
# Distributed under the terms of the MIT/X11 license.
#
# The full license is in the file LICENCE, distributed with this software.
# -----------------------------------------------------------------------------
"""
Used for extracting data such as macro definitions, variables, typedefs, and
function signatures from C header files.
"""
from __future__ import (division, unicode_literals, print_function,
absolute_import)
import sys
import re
import os
import logging
from inspect import cleandoc
from future.utils import istext, isbytes
from ast import literal_eval
from traceback import format_exc
from .errors import DefinitionError
from .utils import find_header
# Import parsing elements
from .thirdparty.pyparsing import \
(ParserElement, ParseResults, Forward, Optional, Word, WordStart,
WordEnd, Keyword, Regex, Literal, SkipTo, ZeroOrMore, OneOrMore,
Group, LineEnd, stringStart, quotedString, oneOf, nestedExpr,
delimitedList, restOfLine, cStyleComment, alphas, alphanums, hexnums,
lineno, Suppress)
ParserElement.enablePackrat()
logger = logging.getLogger(__name__)
__all__ = ['win_defs', 'CParser']
class Type(tuple):
"""
Representation of a C type. CParser uses this class to store the parsed
typedefs and the types of variable/func.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from tuple and can be seen as the tuples from 0.1.0. In future this might
change to a tuple-like object!!!
Parameters
----------
type_spec : str
a string referring the base type of this type defintion. This may
either be a fundametal type (i.e. 'int', 'enum x') or a type definition
made by a typedef-statement
declarators : str or list of tuple
all following parameters are deriving a type from the type defined
until now. Types can be derived by:
- The string '*': define a pointer to the base type
(i.E. Type('int', '*'))
- The string '&': a reference. T.B.D.
- A list of integers of len 1: define an array with N elements
(N is the first and single entry in the list of integers). If N is
-1, the array definition is seen as 'int x[]'
(i.E. Type('int', [1])
- a N-tuple of 3-tuples: defines a function of N parameters. Every
parameter is a 3 tuple of the form:
(<parameter-name-or-None>, <param-type>, None).
Due to compatibility reasons the return value of the function is
stored in Type.type_spec parameter
(This is **not** the case for function pointers):
(i.E. Type(Type('int', '*'), ( ('param1', Type('int'), None), ) ) )
type_quals : dict of int to list of str (optional)
this optional (keyword-)argument allows to optionally add type
qualifiers for every declarator level. The key 0 refers the type
qualifier of type_spec, while 1 refers to declarators[0], 2 refers to
declarators[1] and so on.
To build more complex types any number of declarators can be combined. i.E.
>>> int * (*a[2])(char *, signed c[]);
if represented as:
>>> Type('int', '*',
>>> ( (None, Type('char', '*'), None),
>>> ('c', Type('signed', [-1]), None) )),
>>> '*', [2])
"""
# Cannot slot a subclass of tuple.
def __new__(cls, type_spec, *declarators, **argv):
return super(Type, cls).__new__(cls, (type_spec,) + declarators)
def __init__(self, type_spec, *declarators, **argv):
super(Type, self).__init__()
self.type_quals = (argv.pop('type_quals', None) or
((),) * (1 + len(declarators)))
if len(self.type_quals) != 1 + len(declarators):
raise ValueError("wrong number of type qualifiers")
assert len(argv) == 0, 'Invalid Parameter'
def __eq__(self, other):
if isinstance(other, Type):
if self.type_quals != other.type_quals:
return False
return super(Type, self).__eq__(other)
def __ne__(self, other):
return not self.__eq__(other)
@property
def declarators(self):
"""Return a tuple of all declarators.
"""
return tuple(self[1:])
@property
def type_spec(self):
"""Return the base type of this type.
"""
return self[0]
def is_fund_type(self):
"""Returns True, if this type is a fundamental type.
Fundamental types are all types, that are not defined via typedef
"""
if (self[0].startswith('struct ') or self[0].startswith('union ') or
self[0].startswith('enum ')):
return True
names = (num_types + nonnum_types + size_modifiers + sign_modifiers +
extra_type_list)
for w in self[0].split():
if w not in names:
return False
return True
def eval(self, type_map, used=None):
"""Resolves the type_spec of this type recursively if it is referring
to a typedef. For resolving the type type_map is used for lookup.
Returns a new Type object.
Parameters
----------
type_map : dict of str to Type
All typedefs that shall be resolved have to be stored in this
type_map.
used : list of str
For internal use only to prevent circular typedefs
"""
used = used or []
if self.is_fund_type():
# Remove 'signed' before returning evaluated type
return Type(re.sub(r'\bsigned\b', '', self.type_spec).strip(),
*self.declarators,
type_quals=self.type_quals)
parent = self.type_spec
if parent in used:
m = 'Recursive loop while evaluating types. (typedefs are {})'
raise DefinitionError(m.format(' -> '.join(used+[parent])))
used.append(parent)
if parent not in type_map:
m = 'Unknown type "{}" (typedefs are {})'
raise DefinitionError(m.format(parent, ' -> '.join(used)))
pt = type_map[parent]
evaled_type = Type(pt.type_spec, *(pt.declarators + self.declarators),
type_quals=(pt.type_quals[:-1] +
(pt.type_quals[-1] +
self.type_quals[0],) +
self.type_quals[1:])
)
return evaled_type.eval(type_map, used)
def add_compatibility_hack(self):
"""If This Type is refering to a function (**not** a function pointer)
a new type is returned, that matches the hack from version 0.1.0.
This hack enforces the return value be encapsulated in a separated Type
object:
Type('int', '*', ())
is converted to
Type(Type('int', '*'), ())
"""
if type(self[-1]) == tuple:
return Type(Type(*self[:-1], type_quals=self.type_quals[:-1]),
self[-1],
type_quals=((), self.type_quals[-1]))
else:
return self
def remove_compatibility_hack(self):
"""Returns a Type object, where the hack from .add_compatibility_hack()
is removed
"""
if len(self) == 2 and isinstance(self[0], Type):
return Type(*(self[0] + (self[1],)))
else:
return self
def __repr__(self):
type_qual_str = ('' if not any(self.type_quals) else
', type_quals='+repr(self.type_quals))
return (type(self).__name__ + '(' +
', '.join(map(repr, self)) + type_qual_str + ')')
class Compound(dict):
"""Base class for representing object using a dict-like interface.
"""
__slots__ = ()
def __init__(self, *members, **argv):
members = list(members)
pack = argv.pop('pack', None)
assert len(argv) == 0
super(Compound, self).__init__(dict(members=members, pack=pack))
def __repr__(self):
packParam = ', pack='+repr(self.pack) if self.pack is not None else ''
return (type(self).__name__ + '(' +
', '.join(map(repr, self.members)) + packParam + ')')
@property
def members(self):
return self['members']
@property
def pack(self):
return self['pack']
class Struct(Compound):
"""Representation of a C struct. CParser uses this class to store the parsed
structs.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from dict and can be seen as the dicts from 0.1.0. In future this might
change to a dict-like object!!!
"""
__slots__ = ()
class Union(Compound):
"""Representation of a C union. CParser uses this class to store the parsed
unions.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from dict and can be seen as the dicts from 0.1.0. In future this might
change to a dict-like object!!!
"""
__slots__ = ()
class Enum(dict):
"""Representation of a C enum. CParser uses this class to store the parsed
enums.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from dict and can be seen as the dicts from 0.1.0. In future this might
change to a dict-like object!!!
"""
__slots__ = ()
def __init__(self, **args):
super(Enum, self).__init__(args)
def __repr__(self):
return (type(self).__name__ + '(' +
', '.join(nm + '=' + repr(val)
for nm, val in sorted(self.items())) +
')')
def win_defs(version='800'):
"""Loads selection of windows headers included with PyCLibrary.
These definitions can either be accessed directly or included before
parsing another file like this:
>>> windefs = c_parser.win_defs()
>>> p = c_parser.CParser("headerFile.h", copy_from=windefs)
Definitions are pulled from a selection of header files included in Visual
Studio (possibly not legal to distribute? Who knows.), some of which have
been abridged because they take so long to parse.
Parameters
----------
version : unicode
Version of the MSVC to consider when parsing.
Returns
-------
parser : CParser
CParser containing all the infos from te windows headers.
"""
header_files = ['WinNt.h', 'WinDef.h', 'WinBase.h', 'BaseTsd.h',
'WTypes.h', 'WinUser.h']
if not CParser._init:
logger.warning('Automatic initialisation : OS is assumed to be win32')
from .init import auto_init
auto_init('win32')
d = os.path.dirname(__file__)
p = CParser(
[os.path.join(d, 'headers', h) for h in header_files],
macros={'_WIN32': '', '_MSC_VER': version, 'CONST': 'const',
'NO_STRICT': None, 'MS_WIN32': ''},
process_all=False
)
p.process_all(cache=os.path.join(d, 'headers', 'WinDefs.cache'))
return p
class CParser(object):
"""Class for parsing C code to extract variable, struct, enum, and function
declarations as well as preprocessor macros.
This is not a complete C parser; instead, it is meant to simplify the
process of extracting definitions from header files in the absence of a
complete build system. Many files will require some amount of manual
intervention to parse properly (see 'replace' and extra arguments)
Parameters
----------
files : str or iterable, optional
File or files which should be parsed.
copy_from : CParser or iterable of CParser, optional
CParser whose definitions should be included.
replace : dict, optional
Specify som string replacements to perform before parsing. Format is
{'searchStr': 'replaceStr', ...}
process_all : bool, optional
Flag indicating whether files should be parsed immediatly. True by
default.
cache : unicode, optional
Path of the cache file from which to load definitions/to which save
definitions as parsing is an expensive operation.
kwargs :
Extra parameters may be used to specify the starting state of the
parser. For example, one could provide a set of missing type
declarations by types={'UINT': ('unsigned int'), 'STRING': ('char', 1)}
Similarly, preprocessor macros can be specified: macros={'WINAPI': ''}
Example
-------
Create parser object, load two files
>>> p = CParser(['header1.h', 'header2.h'])
Remove comments, preprocess, and search for declarations
>>> p.process_ all()
Just to see what was successfully parsed from the files
>>> p.print_all()
Access parsed declarations
>>> all_values = p.defs['values']
>>> functionSignatures = p.defs['functions']
To see what was not successfully parsed
>>> unp = p.process_all(return_unparsed=True)
>>> for s in unp:
print s
"""
#: Increment every time cache structure or parsing changes to invalidate
#: old cache files.
cache_version = 1
#: Private flag allowing to know if the parser has been initiliased.
_init = False
def __init__(self, files=None, copy_from=None, replace=None,
process_all=True, cache=None, **kwargs):
if not self._init:
logger.warning('Automatic initialisation based on OS detection')
from .init import auto_init
auto_init()
# Holds all definitions
self.defs = {}
# Holds definitions grouped by the file they came from
self.file_defs = {}
# Description of the struct packing rules as defined by #pragma pack
self.pack_list = {}
self.init_opts = kwargs.copy()
self.init_opts['files'] = []
self.init_opts['replace'] = {}
self.data_list = ['types', 'variables', 'fnmacros', 'macros',
'structs', 'unions', 'enums', 'functions', 'values']
self.file_order = []
self.files = {}
if files is not None:
if istext(files) or isbytes(files):
files = [files]
for f in self.find_headers(files):
self.load_file(f, replace)
# Initialize empty definition lists
for k in self.data_list:
self.defs[k] = {}
# Holds translations from typedefs/structs/unions to fundamental types
self.compiled_types = {}
self.current_file = None
# Import extra arguments if specified
for t in kwargs:
for k in kwargs[t].keys():
self.add_def(t, k, kwargs[t][k])
# Import from other CParsers if specified
if copy_from is not None:
if not isinstance(copy_from, (list, tuple)):
copy_from = [copy_from]
for p in copy_from:
self.import_dict(p.file_defs)
if process_all:
self.process_all(cache=cache)
def process_all(self, cache=None, return_unparsed=False,
print_after_preprocess=False):
""" Remove comments, preprocess, and parse declarations from all files.
This operates in memory, and thus does not alter the original files.
Parameters
----------
cache : unicode, optional
File path where cached results are be stored or retrieved. The
cache is automatically invalidated if any of the arguments to
__init__ are changed, or if the C files are newer than the cache.
return_unparsed : bool, optional
Passed directly to parse_defs.
print_after_preprocess : bool, optional
If true prints the result of preprocessing each file.
Returns
-------
results : list
List of the results from parse_defs.
"""
if cache is not None and self.load_cache(cache, check_validity=True):
logger.debug("Loaded cached definitions; will skip parsing.")
# Cached values loaded successfully, nothing left to do here
return
results = []
logger.debug(cleandoc('''Parsing C header files (no valid cache found).
This could take several minutes...'''))
for f in self.file_order:
if self.files[f] is None:
# This means the file could not be loaded and there was no
# cache.
mess = 'Could not find header file "{}" or a cache file.'
raise IOError(mess.format(f))
logger.debug("Removing comments from file '{}'...".format(f))
self.remove_comments(f)
logger.debug("Preprocessing file '{}'...".format(f))
self.preprocess(f)
if print_after_preprocess:
print("===== PREPROCSSED {} =======".format(f))
print(self.files[f])
logger.debug("Parsing definitions in file '{}'...".format(f))
results.append(self.parse_defs(f, return_unparsed))
if cache is not None:
logger.debug("Writing cache file '{}'".format(cache))
self.write_cache(cache)
return results
def load_cache(self, cache_file, check_validity=False):
"""Load a cache file.
Used internally if cache is specified in process_all().
Parameters
----------
cache_file : unicode
Path of the file from which the cache should be loaded.
check_validity : bool, optional
If True, then run several checks before loading the cache:
- cache file must not be older than any source files
- cache file must not be older than this library file
- options recorded in cache must match options used to initialize
CParser
Returns
-------
result : bool
Did the loading succeeded.
"""
# Make sure cache file exists
if not istext(cache_file):
raise ValueError("Cache file option must be a unicode.")
if not os.path.isfile(cache_file):
# If file doesn't exist, search for it in this module's path
d = os.path.dirname(__file__)
cache_file = os.path.join(d, "headers", cache_file)
if not os.path.isfile(cache_file):
logger.debug("Can't find requested cache file.")
return False
# Make sure cache is newer than all input files
if check_validity:
mtime = os.stat(cache_file).st_mtime
for f in self.file_order:
# If file does not exist, then it does not count against the
# validity of the cache.
if os.path.isfile(f) and os.stat(f).st_mtime > mtime:
logger.debug("Cache file is out of date.")
return False
try:
# Read cache file
import pickle
cache = pickle.load(open(cache_file, 'rb'))
# Make sure __init__ options match
if check_validity:
if cache['opts'] != self.init_opts:
db = logger.debug
db("Cache file is not valid")
db("It was created using different initialization options")
db('{}'.format(cache['opts']))
db('{}'.format(self.init_opts))
return False
else:
logger.debug("Cache init opts are OK:")
logger.debug('{}'.format(cache['opts']))
if cache['version'] < self.cache_version:
mess = "Cache file is not valid--cache format has changed."
logger.debug(mess)
return False
# Import all parse results
self.import_dict(cache['file_defs'])
return True
except Exception:
logger.exception("Warning--cache read failed:")
return False
def import_dict(self, data):
"""Import definitions from a dictionary.
The dict format should be the same as CParser.file_defs.
Used internally; does not need to be called manually.
"""
for f in data.keys():
self.current_file = f
for k in self.data_list:
for n in data[f][k]:
self.add_def(k, n, data[f][k][n])
def write_cache(self, cache_file):
"""Store all parsed declarations to cache. Used internally.
"""
cache = {}
cache['opts'] = self.init_opts
cache['file_defs'] = self.file_defs
cache['version'] = self.cache_version
import pickle
pickle.dump(cache, open(cache_file, 'wb'))
def find_headers(self, headers):
"""Try to find the specified headers.
"""
hs = []
for header in headers:
if os.path.isfile(header):
hs.append(header)
else:
h = find_header(header)
if not h:
raise OSError('Cannot find header: {}'.format(header))
hs.append(h)
return hs
def load_file(self, path, replace=None):
"""Read a file, make replacements if requested.
Called by __init__, should not be called manually.
Parameters
----------
path : unicode
Path of the file to load.
replace : dict, optional
Dictionary containing strings to replace by the associated value
when loading the file.
"""
if not os.path.isfile(path):
# Not a fatal error since we might be able to function properly if
# there is a cache file.
mess = "Warning: C header '{}' is missing, this may cause trouble."
logger.warning(mess.format(path))
self.files[path] = None
return False
# U causes all newline types to be converted to \n
with open(path, 'rU') as fd:
self.files[path] = fd.read()
if replace is not None:
for s in replace:
self.files[path] = re.sub(s, replace[s], self.files[path])
self.file_order.append(path)
bn = os.path.basename(path)
self.init_opts['replace'][bn] = replace
# Only interested in the file names, the directory may change between
# systems.
self.init_opts['files'].append(bn)
return True
def print_all(self, filename=None):
"""Print everything parsed from files. Useful for debugging.
Parameters
----------
filename : unicode, optional
Name of the file whose definition should be printed.
"""
from pprint import pprint
for k in self.data_list:
print("============== {} ==================".format(k))
if filename is None:
pprint(self.defs[k])
else:
pprint(self.file_defs[filename][k])
# =========================================================================
# --- Processing functions
# =========================================================================
def remove_comments(self, path):
"""Remove all comments from file.
Operates in memory, does not alter the original files.
"""
text = self.files[path]
cplusplus_line_comment = Literal("//") + restOfLine
# match quoted strings first to prevent matching comments inside quotes
comment_remover = (quotedString | cStyleComment.suppress() |
cplusplus_line_comment.suppress())
self.files[path] = comment_remover.transformString(text)
# --- Pre processing
def preprocess(self, path):
"""Scan named file for preprocessor directives, removing them while
expanding macros.
Operates in memory, does not alter the original files.
Currently support :
- conditionals : ifdef, ifndef, if, elif, else (defined can be used
in a if statement).
- definition : define, undef
- pragmas : pragma
"""
# We need this so that eval_expr works properly
self.build_parser()
self.current_file = path
# Stack for #pragma pack push/pop
pack_stack = [(None, None)]
self.pack_list[path] = [(0, None)]
packing = None # Current packing value
text = self.files[path]
# First join together lines split by \\n
text = Literal('\\\n').suppress().transformString(text)
# Define the structure of a macro definition
name = Word(alphas+'_', alphanums+'_')('name')
deli_list = Optional(lparen + delimitedList(name) + rparen)
self.pp_define = (name.setWhitespaceChars(' \t')("macro") +
deli_list.setWhitespaceChars(' \t')('args') +
SkipTo(LineEnd())('value'))
self.pp_define.setParseAction(self.process_macro_defn)
# Comb through lines, process all directives
lines = text.split('\n')
result = []
directive = re.compile(r'\s*#\s*([a-zA-Z]+)(.*)$')
if_true = [True]
if_hit = []
for i, line in enumerate(lines):
new_line = ''
m = directive.match(line)
# Regular code line
if m is None:
# Only include if we are inside the correct section of an IF
# block
if if_true[-1]:
new_line = self.expand_macros(line)
# Macro line
else:
d = m.groups()[0]
rest = m.groups()[1]
if d == 'ifdef':
d = 'if'
rest = 'defined ' + rest
elif d == 'ifndef':
d = 'if'
rest = '!defined ' + rest
# Evaluate 'defined' operator before expanding macros
if d in ['if', 'elif']:
def pa(t):
is_macro = t['name'] in self.defs['macros']
is_macro_func = t['name'] in self.defs['fnmacros']
return ['0', '1'][is_macro or is_macro_func]
rest = (Keyword('defined') +
(name | lparen + name + rparen)
).setParseAction(pa).transformString(rest)
elif d in ['define', 'undef']:
match = re.match(r'\s*([a-zA-Z_][a-zA-Z0-9_]*)(.*)$', rest)
macroName, rest = match.groups()
# Expand macros if needed
if rest is not None and (all(if_true) or d in ['if', 'elif']):
rest = self.expand_macros(rest)
if d == 'elif':
if if_hit[-1] or not all(if_true[:-1]):
ev = False
else:
ev = self.eval_preprocessor_expr(rest)
logger.debug(" "*(len(if_true)-2) + line +
'{}, {}'.format(rest, ev))
if_true[-1] = ev
if_hit[-1] = if_hit[-1] or ev
elif d == 'else':
logger.debug(" "*(len(if_true)-2) + line +
'{}'.format(not if_hit[-1]))
if_true[-1] = (not if_hit[-1]) and all(if_true[:-1])
if_hit[-1] = True
elif d == 'endif':
if_true.pop()
if_hit.pop()
logger.debug(" "*(len(if_true)-1) + line)
elif d == 'if':
if all(if_true):
ev = self.eval_preprocessor_expr(rest)
else:
ev = False
logger.debug(" "*(len(if_true)-1) + line +
'{}, {}'.format(rest, ev))
if_true.append(ev)
if_hit.append(ev)
elif d == 'define':
if not if_true[-1]:
continue
logger.debug(" "*(len(if_true)-1) + "define: " +
'{}, {}'.format(macroName, rest))
try:
# Macro is registered here
self.pp_define.parseString(macroName + ' ' + rest)
except Exception:
logger.exception("Error processing macro definition:" +
'{}, {}'.format(macroName, rest))
elif d == 'undef':
if not if_true[-1]:
continue
try:
self.rem_def('macros', macroName.strip())
except Exception:
if sys.exc_info()[0] is not KeyError:
mess = "Error removing macro definition '{}'"
logger.exception(mess.format(macroName.strip()))
# Check for changes in structure packing
# Support only for #pragme pack (with all its variants
# save show), None is used to signal that the default packing
# is used.
# Those two definition disagree :
# https://gcc.gnu.org/onlinedocs/gcc/Structure-Packing-Pragmas.html
# http://msdn.microsoft.com/fr-fr/library/2e70t5y1.aspx
# The current implementation follows the MSVC doc.
elif d == 'pragma':
if not if_true[-1]:
continue
m = re.match(r'\s+pack\s*\(([^\)]*)\)', rest)
if not m:
continue
if m.groups():
opts = [s.strip() for s in m.groups()[0].split(',')]
pushpop = id = val = None
for o in opts:
if o in ['push', 'pop']:
pushpop = o
elif o.isdigit():
val = int(o)
else:
id = o
packing = val
if pushpop == 'push':
pack_stack.append((packing, id))
elif opts[0] == 'pop':
if id is None:
pack_stack.pop()
else:
ind = None
for j, s in enumerate(pack_stack):
if s[1] == id:
ind = j
break
if ind is not None:
pack_stack = pack_stack[:ind]
if val is None:
packing = pack_stack[-1][0]
mess = ">> Packing changed to {} at line {}"
logger.debug(mess.format(str(packing), i))
self.pack_list[path].append((i, packing))
else:
# Ignore any other directives
mess = 'Ignored directive {} at line {}'
logger.debug(mess.format(d, i))
result.append(new_line)
self.files[path] = '\n'.join(result)
def eval_preprocessor_expr(self, expr):
# Make a few alterations so the expression can be eval'd
macro_diffs = (
Literal('!').setParseAction(lambda: ' not ') |
Literal('&&').setParseAction(lambda: ' and ') |
Literal('||').setParseAction(lambda: ' or ') |
Word(alphas + '_', alphanums + '_').setParseAction(lambda: '0'))
expr2 = macro_diffs.transformString(expr).strip()
try:
ev = bool(eval(expr2))
except Exception:
mess = "Error evaluating preprocessor expression: {} [{}]\n{}"
logger.debug(mess.format(expr, repr(expr2), format_exc()))
ev = False
return ev
def process_macro_defn(self, t):
"""Parse a #define macro and register the definition.
"""
logger.debug("Processing MACRO: {}".format(t))
macro_val = t.value.strip()
if macro_val in self.defs['fnmacros']:
self.add_def('fnmacros', t.macro, self.defs['fnmacros'][macro_val])
logger.debug(" Copy fn macro {} => {}".format(macro_val, t.macro))
else:
if t.args == '':
val = self.eval_expr(macro_val)
self.add_def('macros', t.macro, macro_val)
self.add_def('values', t.macro, val)
mess = " Add macro: {} ({}); {}"
logger.debug(mess.format(t.macro, val,
self.defs['macros'][t.macro]))
else:
self.add_def('fnmacros', t.macro,
self.compile_fn_macro(macro_val,
[x for x in t.args]))
mess = " Add fn macro: {} ({}); {}"
logger.debug(mess.format(t.macro, t.args,
self.defs['fnmacros'][t.macro]))
return "#define " + t.macro + " " + macro_val
def compile_fn_macro(self, text, args):
"""Turn a function macro spec into a compiled description.
"""
# Find all instances of each arg in text.
args_str = '|'.join(args)
arg_regex = re.compile(r'("(\\"|[^"])*")|(\b({})\b)'.format(args_str))
start = 0
parts = []
arg_order = []
# The group number to check for macro names
N = 3
for m in arg_regex.finditer(text):
arg = m.groups()[N]
if arg is not None:
parts.append(text[start:m.start(N)] + '{}')
start = m.end(N)
arg_order.append(args.index(arg))
parts.append(text[start:])
return (''.join(parts), arg_order)
def expand_macros(self, line):
"""Expand all the macro expressions in a string.
Faulty calls to macro function are left untouched.
"""
reg = re.compile(r'("(\\"|[^"])*")|(\b(\w+)\b)')
parts = []
# The group number to check for macro names
N = 3
macros = self.defs['macros']
fnmacros = self.defs['fnmacros']
while True:
m = reg.search(line)
if not m:
break
name = m.groups()[N]
if name in macros:
parts.append(line[:m.start(N)])
line = line[m.end(N):]
parts.append(macros[name])
elif name in fnmacros:
# If function macro expansion fails, just ignore it.
try:
exp, end = self.expand_fn_macro(name, line[m.end(N):])
except Exception:
exp = name
end = 0
mess = "Function macro expansion failed: {}, {}"
logger.error(mess.format(name, line[m.end(N):]))
parts.append(line[:m.start(N)])
start = end + m.end(N)
line = line[start:]
parts.append(exp)
else:
start = m.end(N)
parts.append(line[:start])
line = line[start:]
parts.append(line)
return ''.join(parts)
def expand_fn_macro(self, name, text):
"""Replace a function macro.
"""
# defn looks like ('%s + %s / %s', (0, 0, 1))
defn = self.defs['fnmacros'][name]
arg_list = (stringStart + lparen +
Group(delimitedList(expression))('args') + rparen)
res = [x for x in arg_list.scanString(text, 1)]
if len(res) == 0:
mess = "Function macro '{}' not followed by (...)"
raise DefinitionError(0, mess.format(name))
args, start, end = res[0]
args = [self.expand_macros(arg) for arg in args[0]]
new_str = defn[0].format(*[args[i] for i in defn[1]])
return (new_str, end)
# --- Compilation functions
def parse_defs(self, path, return_unparsed=False):
"""Scan through the named file for variable, struct, enum, and function
declarations.
Parameters
----------
path : unicode
Path of the file to parse for definitions.
return_unparsed : bool, optional
If true, return a string of all lines that failed to match (for
debugging purposes).
Returns
-------
tokens : list
Entire tree of successfully parsed tokens.
"""
self.current_file = path
parser = self.build_parser()
if return_unparsed:
text = parser.suppress().transformString(self.files[path])
return re.sub(r'\n\s*\n', '\n', text)
else:
return [x[0] for x in parser.scanString(self.files[path])]
def build_parser(self):
"""Builds the entire tree of parser elements for the C language (the
bits we support, anyway).
"""
if hasattr(self, 'parser'):
return self.parser
self.struct_type = Forward()
self.enum_type = Forward()
type_ = (fund_type |
Optional(kwl(size_modifiers + sign_modifiers)) + ident |
self.struct_type |
self.enum_type)
if extra_modifier is not None:
type_ += extra_modifier
type_.setParseAction(recombine)
self.type_spec = (type_qualifier('pre_qual') +
type_("name"))
# --- Abstract declarators for use in function pointer arguments
# Thus begins the extremely hairy business of parsing C declarators.
# Whomever decided this was a reasonable syntax should probably never
# breed.
# The following parsers combined with the process_declarator function
# allow us to turn a nest of type modifiers into a correctly
# ordered list of modifiers.
self.declarator = Forward()
self.abstract_declarator = Forward()
# Abstract declarators look like:
# <empty string>
# *
# **[num]
# (*)(int, int)
# *( )(int, int)[10]
# ...etc...
self.abstract_declarator << Group(
type_qualifier('first_typequal') +
Group(ZeroOrMore(Group(Suppress('*') + type_qualifier)))('ptrs') +
((Optional('&')('ref')) |
(lparen + self.abstract_declarator + rparen)('center')) +
Optional(lparen +
Optional(delimitedList(Group(
self.type_spec('type') +
self.abstract_declarator('decl') +
Optional(Literal('=').suppress() + expression,
default=None)('val')
)), default=None) +
rparen)('args') +
Group(ZeroOrMore(lbrack + Optional(expression, default='-1') +
rbrack))('arrays')
)
# Declarators look like:
# varName
# *varName
# **varName[num]
# (*fnName)(int, int)
# * fnName(int arg1=0)[10]
# ...etc...
self.declarator << Group(
type_qualifier('first_typequal') + call_conv +
Group(ZeroOrMore(Group(Suppress('*') + type_qualifier)))('ptrs') +
((Optional('&')('ref') + ident('name')) |
(lparen + self.declarator + rparen)('center')) +
Optional(lparen +
Optional(delimitedList(
Group(self.type_spec('type') +
(self.declarator |
self.abstract_declarator)('decl') +
Optional(Literal('=').suppress() +
expression, default=None)('val')
)),
default=None) +
rparen)('args') +
Group(ZeroOrMore(lbrack + Optional(expression, default='-1') +
rbrack))('arrays')
)
self.declarator_list = Group(delimitedList(self.declarator))
# Typedef
self.type_decl = (Keyword('typedef') + self.type_spec('type') +
self.declarator_list('decl_list') + semi)
self.type_decl.setParseAction(self.process_typedef)
# Variable declaration
self.variable_decl = (
Group(storage_class_spec +
self.type_spec('type') +
Optional(self.declarator_list('decl_list')) +
Optional(Literal('=').suppress() +
(expression('value') |
(lbrace +
Group(delimitedList(expression))('array_values') +
rbrace
)
)
)
) +
semi)
self.variable_decl.setParseAction(self.process_variable)
# Function definition
self.typeless_function_decl = (self.declarator('decl') +
nestedExpr('{', '}').suppress())
self.function_decl = (storage_class_spec +
self.type_spec('type') +
self.declarator('decl') +
nestedExpr('{', '}').suppress())
self.function_decl.setParseAction(self.process_function)
# Struct definition
self.struct_decl = Forward()
struct_kw = (Keyword('struct') | Keyword('union'))
self.struct_member = (
Group(self.variable_decl.copy().setParseAction(lambda: None)) |
# Hack to handle bit width specification.
Group(Group(self.type_spec('type') +
Optional(self.declarator_list('decl_list')) +
colon + integer('bit') + semi)) |
(self.type_spec + self.declarator +
nestedExpr('{', '}')).suppress() |
(self.declarator + nestedExpr('{', '}')).suppress()
)
self.decl_list = (lbrace +
Group(OneOrMore(self.struct_member))('members') +
rbrace)
self.struct_type << (struct_kw('struct_type') +
((Optional(ident)('name') +
self.decl_list) | ident('name'))
)
self.struct_type.setParseAction(self.process_struct)
self.struct_decl = self.struct_type + semi
# Enum definition
enum_var_decl = Group(ident('name') +
Optional(Literal('=').suppress() +
(integer('value') | ident('valueName'))))
self.enum_type << (Keyword('enum') +
(Optional(ident)('name') +
lbrace +
Group(delimitedList(enum_var_decl))('members') +
Optional(comma) + rbrace | ident('name'))
)
self.enum_type.setParseAction(self.process_enum)
self.enum_decl = self.enum_type + semi
self.parser = (self.type_decl | self.variable_decl |
self.function_decl)
return self.parser
def process_declarator(self, decl):
"""Process a declarator (without base type) and return a tuple
(name, [modifiers])
See process_type(...) for more information.
"""
toks = []
quals = [tuple(decl.get('first_typequal', []))]
name = None
logger.debug("DECL: {}".format(decl))
if 'call_conv' in decl and len(decl['call_conv']) > 0:
toks.append(decl['call_conv'])
quals.append(None)
if 'ptrs' in decl and len(decl['ptrs']) > 0:
toks += ('*',) * len(decl['ptrs'])
quals += map(tuple, decl['ptrs'])
if 'arrays' in decl and len(decl['arrays']) > 0:
toks.extend([self.eval_expr(x)] for x in decl['arrays'])
quals += [()] * len(decl['arrays'])
if 'args' in decl and len(decl['args']) > 0:
if decl['args'][0] is None:
toks.append(())
else:
toks.append(tuple([self.process_type(a['type'],
a['decl']) +
(a['val'][0],) for a in decl['args']]
)
)
quals.append(())
if 'ref' in decl:
toks.append('&')
quals.append(())
if 'center' in decl:
(n, t, q) = self.process_declarator(decl['center'][0])
if n is not None:
name = n
toks.extend(t)
quals = quals[:-1] + [quals[-1] + q[0]] + list(q[1:])
if 'name' in decl:
name = decl['name']
return (name, toks, tuple(quals))
def process_type(self, typ, decl):
"""Take a declarator + base type and return a serialized name/type
description.
The description will be a list of elements (name, [basetype, modifier,
modifier, ...]):
- name is the string name of the declarator or None for an abstract
declarator
- basetype is the string representing the base type
- modifiers can be:
- '*' : pointer (multiple pointers "***" allowed)
- '&' : reference
- '__X' : calling convention (windows only). X can be 'cdecl' or
'stdcall'
- list : array. Value(s) indicate the length of each array, -1
for incomplete type.
- tuple : function, items are the output of processType for each
function argument.
Examples:
- int *x[10] => ('x', ['int', [10], '*'])
- char fn(int x) => ('fn', ['char', [('x', ['int'])]])
- struct s (*)(int, int*) =>
(None, ["struct s", ((None, ['int']), (None, ['int', '*'])), '*'])
"""
logger.debug("PROCESS TYPE/DECL: {}/{}".format(typ['name'], decl))
(name, decl, quals) = self.process_declarator(decl)
pre_typequal = tuple(typ.get('pre_qual', []))
return (name, Type(typ['name'], *decl,
type_quals=(pre_typequal + quals[0],) + quals[1:]))
def process_enum(self, s, l, t):
"""
"""
try:
logger.debug("ENUM: {}".format(t))
if t.name == '':
n = 0
while True:
name = 'anon_enum{}'.format(n)
if name not in self.defs['enums']:
break
n += 1
else:
name = t.name[0]
logger.debug(" name: {}".format(name))
if name not in self.defs['enums']:
i = 0
enum = {}
for v in t.members:
if v.value != '':
i = literal_eval(v.value)
if v.valueName != '':
i = enum[v.valueName]
enum[v.name] = i
self.add_def('values', v.name, i)
i += 1
logger.debug(" members: {}".format(enum))
self.add_def('enums', name, enum)
self.add_def('types', 'enum '+name, Type('enum', name))
return ('enum ' + name)
except:
logger.exception("Error processing enum: {}".format(t))
def process_function(self, s, l, t):
"""Build a function definition from the parsing tokens.
"""
logger.debug("FUNCTION {} : {}".format(t, t.keys()))
try:
(name, decl) = self.process_type(t.type, t.decl[0])
if len(decl) == 0 or type(decl[-1]) != tuple:
logger.error('{}'.format(t))
mess = "Incorrect declarator type for function definition."
raise DefinitionError(mess)
logger.debug(" name: {}".format(name))
logger.debug(" sig: {}".format(decl))
self.add_def('functions', name, decl.add_compatibility_hack())
except Exception:
logger.exception("Error processing function: {}".format(t))
def packing_at(self, line):
"""Return the structure packing value at the given line number.
"""
packing = None
for p in self.pack_list[self.current_file]:
if p[0] <= line:
packing = p[1]
else:
break
return packing
def process_struct(self, s, l, t):
"""
"""
try:
str_typ = t.struct_type # struct or union
# Check for extra packing rules
packing = self.packing_at(lineno(l, s))
logger.debug('{} {} {}'.format(str_typ.upper(), t.name, t))
if t.name == '':
n = 0
while True:
sname = 'anon_{}{}'.format(str_typ, n)
if sname not in self.defs[str_typ+'s']:
break
n += 1
else:
if istext(t.name):
sname = t.name
else:
sname = t.name[0]
logger.debug(" NAME: {}".format(sname))
if (len(t.members) > 0 or sname not in self.defs[str_typ+'s'] or
self.defs[str_typ+'s'][sname] == {}):
logger.debug(" NEW " + str_typ.upper())
struct = []
for m in t.members:
typ = m[0].type
val = self.eval_expr(m[0].value)
logger.debug(" member: {}, {}, {}".format(
m, m[0].keys(), m[0].decl_list))
if len(m[0].decl_list) == 0: # anonymous member
member = [None, Type(typ[0]), None]
if m[0].bit:
member.append(int(m[0].bit))
struct.append(tuple(member))
for d in m[0].decl_list:
(name, decl) = self.process_type(typ, d)
member = [name, decl, val]
if m[0].bit:
member.append(int(m[0].bit))
struct.append(tuple(member))
logger.debug(" {} {} {} {}".format(name, decl,
val, m[0].bit))
str_cls = (Struct if str_typ == 'struct' else Union)
self.add_def(str_typ + 's', sname,
str_cls(*struct, pack=packing))
self.add_def('types', str_typ+' '+sname, Type(str_typ, sname))
return str_typ + ' ' + sname
except Exception:
logger.exception('Error processing struct: {}'.format(t))
def process_variable(self, s, l, t):
"""
"""
logger.debug("VARIABLE: {}".format(t))
try:
val = self.eval_expr(t[0])
for d in t[0].decl_list:
(name, typ) = self.process_type(t[0].type, d)
# This is a function prototype
if type(typ[-1]) is tuple:
logger.debug(" Add function prototype: {} {} {}".format(
name, typ, val))
self.add_def('functions', name,
typ.add_compatibility_hack())
# This is a variable
else:
logger.debug(" Add variable: {} {} {}".format(name,
typ, val))
self.add_def('variables', name, (val, typ))
self.add_def('values', name, val)
except Exception:
logger.exception('Error processing variable: {}'.format(t))
def process_typedef(self, s, l, t):
"""
"""
logger.debug("TYPE: {}".format(t))
typ = t.type
for d in t.decl_list:
(name, decl) = self.process_type(typ, d)
logger.debug(" {} {}".format(name, decl))
self.add_def('types', name, decl)
# --- Utility methods
def eval_expr(self, toks):
"""Evaluates expressions.
Currently only works for expressions that also happen to be valid
python expressions.
"""
logger.debug("Eval: {}".format(toks))
try:
if istext(toks) or isbytes(toks):
val = self.eval(toks, None, self.defs['values'])
elif toks.array_values != '':
val = [self.eval(x, None, self.defs['values'])
for x in toks.array_values]
elif toks.value != '':
val = self.eval(toks.value, None, self.defs['values'])
else:
val = None
return val
except Exception:
logger.debug(" failed eval {} : {}".format(toks, format_exc()))
return None
def eval(self, expr, *args):
"""Just eval with a little extra robustness."""
expr = expr.strip()
cast = (lparen + self.type_spec + self.abstract_declarator +
rparen).suppress()
expr = (quotedString | number | cast).transformString(expr)
if expr == '':
return None
return eval(expr, *args)
def add_def(self, typ, name, val):
"""Add a definition of a specific type to both the definition set for
the current file and the global definition set.
"""
self.defs[typ][name] = val
if self.current_file is None:
base_name = None
else:
base_name = os.path.basename(self.current_file)
if base_name not in self.file_defs:
self.file_defs[base_name] = {}
for k in self.data_list:
self.file_defs[base_name][k] = {}
self.file_defs[base_name][typ][name] = val
def rem_def(self, typ, name):
"""Remove a definition of a specific type to both the definition set
for the current file and the global definition set.
"""
if self.current_file is None:
base_name = None
else:
base_name = os.path.basename(self.current_file)
del self.defs[typ][name]
del self.file_defs[base_name][typ][name]
def is_fund_type(self, typ):
"""Return True if this type is a fundamental C type, struct, or
union.
**ATTENTION: This function is legacy and should be replaced by
Type.is_fund_type()**
"""
return Type(typ).is_fund_type()
def eval_type(self, typ):
"""Evaluate a named type into its fundamental type.
**ATTENTION: This function is legacy and should be replaced by
Type.eval()**
"""
if not isinstance(typ, Type):
typ = Type(*typ)
return typ.eval(self.defs['types'])
def find(self, name):
"""Search all definitions for the given name.
"""
res = []
for f in self.file_defs:
fd = self.file_defs[f]
for t in fd:
typ = fd[t]
for k in typ:
if istext(name):
if k == name:
res.append((f, t))
else:
if re.match(name, k):
res.append((f, t, k))
return res
def find_text(self, text):
"""Search all file strings for text, return matching lines.
"""
res = []
for f in self.files:
l = self.files[f].split('\n')
for i in range(len(l)):
if text in l[i]:
res.append((f, i, l[i]))
return res
# --- Basic parsing elements.
def kwl(strs):
"""Generate a match-first list of keywords given a list of strings."""
return Regex(r'\b({})\b'.format('|'.join(strs)))
def flatten(lst):
res = []
for i in lst:
if isinstance(i, (list, tuple)):
res.extend(flatten(i))
else:
res.append(str(i))
return res
def recombine(tok):
"""Flattens a tree of tokens and joins into one big string.
"""
return " ".join(flatten(tok.asList()))
def print_parse_results(pr, depth=0, name=''):
"""For debugging; pretty-prints parse result objects.
"""
start = name + " " * (20 - len(name)) + ':' + '..' * depth
if isinstance(pr, ParseResults):
print(start)
for i in pr:
name = ''
for k in pr.keys():
if pr[k] is i:
name = k
break
print_parse_results(i, depth+1, name)
else:
print(start + str(pr))
# Syntatic delimiters
comma = Literal(",").ignore(quotedString).suppress()
colon = Literal(":").ignore(quotedString).suppress()
semi = Literal(";").ignore(quotedString).suppress()
lbrace = Literal("{").ignore(quotedString).suppress()
rbrace = Literal("}").ignore(quotedString).suppress()
lbrack = Literal("[").ignore(quotedString).suppress()
rbrack = Literal("]").ignore(quotedString).suppress()
lparen = Literal("(").ignore(quotedString).suppress()
rparen = Literal(")").ignore(quotedString).suppress()
# Numbers
int_strip = lambda t: t[0].rstrip('UL')
hexint = Regex('[+-]?\s*0[xX][{}]+[UL]*'.format(hexnums)).setParseAction(int_strip)
decint = Regex('[+-]?\s*[0-9]+[UL]*').setParseAction(int_strip)
integer = (hexint | decint)
# The floating regex is ugly but it is because we do not want to match
# integer to it.
floating = Regex(r'[+-]?\s*((((\d(\.\d*)?)|(\.\d+))[eE][+-]?\d+)|((\d\.\d*)|(\.\d+)))')
number = (floating | integer)
# Miscelaneous
bi_operator = oneOf("+ - / * | & || && ! ~ ^ % == != > < >= <= -> . :: << >> = ? :")
uni_right_operator = oneOf("++ --")
uni_left_operator = oneOf("++ -- - + * sizeof new")
wordchars = alphanums+'_$'
name = (WordStart(wordchars) + Word(alphas+"_", alphanums+"_$") +
WordEnd(wordchars))
size_modifiers = ['short', 'long']
sign_modifiers = ['signed', 'unsigned']
# Syntax elements defined by _init_parser.
expression = Forward()
array_op = lbrack + expression + rbrack
base_types = None
ident = None
call_conv = None
type_qualifier = None
storage_class_spec = None
extra_modifier = None
fund_type = None
extra_type_list = []
num_types = ['int', 'float', 'double']
nonnum_types = ['char', 'bool', 'void']
# Define some common language elements when initialising.
def _init_cparser(extra_types=None, extra_modifiers=None):
global expression
global call_conv, ident
global base_types
global type_qualifier, storage_class_spec, extra_modifier
global fund_type
global extra_type_list
# Some basic definitions
extra_type_list = [] if extra_types is None else list(extra_types)
base_types = nonnum_types + num_types + extra_type_list
storage_classes = ['inline', 'static', 'extern']
qualifiers = ['const', 'volatile', 'restrict', 'near', 'far']
keywords = (['struct', 'enum', 'union', '__stdcall', '__cdecl'] +
qualifiers + base_types + size_modifiers + sign_modifiers)
keyword = kwl(keywords)
wordchars = alphanums+'_$'
ident = (WordStart(wordchars) + ~keyword +
Word(alphas + "_", alphanums + "_$") +
WordEnd(wordchars)).setParseAction(lambda t: t[0])
call_conv = Optional(Keyword('__cdecl') |
Keyword('__stdcall'))('call_conv')
# Removes '__name' from all type specs. may cause trouble.
underscore_2_ident = (WordStart(wordchars) + ~keyword + '__' +
Word(alphanums, alphanums+"_$") +
WordEnd(wordchars)).setParseAction(lambda t: t[0])
type_qualifier = ZeroOrMore((underscore_2_ident + Optional(nestedExpr())) |
kwl(qualifiers))
storage_class_spec = Optional(kwl(storage_classes))
if extra_modifiers:
extra_modifier = ZeroOrMore(kwl(extra_modifiers) +
Optional(nestedExpr())).suppress()
else:
extra_modifier = None
# Language elements
fund_type = OneOrMore(kwl(sign_modifiers + size_modifiers +
base_types)).setParseAction(lambda t: ' '.join(t))
# Is there a better way to process expressions with cast operators??
cast_atom = (
ZeroOrMore(uni_left_operator) + Optional('('+ident+')').suppress() +
((ident + '(' + Optional(delimitedList(expression)) + ')' |
ident + OneOrMore('[' + expression + ']') |
ident | number | quotedString
) |
('(' + expression + ')')) +
ZeroOrMore(uni_right_operator)
)
# XXX Added name here to catch macro functions on types
uncast_atom = (
ZeroOrMore(uni_left_operator) +
((ident + '(' + Optional(delimitedList(expression)) + ')' |
ident + OneOrMore('[' + expression + ']') |
ident | number | name | quotedString
) |
('(' + expression + ')')) +
ZeroOrMore(uni_right_operator)
)
atom = cast_atom | uncast_atom
expression << Group(atom + ZeroOrMore(bi_operator + atom))
expression.setParseAction(recombine)
| mrh1997/pyclibrary | pyclibrary/c_parser.py | Python | mit | 62,500 | [
30522,
1001,
1011,
1008,
1011,
16861,
1024,
21183,
2546,
1011,
1022,
1011,
1008,
1011,
1001,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
30524,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#ifndef MANAGEDEFINITIONSDIALOG_H
#define MANAGEDEFINITIONSDIALOG_H
#include "ui_managedefinitionsdialog.h"
#include "highlightdefinitionmetadata.h"
#include <QtCore/QList>
namespace TextEditor {
namespace Internal {
class ManageDefinitionsDialog : public QDialog
{
Q_OBJECT
public:
explicit ManageDefinitionsDialog(const QList<HighlightDefinitionMetaData> &metaDataList,
const QString &path,
QWidget *parent = 0);
protected:
void changeEvent(QEvent *e);
private slots:
void downloadDefinitions();
void selectAll();
void clearSelection();
void invertSelection();
private:
void populateDefinitionsWidget();
QList<HighlightDefinitionMetaData> m_definitionsMetaData;
QString m_path;
Ui::ManageDefinitionsDialog ui;
};
} // namespace Internal
} // namespace TextEditor
#endif // MANAGEDEFINITIONSDIALOG_H
| pcacjr/qt-creator | src/plugins/texteditor/generichighlighter/managedefinitionsdialog.h | C | lgpl-2.1 | 2,212 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* Generic definitions */
#define PACKAGE it.unimi.dsi.fastutil.doubles
#define VALUE_PACKAGE it.unimi.dsi.fastutil.chars
/* Assertions (useful to generate conditional code) */
#unassert keyclass
#assert keyclass(Double)
#unassert keys
#assert keys(primitive)
#unassert valueclass
#assert valueclass(Character)
#unassert values
#assert values(primitive)
/* Current type and class (and size, if applicable) */
#define KEY_TYPE double
#define VALUE_TYPE char
#define KEY_CLASS Double
#define VALUE_CLASS Character
#if #keyclass(Object) || #keyclass(Reference)
#define KEY_GENERIC_CLASS K
#define KEY_GENERIC_TYPE K
#define KEY_GENERIC <K>
#define KEY_GENERIC_WILDCARD <?>
#define KEY_EXTENDS_GENERIC <? extends K>
#define KEY_SUPER_GENERIC <? super K>
#define KEY_GENERIC_CAST (K)
#define KEY_GENERIC_ARRAY_CAST (K[])
#define KEY_GENERIC_BIG_ARRAY_CAST (K[][])
#else
#define KEY_GENERIC_CLASS KEY_CLASS
#define KEY_GENERIC_TYPE KEY_TYPE
#define KEY_GENERIC
#define KEY_GENERIC_WILDCARD
#define KEY_EXTENDS_GENERIC
#define KEY_SUPER_GENERIC
#define KEY_GENERIC_CAST
#define KEY_GENERIC_ARRAY_CAST
#define KEY_GENERIC_BIG_ARRAY_CAST
#endif
#if #valueclass(Object) || #valueclass(Reference)
#define VALUE_GENERIC_CLASS V
#define VALUE_GENERIC_TYPE V
#define VALUE_GENERIC <V>
#define VALUE_EXTENDS_GENERIC <? extends V>
#define VALUE_GENERIC_CAST (V)
#define VALUE_GENERIC_ARRAY_CAST (V[])
#else
#define VALUE_GENERIC_CLASS VALUE_CLASS
#define VALUE_GENERIC_TYPE VALUE_TYPE
#define VALUE_GENERIC
#define VALUE_EXTENDS_GENERIC
#define VALUE_GENERIC_CAST
#define VALUE_GENERIC_ARRAY_CAST
#endif
#if #keyclass(Object) || #keyclass(Reference)
#if #valueclass(Object) || #valueclass(Reference)
#define KEY_VALUE_GENERIC <K,V>
#define KEY_VALUE_EXTENDS_GENERIC <? extends K, ? extends V>
#else
#define KEY_VALUE_GENERIC <K>
#define KEY_VALUE_EXTENDS_GENERIC <? extends K>
#endif
#else
#if #valueclass(Object) || #valueclass(Reference)
#define KEY_VALUE_GENERIC <V>
#define KEY_VALUE_EXTENDS_GENERIC <? extends V>
#else
#define KEY_VALUE_GENERIC
#define KEY_VALUE_EXTENDS_GENERIC
#endif
#endif
/* Value methods */
#define KEY_VALUE doubleValue
#define VALUE_VALUE charValue
/* Interfaces (keys) */
#define COLLECTION DoubleCollection
#define SET DoubleSet
#define HASH DoubleHash
#define SORTED_SET DoubleSortedSet
#define STD_SORTED_SET DoubleSortedSet
#define FUNCTION Double2CharFunction
#define MAP Double2CharMap
#define SORTED_MAP Double2CharSortedMap
#if #keyclass(Object) || #keyclass(Reference)
#define STD_SORTED_MAP SortedMap
#define STRATEGY Strategy
#else
#define STD_SORTED_MAP Double2CharSortedMap
#define STRATEGY PACKAGE.DoubleHash.Strategy
#endif
#define LIST DoubleList
#define BIG_LIST DoubleBigList
#define STACK DoubleStack
#define PRIORITY_QUEUE DoublePriorityQueue
#define INDIRECT_PRIORITY_QUEUE DoubleIndirectPriorityQueue
#define INDIRECT_DOUBLE_PRIORITY_QUEUE DoubleIndirectDoublePriorityQueue
#define KEY_ITERATOR DoubleIterator
#define KEY_ITERABLE DoubleIterable
#define KEY_BIDI_ITERATOR DoubleBidirectionalIterator
#define KEY_LIST_ITERATOR DoubleListIterator
#define KEY_BIG_LIST_ITERATOR DoubleBigListIterator
#define STD_KEY_ITERATOR DoubleIterator
#define KEY_COMPARATOR DoubleComparator
/* Interfaces (values) */
#define VALUE_COLLECTION CharCollection
#define VALUE_ARRAY_SET CharArraySet
#define VALUE_ITERATOR CharIterator
#define VALUE_LIST_ITERATOR CharListIterator
/* Abstract implementations (keys) */
#define ABSTRACT_COLLECTION AbstractDoubleCollection
#define ABSTRACT_SET AbstractDoubleSet
#define ABSTRACT_SORTED_SET AbstractDoubleSortedSet
#define ABSTRACT_FUNCTION AbstractDouble2CharFunction
#define ABSTRACT_MAP AbstractDouble2CharMap
#define ABSTRACT_FUNCTION AbstractDouble2CharFunction
#define ABSTRACT_SORTED_MAP AbstractDouble2CharSortedMap
#define ABSTRACT_LIST AbstractDoubleList
#define ABSTRACT_BIG_LIST AbstractDoubleBigList
#define SUBLIST DoubleSubList
#define ABSTRACT_PRIORITY_QUEUE AbstractDoublePriorityQueue
#define ABSTRACT_STACK AbstractDoubleStack
#define KEY_ABSTRACT_ITERATOR AbstractDoubleIterator
#define KEY_ABSTRACT_BIDI_ITERATOR AbstractDoubleBidirectionalIterator
#define KEY_ABSTRACT_LIST_ITERATOR AbstractDoubleListIterator
#define KEY_ABSTRACT_BIG_LIST_ITERATOR AbstractDoubleBigListIterator
#if #keyclass(Object)
#define KEY_ABSTRACT_COMPARATOR Comparator
#else
#define KEY_ABSTRACT_COMPARATOR AbstractDoubleComparator
#endif
/* Abstract implementations (values) */
#define VALUE_ABSTRACT_COLLECTION AbstractCharCollection
#define VALUE_ABSTRACT_ITERATOR AbstractCharIterator
#define VALUE_ABSTRACT_BIDI_ITERATOR AbstractCharBidirectionalIterator
/* Static containers (keys) */
#define COLLECTIONS DoubleCollections
#define SETS DoubleSets
#define SORTED_SETS DoubleSortedSets
#define LISTS DoubleLists
#define BIG_LISTS DoubleBigLists
#define MAPS Double2CharMaps
#define FUNCTIONS Double2CharFunctions
#define SORTED_MAPS Double2CharSortedMaps
#define PRIORITY_QUEUES DoublePriorityQueues
#define HEAPS DoubleHeaps
#define SEMI_INDIRECT_HEAPS DoubleSemiIndirectHeaps
#define INDIRECT_HEAPS DoubleIndirectHeaps
#define ARRAYS DoubleArrays
#define BIG_ARRAYS DoubleBigArrays
#define ITERATORS DoubleIterators
#define BIG_LIST_ITERATORS DoubleBigListIterators
#define COMPARATORS DoubleComparators
/* Static containers (values) */
#define VALUE_COLLECTIONS CharCollections
#define VALUE_SETS CharSets
#define VALUE_ARRAYS CharArrays
/* Implementations */
#define OPEN_HASH_SET DoubleOpenHashSet
#define OPEN_HASH_BIG_SET DoubleOpenHashBigSet
#define OPEN_DOUBLE_HASH_SET DoubleOpenDoubleHashSet
#define OPEN_HASH_MAP Double2CharOpenHashMap
#define STRIPED_OPEN_HASH_MAP StripedDouble2CharOpenHashMap
#define OPEN_DOUBLE_HASH_MAP Double2CharOpenDoubleHashMap
#define ARRAY_SET DoubleArraySet
#define ARRAY_MAP Double2CharArrayMap
#define LINKED_OPEN_HASH_SET DoubleLinkedOpenHashSet
#define AVL_TREE_SET DoubleAVLTreeSet
#define RB_TREE_SET DoubleRBTreeSet
#define AVL_TREE_MAP Double2CharAVLTreeMap
#define RB_TREE_MAP Double2CharRBTreeMap
#define ARRAY_LIST DoubleArrayList
#define BIG_ARRAY_BIG_LIST DoubleBigArrayBigList
#define ARRAY_FRONT_CODED_LIST DoubleArrayFrontCodedList
#define HEAP_PRIORITY_QUEUE DoubleHeapPriorityQueue
#define HEAP_SEMI_INDIRECT_PRIORITY_QUEUE DoubleHeapSemiIndirectPriorityQueue
#define HEAP_INDIRECT_PRIORITY_QUEUE DoubleHeapIndirectPriorityQueue
#define HEAP_SESQUI_INDIRECT_DOUBLE_PRIORITY_QUEUE DoubleHeapSesquiIndirectDoublePriorityQueue
#define HEAP_INDIRECT_DOUBLE_PRIORITY_QUEUE DoubleHeapIndirectDoublePriorityQueue
#define ARRAY_FIFO_QUEUE DoubleArrayFIFOQueue
#define ARRAY_PRIORITY_QUEUE DoubleArrayPriorityQueue
#define ARRAY_INDIRECT_PRIORITY_QUEUE DoubleArrayIndirectPriorityQueue
#define ARRAY_INDIRECT_DOUBLE_PRIORITY_QUEUE DoubleArrayIndirectDoublePriorityQueue
/* Synchronized wrappers */
#define SYNCHRONIZED_COLLECTION SynchronizedDoubleCollection
#define SYNCHRONIZED_SET SynchronizedDoubleSet
#define SYNCHRONIZED_SORTED_SET SynchronizedDoubleSortedSet
#define SYNCHRONIZED_FUNCTION SynchronizedDouble2CharFunction
#define SYNCHRONIZED_MAP SynchronizedDouble2CharMap
#define SYNCHRONIZED_LIST SynchronizedDoubleList
/* Unmodifiable wrappers */
#define UNMODIFIABLE_COLLECTION UnmodifiableDoubleCollection
#define UNMODIFIABLE_SET UnmodifiableDoubleSet
#define UNMODIFIABLE_SORTED_SET UnmodifiableDoubleSortedSet
#define UNMODIFIABLE_FUNCTION UnmodifiableDouble2CharFunction
#define UNMODIFIABLE_MAP UnmodifiableDouble2CharMap
#define UNMODIFIABLE_LIST UnmodifiableDoubleList
#define UNMODIFIABLE_KEY_ITERATOR UnmodifiableDoubleIterator
#define UNMODIFIABLE_KEY_BIDI_ITERATOR UnmodifiableDoubleBidirectionalIterator
#define UNMODIFIABLE_KEY_LIST_ITERATOR UnmodifiableDoubleListIterator
/* Other wrappers */
#define KEY_READER_WRAPPER DoubleReaderWrapper
#define KEY_DATA_INPUT_WRAPPER DoubleDataInputWrapper
/* Methods (keys) */
#define NEXT_KEY nextDouble
#define PREV_KEY previousDouble
#define FIRST_KEY firstDoubleKey
#define LAST_KEY lastDoubleKey
#define GET_KEY getDouble
#define REMOVE_KEY removeDouble
#define READ_KEY readDouble
#define WRITE_KEY writeDouble
#define DEQUEUE dequeueDouble
#define DEQUEUE_LAST dequeueLastDouble
#define SUBLIST_METHOD doubleSubList
#define SINGLETON_METHOD doubleSingleton
#define FIRST firstDouble
#define LAST lastDouble
#define TOP topDouble
#define PEEK peekDouble
#define POP popDouble
#define KEY_ITERATOR_METHOD doubleIterator
#define KEY_LIST_ITERATOR_METHOD doubleListIterator
#define KEY_EMPTY_ITERATOR_METHOD emptyDoubleIterator
#define AS_KEY_ITERATOR asDoubleIterator
#define TO_KEY_ARRAY toDoubleArray
#define ENTRY_GET_KEY getDoubleKey
#define REMOVE_FIRST_KEY removeFirstDouble
#define REMOVE_LAST_KEY removeLastDouble
#define PARSE_KEY parseDouble
#define LOAD_KEYS loadDoubles
#define LOAD_KEYS_BIG loadDoublesBig
#define STORE_KEYS storeDoubles
/* Methods (values) */
#define NEXT_VALUE nextChar
#define PREV_VALUE previousChar
#define READ_VALUE readChar
#define WRITE_VALUE writeChar
#define VALUE_ITERATOR_METHOD charIterator
#define ENTRY_GET_VALUE getCharValue
#define REMOVE_FIRST_VALUE removeFirstChar
#define REMOVE_LAST_VALUE removeLastChar
/* Methods (keys/values) */
#define ENTRYSET double2CharEntrySet
/* Methods that have special names depending on keys (but the special names depend on values) */
#if #keyclass(Object) || #keyclass(Reference)
#define GET_VALUE getChar
#define REMOVE_VALUE removeChar
#else
#define GET_VALUE get
#define REMOVE_VALUE remove
#endif
/* Equality */
#ifdef Custom
#define KEY_EQUALS(x,y) ( strategy.equals( (x), KEY_GENERIC_CAST (y) ) )
#else
#if #keyclass(Object)
#define KEY_EQUALS(x,y) ( (x) == null ? (y) == null : (x).equals(y) )
#define KEY_EQUALS_NOT_NULL(x,y) ( (x).equals(y) )
#else
#define KEY_EQUALS(x,y) ( (x) == (y) )
#define KEY_EQUALS_NOT_NULL(x,y) ( (x) == (y) )
#endif
#endif
#if #valueclass(Object)
#define VALUE_EQUALS(x,y) ( (x) == null ? (y) == null : (x).equals(y) )
#else
#define VALUE_EQUALS(x,y) ( (x) == (y) )
#endif
/* Object/Reference-only definitions (keys) */
#if #keyclass(Object) || #keyclass(Reference)
#define REMOVE remove
#define KEY_OBJ2TYPE(x) (x)
#define KEY_CLASS2TYPE(x) (x)
#define KEY2OBJ(x) (x)
#if #keyclass(Object)
#ifdef Custom
#define KEY2JAVAHASH(x) ( strategy.hashCode( KEY_GENERIC_CAST (x)) )
#define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( KEY_GENERIC_CAST (x)) ) )
#define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)strategy.hashCode( KEY_GENERIC_CAST (x)) ) )
#else
#define KEY2JAVAHASH(x) ( (x) == null ? 0 : (x).hashCode() )
#define KEY2INTHASH(x) ( (x) == null ? 0x87fcd5c : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (x).hashCode() ) )
#define KEY2LONGHASH(x) ( (x) == null ? 0x810879608e4259ccL : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)(x).hashCode() ) )
#endif
#else
#define KEY2JAVAHASH(x) ( (x) == null ? 0 : System.identityHashCode(x) )
#define KEY2INTHASH(x) ( (x) == null ? 0x87fcd5c : it.unimi.dsi.fastutil.HashCommon.murmurHash3( System.identityHashCode(x) ) )
#define KEY2LONGHASH(x) ( (x) == null ? 0x810879608e4259ccL : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)System.identityHashCode(x) ) )
#endif
#define KEY_CMP(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) )
#define KEY_CMP_EQ(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) == 0 )
#define KEY_LESS(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) < 0 )
#define KEY_LESSEQ(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) <= 0 )
#define KEY_NULL (null)
#else
/* Primitive-type-only definitions (keys) */
#define REMOVE rem
#define KEY_CLASS2TYPE(x) ((x).KEY_VALUE())
#define KEY_OBJ2TYPE(x) (KEY_CLASS2TYPE((KEY_CLASS)(x)))
#define KEY2OBJ(x) (KEY_CLASS.valueOf(x))
#if #keyclass(Boolean)
#define KEY_CMP_EQ(x,y) ( (x) == (y) )
#define KEY_NULL (false)
#define KEY_CMP(x,y) ( !(x) && (y) ? -1 : ( (x) == (y) ? 0 : 1 ) )
#define KEY_LESS(x,y) ( !(x) && (y) )
#define KEY_LESSEQ(x,y) ( !(x) || (y) )
#else
#define KEY_NULL ((KEY_TYPE)0)
#if #keyclass(Float) || #keyclass(Double)
#define KEY_CMP_EQ(x,y) ( KEY_CLASS.compare((x),(y)) == 0 )
#define KEY_CMP(x,y) ( KEY_CLASS.compare((x),(y)) )
#define KEY_LESS(x,y) ( KEY_CLASS.compare((x),(y)) < 0 )
#define KEY_LESSEQ(x,y) ( KEY_CLASS.compare((x),(y)) <= 0 )
#else
#define KEY_CMP_EQ(x,y) ( (x) == (y) )
#define KEY_CMP(x,y) ( (x) < (y) ? -1 : ( (x) == (y) ? 0 : 1 ) )
#define KEY_LESS(x,y) ( (x) < (y) )
#define KEY_LESSEQ(x,y) ( (x) <= (y) )
#endif
#if #keyclass(Float)
#define KEY2LEXINT(x) fixFloat(x)
#elif #keyclass(Double)
#define KEY2LEXINT(x) fixDouble(x)
#else
#define KEY2LEXINT(x) (x)
#endif
#endif
#ifdef Custom
#define KEY2JAVAHASH(x) ( strategy.hashCode(x) )
#define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(x) ) )
#define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)strategy.hashCode(x) ) )
#else
#if #keyclass(Float)
#define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.float2int(x)
#define KEY2INTHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3( it.unimi.dsi.fastutil.HashCommon.float2int(x) )
#define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)it.unimi.dsi.fastutil.HashCommon.float2int(x) )
#elif #keyclass(Double)
#define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.double2int(x)
#define KEY2INTHASH(x) (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(x))
#define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(x))
#elif #keyclass(Long)
#define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.long2int(x)
#define KEY2INTHASH(x) (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(x)
#define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3(x)
#elif #keyclass(Boolean)
#define KEY2JAVAHASH(x) ((x) ? 1231 : 1237)
#define KEY2INTHASH(x) ((x) ? 0xfab5368 : 0xcba05e7b)
#define KEY2LONGHASH(x) ((x) ? 0x74a19fc8b6428188L : 0xbaeca2031a4fd9ecL)
#else
#define KEY2JAVAHASH(x) (x)
#define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (x) ) )
#define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)(x) ) )
#endif
#endif
#endif
/* Object/Reference-only definitions (values) */
#if #valueclass(Object) || #valueclass(Reference)
#define VALUE_OBJ2TYPE(x) (x)
#define VALUE_CLASS2TYPE(x) (x)
#define VALUE2OBJ(x) (x)
#if #valueclass(Object)
#define VALUE2JAVAHASH(x) ( (x) == null ? 0 : (x).hashCode() )
#else
#define VALUE2JAVAHASH(x) ( (x) == null ? 0 : System.identityHashCode(x) )
#endif
#define VALUE_NULL (null)
#define OBJECT_DEFAULT_RETURN_VALUE (this.defRetValue)
#else
/* Primitive-type-only definitions (values) */
#define VALUE_CLASS2TYPE(x) ((x).VALUE_VALUE())
#define VALUE_OBJ2TYPE(x) (VALUE_CLASS2TYPE((VALUE_CLASS)(x)))
#define VALUE2OBJ(x) (VALUE_CLASS.valueOf(x))
#if #valueclass(Float) || #valueclass(Double) || #valueclass(Long)
#define VALUE_NULL (0)
#define VALUE2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.char2int(x)
#elif #valueclass(Boolean)
#define VALUE_NULL (false)
#define VALUE2JAVAHASH(x) (x ? 1231 : 1237)
#else
#if #valueclass(Integer)
#define VALUE_NULL (0)
#else
#define VALUE_NULL ((VALUE_TYPE)0)
#endif
#define VALUE2JAVAHASH(x) (x)
#endif
#define OBJECT_DEFAULT_RETURN_VALUE (null)
#endif
#include "drv/AbstractSortedMap.drv"
| karussell/fastutil | src/it/unimi/dsi/fastutil/doubles/AbstractDouble2CharSortedMap.c | C | apache-2.0 | 15,455 | [
30522,
1013,
1008,
12391,
15182,
1008,
1013,
1001,
9375,
7427,
2009,
1012,
4895,
27605,
1012,
16233,
2072,
1012,
3435,
21823,
2140,
1012,
7695,
1001,
9375,
3643,
1035,
7427,
2009,
1012,
4895,
27605,
1012,
16233,
2072,
1012,
3435,
21823,
214... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Logging #
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<span class="aside">
To follow this tutorial you'll need to have
[installed the SDK](dev-guide/tutorials/installation.html)
and learned the
[basics of `cfx`](dev-guide/tutorials/getting-started-with-cfx.html).
</span>
The [DOM `console` object](https://developer.mozilla.org/en/DOM/console)
is useful for debugging JavaScript. Because DOM objects aren't available
to the main add-on code, the SDK provides its own global `console` object
with most of the same methods as the DOM `console`, including methods to
log error, warning, or informational messages. You don't have to
`require()` anything to get access to the console: it is automatically
made available to you.
The `console.log()` method prints an informational message:
console.log("Hello World");
Try it out:
* create a new directory, and navigate to it
* execute `cfx init`
* open "lib/main.js" and add the line above
* execute `cfx run`, then `cfx run` again
Firefox will start, and the following line will appear in the command
window you used to execute `cfx run`:
<pre>
info: Hello World!
</pre>
## `console` in Content Scripts ##
You can use the console in
[content scripts](dev-guide/guides/content-scripts/index.html) as well
as in your main add-on code. The following add-on logs the HTML content
of every tab the user loads, by calling `console.log()` inside a content
script:
require("sdk/tabs").on("ready", function(tab) {
tab.attach({
contentScript: "console.log(document.body.innerHTML);"
});
});
## `console` Output ##
If you are running your add-on from the command line (for example,
executing `cfx run` or `cfx test`) then the console's messages appear
in the command shell you used.
If you've installed the add-on in Firefox, or you're running the
add-on in the Add-on Builder, then the messages appear in Firefox's
[Error Console](https://developer.mozilla.org/en/Error_Console).
But note that **by default, calls to `console.log()` will not result
in any output in the Error Console for any installed add-ons**: this
includes add-ons installed using the Add-on Builder or using tools
like the
[Extension Auto-installer](https://addons.mozilla.org/en-US/firefox/addon/autoinstaller/).
See ["Logging Levels"](dev-guide/console.html#Logging Levels)
in the console reference documentation for more information on this.
## Learning More ##
For the complete `console` API, see its
[API reference](dev-guide/console.html).
| cerivera/crossfire | bin/firefox/addon-sdk-1.15/doc/dev-guide-source/tutorials/logging.md | Markdown | mit | 2,673 | [
30522,
1001,
15899,
1001,
1026,
999,
1011,
1011,
2023,
3120,
3642,
2433,
2003,
3395,
2000,
1996,
3408,
1997,
1996,
9587,
5831,
4571,
2270,
1011,
6105,
1010,
1058,
1012,
1016,
1012,
1014,
1012,
2065,
1037,
6100,
1997,
1996,
6131,
2140,
200... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
---
license: 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.
---
camera.getPicture
=================
Takes a photo using the camera or retrieves a photo from the device's album. The image is returned as a base64 encoded `String` or as the URI of an image file.
navigator.camera.getPicture( cameraSuccess, cameraError, [ cameraOptions ] );
Description
-----------
Function `camera.getPicture` opens the device's default camera application so that the user can take a picture (if `Camera.sourceType = Camera.PictureSourceType.CAMERA`, which is the default). Once the photo is taken, the camera application closes and your application is restored.
If `Camera.sourceType = Camera.PictureSourceType.PHOTOLIBRARY` or `Camera.PictureSourceType.SAVEDPHOTOALBUM`, then a photo chooser dialog is shown, from which a photo from the album can be selected.
The return value will be sent to the `cameraSuccess` function, in one of the following formats, depending on the `cameraOptions` you specify:
- A `String` containing the Base64 encoded photo image.
- A `String` representing the image file location on local storage (default).
You can do whatever you want with the encoded image or URI, for example:
- Render the image in an `<img>` tag _(see example below)_
- Save the data locally (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc)
- Post the data to a remote server
Note: The image quality of pictures taken using the camera on newer devices is quite good. _Encoding such images using Base64 has caused memory issues on some of these devices (iPhone 4, BlackBerry Torch 9800)._ Therefore, using FILE_URI as the 'Camera.destinationType' is highly recommended.
Supported Platforms
-------------------
- Android
- BlackBerry WebWorks (OS 5.0 and higher)
- iPhone
- Windows Phone 7 ( Mango )
Windows Phone 7 Quirks
----------------------
Invoking the native camera application while your device is connected
via Zune will not work, and the error callback will be triggered.
Quick Example
-------------
Take photo and retrieve Base64-encoded image:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Take photo and retrieve image file location:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Full Example
------------
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for Cordova to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);
// Cordova is ready to be used!
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64 encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
//
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType.DATA_URL });
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType.DATA_URL });
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
<button onclick="capturePhoto();">Capture Photo</button> <br>
<button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
| kant2002/cordova-docs | docs/en/1.6.0/cordova/camera/camera.getPicture.md | Markdown | apache-2.0 | 7,348 | [
30522,
1011,
1011,
1011,
6105,
1024,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
2030,
2062,
12130,
6105,
10540,
1012,
2156,
1996,
5060,
5371,
5500,
2007,
2023,
2147,
2005,
3176,
2592,
4953,
9385,
6095,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
""" Check what the `lambdax` module publicly exposes. """
import builtins
from inspect import isbuiltin, ismodule, isclass
from itertools import chain
import operator
from unittest.mock import patch
import lambdax.builtins_as_lambdas
import lambdax.builtins_overridden
from lambdax import x1, x2, x
def _get_exposed(tested_module):
return {name for name, obj in vars(tested_module).items()
if not name.startswith('_') and not ismodule(obj)}
def test_no_builtin_exposed():
for obj in chain(vars(lambdax).values(), vars(lambdax.builtins_overridden).values()):
assert not isbuiltin(obj)
def test_base_exposed():
variables = {'x'} | {'x%d' % i for i in range(1, 10)}
variables |= {v.upper() for v in variables}
special_functions = {'λ', 'is_λ', 'comp', 'circle', 'chaining', 'and_', 'or_', 'if_'}
to_expose = variables | special_functions
exposed = _get_exposed(lambdax.lambda_calculus)
assert to_expose == exposed
def test_operators_exposed():
operators = {name for name, obj in vars(operator).items()
if not name.startswith('_') and not isclass(obj) and not hasattr(builtins, name)}
to_expose = operators.difference(('and_', 'or_', 'xor'))
assert to_expose == _get_exposed(lambdax.operators)
def test_overridden_builtins_exposed():
builtin_names = {name for name, obj in vars(builtins).items()
if name[0].upper() != name[0]}
irrelevant_builtins = {
'input', 'help', 'open',
'copyright', 'license', 'credits',
'compile', 'eval', 'exec', 'execfile', 'runfile',
'classmethod', 'staticmethod', 'property',
'object', 'super',
'globals', 'locals'
}
builtins_to_expose = builtin_names - irrelevant_builtins
to_expose_as_λ = {name + '_λ' for name in builtins_to_expose}
split_exposed_names = (name.split('_') for name in _get_exposed(lambdax.builtins_as_lambdas))
exposed_as_λ = {'%s_%s' % (words[0], words[-1]) for words in split_exposed_names}
assert to_expose_as_λ == exposed_as_λ
assert builtins_to_expose == _get_exposed(lambdax.builtins_overridden)
def test_operators_implementations():
operators = vars(operator)
for name, abstraction in vars(lambdax.operators).items():
initial = operators.get(name)
if initial and isbuiltin(initial):
wrapped = getattr(abstraction, '_λ_constant')
assert wrapped == initial
try:
ref = initial(42, 51)
except TypeError as e:
ref = e.args
try:
res = abstraction(x1, x2)(42, 51)
except TypeError as e:
res = e.args
assert res == ref
def _get_effect(implementation):
output = []
with patch('sys.stdout') as out:
out.side_effect = output.append
try:
res = implementation("42")
except BaseException as e:
res = e.args
return res, output
def _get_method_or_object(obj, meth=''):
return getattr(obj, meth) if meth else obj
def test_overridden_builtins_implementations():
for name in _get_exposed(lambdax.builtins_as_lambdas):
obj, tail = name.split('_', 1)
meth = tail[:-2]
original = _get_method_or_object(getattr(builtins, obj), meth)
as_λ = getattr(lambdax.builtins_as_lambdas, name)
overridden = _get_method_or_object(getattr(lambdax.builtins_overridden, obj), meth)
ref, ref_output = _get_effect(original)
expl, expl_output = _get_effect(as_λ(x))
iso, iso_output = _get_effect(overridden)
lbda, lbda_output = _get_effect(overridden(x))
assert lbda_output == iso_output == expl_output == ref_output
try:
assert list(iter(lbda)) == list(iter(iso)) == list(iter(expl)) == list(iter(ref))
except TypeError:
assert lbda == iso == expl == ref
| hlerebours/lambda-calculus | lambdax/test/test_exposed.py | Python | mit | 3,947 | [
30522,
1000,
1000,
1000,
4638,
2054,
1996,
1036,
23375,
2595,
1036,
11336,
7271,
14451,
2015,
1012,
1000,
1000,
1000,
12324,
2328,
7076,
2013,
22459,
12324,
2003,
8569,
4014,
7629,
1010,
2003,
5302,
8566,
2571,
1010,
2003,
26266,
2013,
2009... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# DEPRECATION WARNING
This functionality is better provided by:
https://github.com/benmosher/eslint-plugin-import
I'd suggest using that module instad.
-----------------
# eslint-plugin-modules
ESLint rules for JavaScript modules.
### Installation
`npm install --save-dev eslint-plugin-modules`
### Usage
Add the following to your `.eslintrc` file:
```js
"plugins": [
"modules"
]
```
### Rules
All of these rules have to do with JavaScript modules in one way or another.
- `no-define` - avoid AMD style define()
- `no-cjs` - prefer es6 modules to CJS style require()
- `no-exports-typo` - avoid typos in your module.exports
- `no-mix-default-named` - disallow using both named and default es6 exports
| xjamundx/eslint-plugin-modules | README.md | Markdown | mit | 716 | [
30522,
1001,
2139,
28139,
10719,
5432,
2023,
15380,
2003,
2488,
3024,
2011,
1024,
16770,
1024,
1013,
1013,
21025,
2705,
12083,
1012,
4012,
1013,
3841,
15530,
5886,
1013,
9686,
4115,
2102,
1011,
13354,
2378,
1011,
12324,
1045,
1005,
1040,
65... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#include "caf/config_option_adder.hpp"
#include "caf/config.hpp"
#include "caf/config_option_set.hpp"
CAF_PUSH_DEPRECATED_WARNING
namespace caf {
config_option_adder::config_option_adder(config_option_set& target,
string_view category)
: xs_(target),
category_(category) {
// nop
}
config_option_adder& config_option_adder::add_neg(bool& ref, string_view name,
string_view description) {
return add_impl(make_negated_config_option(ref, category_,
name, description));
}
config_option_adder& config_option_adder::add_impl(config_option&& opt) {
xs_.add(std::move(opt));
return *this;
}
} // namespace caf
CAF_POP_WARNINGS
| actor-framework/actor-framework | libcaf_core/src/config_option_adder.cpp | C++ | bsd-3-clause | 1,013 | [
30522,
1013,
1013,
2023,
5371,
2003,
2112,
1997,
24689,
1010,
1996,
1039,
1009,
1009,
3364,
7705,
1012,
2156,
1996,
5371,
6105,
1999,
1013,
1013,
1996,
2364,
4353,
14176,
2005,
6105,
3408,
1998,
9385,
2030,
3942,
1013,
1013,
16770,
1024,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* -----------------------------------------------------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------------------------------------------- */
package ppm_java._dev.concept.example.event;
import ppm_java.backend.TController;
import ppm_java.typelib.IControllable;
import ppm_java.typelib.IEvented;
import ppm_java.typelib.VBrowseable;
/**
*
*/
class TSink extends VBrowseable implements IEvented, IControllable
{
public TSink (String id)
{
super (id);
}
public void OnEvent (int e, String arg0)
{
String msg;
msg = GetID () + ": " + "Received messaging event. Message: " + arg0;
System.out.println (msg);
}
public void Start () {/* Do nothing */}
public void Stop () {/* Do nothing */}
public void OnEvent (int e) {/* Do nothing */}
public void OnEvent (int e, int arg0) {/* Do nothing */}
public void OnEvent (int e, long arg0) {/* Do nothing */}
protected void _Register ()
{
TController.Register (this);
}
}
| ustegrew/ppm-java | src/ppm_java/_dev/concept/example/event/TSink.java | Java | gpl-3.0 | 1,733 | [
30522,
1013,
1008,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*!
* inferno v0.7.3
* (c) 2016 Dominic Gannaway
* Released under the MPL-2.0 License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Inferno = factory());
}(this, function () { 'use strict';
var babelHelpers = {};
babelHelpers.typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
babelHelpers.classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
babelHelpers.createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
babelHelpers.extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
babelHelpers;
function isNullOrUndefined(obj) {
return obj === void 0 || obj === null;
}
function isAttrAnEvent(attr) {
return attr[0] === 'o' && attr[1] === 'n' && attr.length > 3;
}
function VNode(blueprint) {
this.bp = blueprint;
this.dom = null;
this.instance = null;
this.tag = null;
this.children = null;
this.style = null;
this.className = null;
this.attrs = null;
this.events = null;
this.hooks = null;
this.key = null;
this.clipData = null;
}
VNode.prototype = {
setAttrs: function setAttrs(attrs) {
this.attrs = attrs;
return this;
},
setTag: function setTag(tag) {
this.tag = tag;
return this;
},
setStyle: function setStyle(style) {
this.style = style;
return this;
},
setClassName: function setClassName(className) {
this.className = className;
return this;
},
setChildren: function setChildren(children) {
this.children = children;
return this;
},
setHooks: function setHooks(hooks) {
this.hooks = hooks;
return this;
},
setEvents: function setEvents(events) {
this.events = events;
return this;
},
setKey: function setKey(key) {
this.key = key;
return this;
}
};
function createVNode(bp) {
return new VNode(bp);
}
function createBlueprint(shape, childrenType) {
var tag = shape.tag || null;
var tagIsDynamic = tag && tag.arg !== void 0 ? true : false;
var children = !isNullOrUndefined(shape.children) ? shape.children : null;
var childrenIsDynamic = children && children.arg !== void 0 ? true : false;
var attrs = shape.attrs || null;
var attrsIsDynamic = attrs && attrs.arg !== void 0 ? true : false;
var hooks = shape.hooks || null;
var hooksIsDynamic = hooks && hooks.arg !== void 0 ? true : false;
var events = shape.events || null;
var eventsIsDynamic = events && events.arg !== void 0 ? true : false;
var key = shape.key !== void 0 ? shape.key : null;
var keyIsDynamic = !isNullOrUndefined(key) && !isNullOrUndefined(key.arg);
var style = shape.style || null;
var styleIsDynamic = style && style.arg !== void 0 ? true : false;
var className = shape.className !== void 0 ? shape.className : null;
var classNameIsDynamic = className && className.arg !== void 0 ? true : false;
var blueprint = {
lazy: shape.lazy || false,
dom: null,
pools: {
keyed: {},
nonKeyed: []
},
tag: !tagIsDynamic ? tag : null,
className: className !== '' && className ? className : null,
style: style !== '' && style ? style : null,
isComponent: tagIsDynamic,
hasAttrs: attrsIsDynamic || (attrs ? true : false),
hasHooks: hooksIsDynamic,
hasEvents: eventsIsDynamic,
hasStyle: styleIsDynamic || (style !== '' && style ? true : false),
hasClassName: classNameIsDynamic || (className !== '' && className ? true : false),
childrenType: childrenType === void 0 ? children ? 5 : 0 : childrenType,
attrKeys: null,
eventKeys: null,
isSVG: shape.isSVG || false
};
return function () {
var vNode = new VNode(blueprint);
if (tagIsDynamic === true) {
vNode.tag = arguments[tag.arg];
}
if (childrenIsDynamic === true) {
vNode.children = arguments[children.arg];
}
if (attrsIsDynamic === true) {
vNode.attrs = arguments[attrs.arg];
} else {
vNode.attrs = attrs;
}
if (hooksIsDynamic === true) {
vNode.hooks = arguments[hooks.arg];
}
if (eventsIsDynamic === true) {
vNode.events = arguments[events.arg];
}
if (keyIsDynamic === true) {
vNode.key = arguments[key.arg];
}
if (styleIsDynamic === true) {
vNode.style = arguments[style.arg];
} else {
vNode.style = blueprint.style;
}
if (classNameIsDynamic === true) {
vNode.className = arguments[className.arg];
} else {
vNode.className = blueprint.className;
}
return vNode;
};
}
// Runs only once in applications lifetime
var isBrowser = typeof window !== 'undefined' && window.document;
// Copy of the util from dom/util, otherwise it makes massive bundles
function documentCreateElement(tag, isSVG) {
var dom = void 0;
if (isSVG === true) {
dom = document.createElementNS('http://www.w3.org/2000/svg', tag);
} else {
dom = document.createElement(tag);
}
return dom;
}
function createUniversalElement(tag, attrs, isSVG) {
if (isBrowser) {
var dom = documentCreateElement(tag, isSVG);
if (attrs) {
createStaticAttributes(attrs, dom);
}
return dom;
}
return null;
}
function createStaticAttributes(attrs, dom) {
var attrKeys = Object.keys(attrs);
for (var i = 0; i < attrKeys.length; i++) {
var attr = attrKeys[i];
var value = attrs[attr];
if (attr === 'className') {
dom.className = value;
} else {
if (value === true) {
dom.setAttribute(attr, attr);
} else if (!isNullOrUndefined(value) && value !== false && !isAttrAnEvent(attr)) {
dom.setAttribute(attr, value);
}
}
}
}
var index = {
createBlueprint: createBlueprint,
createVNode: createVNode,
universal: {
createElement: createUniversalElement
}
};
return index;
})); | sashberd/cdnjs | ajax/libs/inferno/0.7.3/inferno.js | JavaScript | mit | 6,896 | [
30522,
1013,
1008,
999,
1008,
21848,
1058,
2692,
1012,
1021,
1012,
1017,
1008,
1006,
1039,
1007,
2355,
11282,
25957,
2532,
4576,
1008,
2207,
2104,
1996,
6131,
2140,
1011,
1016,
1012,
1014,
6105,
1012,
1008,
1013,
1006,
3853,
1006,
3795,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* #%L
* FlatPack serialization code
* %%
* Copyright (C) 2012 Perka Inc.
* %%
* 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.
* #L%
*/
package com.getperka.flatpack.codex;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import org.junit.Test;
import com.getperka.flatpack.FlatPackTest;
import com.getperka.flatpack.HasUuid;
import com.getperka.flatpack.codexes.ArrayCodex;
import com.getperka.flatpack.codexes.ListCodex;
import com.getperka.flatpack.codexes.SetCodex;
import com.getperka.flatpack.domain.Employee;
import com.getperka.flatpack.domain.Person;
import com.getperka.flatpack.util.FlatPackCollections;
import com.google.inject.TypeLiteral;
/**
* Tests serializing collections of things.
*/
public class CollectionCodexTest extends FlatPackTest {
@Inject
private TypeLiteral<ArrayCodex<Person>> arrayPerson;
@Inject
private TypeLiteral<ArrayCodex<String>> arrayString;
@Inject
private TypeLiteral<ListCodex<Person>> listPerson;
@Inject
private TypeLiteral<ListCodex<String>> listString;
@Inject
private TypeLiteral<SetCodex<String>> setString;
@Inject
private Employee employee;
@Test
public void testArray() {
String[] in = { "Hello", " ", "", null, "World!" };
String[] out = testCodex(arrayString, in);
assertArrayEquals(in, out);
Set<HasUuid> scanned = FlatPackCollections.setForIteration();
Employee[] in2 = { employee, null, employee };
Person[] out2 = testCodex(arrayPerson, in2, scanned);
assertEquals(Collections.singleton(employee), scanned);
/*
* Because we're testing without a full flatpack structure, all we can expect is that a HasUuid
* is created with the same UUID. The concrete type would normally be specified in the data
* section, however it is missing, so we expect the configured type of the codex instead.
*/
Person p = out2[0];
assertNotNull(p);
assertEquals(Person.class, p.getClass());
assertEquals(employee.getUuid(), p.getUuid());
}
@Test
public void testList() {
List<String> in = Arrays.asList("Hello", " ", "", null, "World!");
Collection<String> out = testCodex(listString, in);
assertEquals(in, out);
Set<HasUuid> scanned = FlatPackCollections.setForIteration();
List<Person> in2 = Arrays.<Person> asList(employee, null, employee);
Collection<Person> out2 = testCodex(listPerson, in2, scanned);
assertEquals(Collections.singleton(employee), scanned);
/*
* Because we're testing without a full flatpack structure, all we can expect is that a HasUuid
* is created with the same UUID. The concrete type would normally be specified in the data
* section, however it is missing, so we expect the configured type of the codex instead.
*/
Person p = ((List<Person>) out2).get(0);
assertNotNull(p);
assertEquals(Person.class, p.getClass());
assertEquals(employee.getUuid(), p.getUuid());
}
@Test
public void testNull() {
assertNull(testCodex(arrayString, null));
assertNull(testCodex(listString, null));
assertNull(testCodex(setString, null));
}
@Test
public void testSet() {
Set<String> in = new LinkedHashSet<String>(Arrays.asList("Hello", " ", "", null, "World!"));
Set<String> out = testCodex(setString, in);
assertEquals(in, out);
}
}
| perka/flatpack-java | core/src/test/java/com/getperka/flatpack/codex/CollectionCodexTest.java | Java | apache-2.0 | 4,155 | [
30522,
1013,
1008,
1008,
1001,
1003,
1048,
1008,
4257,
23947,
7642,
3989,
3642,
1008,
1003,
1003,
1008,
9385,
1006,
1039,
1007,
2262,
2566,
2912,
4297,
1012,
1008,
1003,
1003,
1008,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* Framework APIs (global - app.*)
*
* Note: View APIs are in view.js (view - view.*)
*
* @author Tim Lauv
* @created 2015.07.29
* @updated 2017.04.04
*/
;(function(app){
/**
* Universal app object creation api entry point
* ----------------------------------------------------
* @deprecated Use the detailed apis instead.
*/
app.create = function(type, config){
console.warn('DEV::Application::create() method is deprecated, use methods listed in ', app._apis, ' for alternatives');
};
/**
* Detailed api entry point
* ------------------------
* If you don't want to use .create() there you go:
*/
_.extend(app, {
//----------------view------------------
//pass in [name,] options to define view (named view will be registered)
//pass in name to get registered view def
//pass in options, true to create anonymous view
view: function(name /*or options*/, options /*or instance flag*/){
if(_.isString(name) && _.isPlainObject(options)){
return app.Core.View.register(name, options);
}
if(_.isPlainObject(name)){
var instance = options;
options = name;
var Def = app.Core.View.register(options);
if(_.isBoolean(instance) && instance) return Def.create();
return Def;
}
return app.Core.View.get(name);
},
//@deprecated---------------------
//pass in [name,] options to register (always requires a name)
//pass in [name] to get (name can be of path form)
context: function(name /*or options*/, options){
if(!options) {
if(_.isString(name) || !name)
return app.Core.Context.get(name);
else
options = name;
}
else
_.extend(options, {name: name});
console.warn('DEV::Application::context() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/);
return app.Core.Context.register(options);
},
//--------------------------------
//pass in name, factory to register
//pass in name, options to create
//pass in [name] to get (name can be of path form)
widget: function(name, options /*or factory*/){
if(!options) return app.Core.Widget.get(name);
if(_.isFunction(options))
//register
return app.Core.Widget.register(name, options);
return app.Core.Widget.create(name, options);
//you can not register the definition when providing name, options.
},
//pass in name, factory to register
//pass in name, options to create
//pass in [name] to get (name can be of path form)
editor: function(name, options /*or factory*/){
if(!options) return app.Core.Editor.get(name);
if(_.isFunction(options))
//register
return app.Core.Editor.register(name, options);
return app.Core.Editor.create(name, options);
//you can not register the definition when providing name, options.
},
//@deprecated---------------------
regional: function(name, options){
options = options || {};
if(_.isString(name))
_.extend(options, {name: name});
else
_.extend(options, name);
console.warn('DEV::Application::regional() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/);
return app.view(options, !options.name);
},
//--------------------------------
//(name can be of path form)
has: function(name, type){
type = type || 'View';
if(name)
return app.Core[type] && app.Core[type].has(name);
_.each(['Context', 'View', 'Widget', 'Editor'], function(t){
if(!type && app.Core[t].has(name))
type = t;
});
return type;
},
//(name can be of path form)
//always return View definition.
get: function(name, type, options){
if(!name)
return {
'Context': app.Core.Context.get(),
'View': app.Core.View.get(),
'Widget': app.Core.Widget.get(),
'Editor': app.Core.Editor.get()
};
if(_.isPlainObject(type)){
options = type;
type = undefined;
}
var Reusable, t = type || 'View';
options = _.extend({fallback: false, override: false}, options);
//try local
if(!options.override)
Reusable = (app.Core[t] && app.Core[t].get(name)) || (options.fallback && app.Core['View'].get(name));
//try remote, if we have app.viewSrcs set to load the View def dynamically
if(!Reusable && app.config && app.config.viewSrcs){
var targetJS = _.compact([app.config.viewSrcs, t.toLowerCase()/*not view.category yet*/, app.nameToPath(name)]).join('/') + '.js';
app.inject.js(
targetJS, true //sync
).done(function(){
app.debug(t, name, 'injected', 'from', app.config.viewSrcs);
if(app.has(name, t) || (options.fallback && app.has(name)))
Reusable = app.get(name, t, {fallback: true});
else
throw new Error('DEV::Application::get() loaded definitions other than required ' + name + ' of type ' + t + ' from ' + targetJS + ', please check your view name in that file!');
}).fail(function(jqXHR, settings, e){
if(!options.fallback || (t === 'View'))
throw new Error('DEV::Application::get() can NOT load definition for ' + name + ' - [' + e + ']');
else
Reusable = app.get(name, 'View');
});
}
return Reusable;
},
//**Caveat**: spray returns the region (created on $anchor), upon returning, its 'show' event has already passed.
spray: function($anchor, View /*or template or name or instance or options or svg draw(paper){} func */, options, parentCt){
var $el = $($anchor);
parentCt = parentCt || app.mainView;
//check if $anchor is already a region
var region = $el.data('region');
var regionName = region && region._name;
if(!regionName){
regionName = $el.attr('region') || _.uniqueId('anonymous-region-');
$el.attr('region', regionName);
region = parentCt.addRegion(regionName, '[region="' + regionName + '"]');
region.ensureEl(parentCt);
} else
parentCt = region.parentCt;
//see if it is an svg draw(paper){} function
if(_.isFunction(View) && View.length === 1){
//svg
return parentCt.show(regionName, {
template: '<div svg="canvas"></div>',
data: options && options.data, //only honor options.data if passed in.
svg: {
canvas: View
},
onPaperCleared: function(paper){
paper._fit($el);
},
});
}else
//view
return parentCt.show(regionName, View, options); //returns the sub-regional view.
},
icing: function(name, flag, View, options){
if(_.isBoolean(name)){
options = View;
View = flag;
flag = name;
name = 'default';
}
var regionName = ['icing', 'region', name].join('-');
if(!app.mainView.getRegion(regionName) && !_.isBoolean(name)){
options = flag;
View = name;
flag = true;
name = 'default';
}
regionName = ['icing', 'region', name].join('-');
var ir = app.mainView.getRegion(regionName);
if(flag === false){
ir.$el.hide();
ir.currentView && ir.currentView.close();
}
else {
ir.$el.show();
app.mainView.show(regionName, View, options);
}
},
coop: function(event){
var args = _.toArray(arguments);
args.unshift('app:coop');
app.trigger.apply(app, args);
args = args.slice(2);
args.unshift('app:coop-' + event);
app.trigger.apply(app, args);
return app;
},
pathToName: function(path){
if(!_.isString(path)) throw new Error('DEV::Application::pathToName() You must pass in a valid path string.');
if(_.contains(path, '.')) return path;
return path.split('/').map(_.string.humanize).map(_.string.classify).join('.');
},
nameToPath: function(name){
if(!_.isString(name)) throw new Error('DEV::Application::nameToPath() You must pass in a Reusable view name.');
if(_.contains(name, '/')) return name;
return name.split('.').map(_.string.humanize).map(_.string.slugify).join('/');
},
//----------------navigation-----------
navigate: function(options, silent){
return app.trigger('app:navigate', options, silent);
},
navPathArray: function(){
return _.compact(window.location.hash.replace('#navigate', '').split('/'));
},
//-----------------mutex---------------
lock: function(topic){
return app.Core.Lock.lock(topic);
},
unlock: function(topic){
return app.Core.Lock.unlock(topic);
},
available: function(topic){
return app.Core.Lock.available(topic);
},
//-----------------remote data------------
//returns jqXHR object (use promise pls)
remote: function(options /*or url*/, payload, restOpt){
options = options || {};
if(options.payload || payload){
payload = options.payload || payload;
return app.Core.Remote.change(options, _.extend({payload: payload}, restOpt));
}
else
return app.Core.Remote.get(options, restOpt);
},
download: function(ticket /*or url*/, options /*{params:{...}} only*/){
return app.Util.download(ticket, options);
},
upload: function(url, options){
return app.Util.upload(url, options);
},
//data push
//(ws channels)
_websockets: {},
/**
* returns a promise.
*
* Usage
* -----
* register: app.config.defaultWebsocket or app.ws(socketPath);
* receive (e): view.coop['ws-data-[channel]'] or app.onWsData = custom fn;
* send (json): app.ws(socketPath)
* .then(function(ws){ws.channel(...).json({...});}); default per channel data
* .then(function(ws){ws.send(); or ws.json();}); anything by any contract
* e.websocket = ws in .then(function(ws){})
*
* Default messaging contract
* --------------------------
* Nodejs /devserver: json {channel: '..:..', payload: {..data..}} through ws.channel('..:..').json({..data..})
* Python ASGI: json {stream: '...', payload: {..data..}} through ws.stream('...').json({..data..})
*
* Reconnecting websockets
* -----------------------
* websocket path ends with '+' will be reconnecting websocket when created.
*
*/
ws: function(socketPath, coopEvent /*or callback or options*/){
if(!app.detect('websockets')) throw new Error('DEV::Application::ws() Websocket is not supported by your browser!');
socketPath = socketPath || app.config.defaultWebsocket || '/ws';
var reconnect = false;
if(_.string.endsWith(socketPath, '+')){
socketPath = socketPath.slice(0, socketPath.length - 1);
reconnect = true;
}
var d = $.Deferred();
if(!app._websockets[socketPath]) {
app._websockets[socketPath] = new WebSocket(location.protocol.replace('http', 'ws') + '//' + location.host + socketPath);
app._websockets[socketPath].path = socketPath;
app._websockets[socketPath].reconnect = reconnect;
//events: 'open', 'error', 'close', 'message' = e.data
//apis: send(), +json(), +channel().json(), close()
app._websockets[socketPath].json = function(data){
app._websockets[socketPath].send(JSON.stringify(data));
};
app._websockets[socketPath].channel = function(channel){
return {
name: channel,
websocket: app._websockets[socketPath],
json: function(data){
app._websockets[socketPath].json({
channel: channel,
stream: channel, //alias for ASGI backends
payload: data
});
}
};
};
app._websockets[socketPath].stream = app._websockets[socketPath].channel; //alias for ASGI backends
app._websockets[socketPath].onclose = function(){
var ws = app._websockets[socketPath];
delete app._websockets[socketPath];
if(ws.reconnect)
app.ws(ws.path + '+');
};
app._websockets[socketPath].onopen = function(){
return d.resolve(app._websockets[socketPath]);
};
//general ws data stub
//server need to always send default json contract string {"channel/stream": "...", "payload": "..."}
//Opt: override this through app.ws(path).then(function(ws){ws.onmessage=...});
app._websockets[socketPath].onmessage = function(e){
//opt a. override app.onWsData to active otherwise
app.trigger('app:ws-data', {websocket: app._websockets[socketPath], raw: e.data});
//opt b. use global coop event 'ws-data-[channel]' in views directly (default json contract)
try {
var data = JSON.parse(e.data);
app.coop('ws-data-' + (data.channel || data.stream), data.payload, app._websockets[socketPath].channel(data.channel || data.stream));
}catch(ex){
console.warn('DEV::Application::ws() Websocket is getting non-default {channel: ..., payload: ...} json contract strings...');
}
};
//register coopEvent or callback function or callback options
if(coopEvent){
//onmessage callback function
if(_.isFunction(coopEvent)){
//overwrite onmessage callback function defined by framework
app._websockets[socketPath].onmessage = function(e){
coopEvent(e.data, e, app._websockets[socketPath]);
};
}
//object may contain onmessage, onerror, since onopen and onclose is done by the framework
else if(_.isPlainObject(coopEvent)){
//traverse through object to register all callback events
_.each(coopEvent, function(fn, eventName){
//guard events
if(_.contains(['onmessage', 'onerror'], eventName))
app._websockets[socketPath][eventName] = fn;
});
}
//app coop event
else if(_.isString(coopEvent)){
//trigger coop event with data from sse's onmessage callback
app._websockets[socketPath].onmessage = function(e){
app.coop('ws-data-' + coopEvent, e.data, e, app._websockets[socketPath]);
};
}
//type is not right
else
console.warn('DEV::Application::ws() The coopEvent or callback function or callbacks\' options you give is not right.');
}
}else
d.resolve(app._websockets[socketPath]);
return d.promise();
},
//data polling
//(through later.js) and emit data events/or invoke callback
_polls: {},
poll: function(url /*or {options} for app.remote()*/, occurrence, coopEvent /*or callback or options*/) {
//stop everything
if (url === false){
return _.map(this._polls, function(card) {
return card.cancel();
});
}
var schedule;
if (_.isString(occurrence) && !Number.parseInt(occurrence)) {
schedule = app.later.parse.text(occurrence);
if (schedule.error !== -1)
throw new Error('DEV::Application::poll() occurrence string unrecognizable...');
} else if (_.isPlainObject(occurrence))
schedule = occurrence;
else //number
schedule = Number(occurrence);
//make a key from url, or {url: ..., params/querys}
var key = url;
if (_.isPlainObject(key))
key = [key.url, _.reduce((_.map(key.params || key.querys, function(qV, qKey) {
return [qKey, qV].join('=');
})).sort(), function(qSignature, more) {
return [more, qSignature].join('&');
}, '')].join('?');
//cancel polling
if (occurrence === false) {
if (this._polls[key])
return this._polls[key].cancel();
console.warn('DEV::Application::poll() No polling card registered yet for ' + key);
return;
}
//cancel previous polling
if (this._polls[key])
this._polls[key].cancel();
//register polling card
if (!occurrence || !coopEvent)
throw new Error('DEV::Application::poll() You must specify an occurrence and a coop event or callback...');
var card = {
_key: key,
url: url,
eof: coopEvent,
timerId: undefined,
failed: 0,
valid: true,
occurrence: occurrence, //info only
};
this._polls[key] = card;
var call = _.isNumber(schedule) ? window.setTimeout : app.later.setTimeout;
//if coopEvent is an object. register options events before calling app.remote
if(_.isPlainObject(coopEvent)){
//save url
var temp = url;
//build url as an object for app.remote
url = {
url: temp
};
_.each(coopEvent, function(fn, eventName){
//guard for only allowing $.ajax events
if(_.contains(['beforeSend', 'error', 'dataFilter', 'success', 'complete'], eventName))
url[eventName] = fn;
});
}
var worker = function() {
app.remote(url).done(function(data) {
//callback
if (_.isFunction(card.eof))
card.eof(data, card);
//coop event
else
app.coop('poll-data-' + card.eof, data, card);
}).fail(function() {
card.failed++;
//Warning: Hardcoded 3 attemps here!
if (card.failed >= 3) card.cancel();
}).always(function() {
//go schedule the next call
if (card.valid)
card.timerId = call(worker, schedule);
});
};
//+timerType
card.timerType = (call === window.setTimeout) ? 'native' : 'later.js';
//+cancel()
var that = this;
card.cancel = function() {
this.valid = false;
if (this.timerType === 'native')
!_.isUndefined(this.timerId) && window.clearTimeout(this.timerId);
else
!_.isUndefined(this.timerId) && this.timerId.clear();
delete that._polls[this._key];
return this;
};
//make the 1st call (eagerly)
worker();
},
//-----------------ee/observer with built-in state-machine----------------
//use start('stateB') or trigger('stateA-->stateB') to swap between states
//use ['stateA-->stateB', 'stateC<-->stateB', 'stateA<--stateC', ...] in edges to constrain state changes.
ee: function(data, evtmap, edges){ //+on/once, off, +start/reset/stop/getState/getEdges; +listenTo/Once, stopListening; +trigger*;
var dispatcher;
data = _.extend({}, data, {cid: _.uniqueId('ee')});
evtmap = _.extend({
'initialize': _.noop,
'finalize': _.noop,
}, evtmap);
edges = _.reduce(edges || {}, function(mem, val, index){
var bi = val.match('(.*)<-->(.*)'),
left = val.match('(.*)<--(.*)'),
right = val.match('(.*)-->(.*)');
if(bi){
mem[bi[1] + '-->' + bi[2]] = true;
mem[bi[2] + '-->' + bi[1]] = true;
} else if (left)
mem[left[2] + '-->' + left[1]] = true;
else if (right)
mem[val] = true;
else
console.warn('DEV::Application::ee() illegal edge format: ' + val);
return mem;
}, {});
if(!_.size(edges)) edges = undefined;
dispatcher = _.extend(data, Backbone.Events);
var oldTriggerFn = dispatcher.trigger;
var currentState = '';
//add a state-machine friendly .trigger method;
dispatcher.trigger = function(){
var changeOfStates = arguments[0] && arguments[0].match('(.*)-->(.*)');
if(changeOfStates && changeOfStates.length){
var from = _.string.trim(changeOfStates[1]), to = _.string.trim(changeOfStates[2]);
//check edge constraints
if(from && to && edges && !edges[arguments[0]]){
console.warn('DEV::Application::ee() edge constraint: ' + from + '-x->' + to);
return this;
}
//check current state
if(from != currentState){
console.warn('DEV::Application::ee() current state is ' + (currentState || '\'\'') + ' not ' + from);
return this;
}
this.trigger('leave', {to: to});
//unregister event listeners in [from] state
_.each(evtmap[from], function(listener, e){
dispatcher.off(from + ':' + e);
});
//register event listeners in [to] state
_.each(evtmap[to], function(listener, e){
dispatcher.on(to + ':' + e, listener);
});
currentState = to;
this.trigger('enter', {from: from});
} else {
if(evtmap[currentState] && evtmap[currentState][arguments[0]])
arguments[0] = currentState + ':' + arguments[0];
oldTriggerFn.apply(this, arguments);
}
return this;
};
//add an internal worker swap method;
dispatcher._swap = function(targetState){
targetState = targetState || '';
this.trigger(currentState + '-->' + targetState);
return this;
};
//add a start method; (start at any state)
dispatcher.start = function(targetState){
targetState = targetState || currentState;
return this._swap(targetState);
};
//add a reset method; (reset to '' state)
dispatcher.reset = function(){
return this._swap();
};
//add a clean-up method;
dispatcher.stop = function(){
this.trigger('finalize');
this.off();
this.stopListening();
};
//add some getters;
dispatcher.getState = function(){
return currentState;
};
dispatcher.getEdges = function(){
return edges;
};
//mount shared events
_.each(evtmap, function(listener, eOrStateName){
if(!_.isFunction(listener)) return;
dispatcher.on(eOrStateName, listener);
});
this.trigger('initialize');
return dispatcher;
},
model: function(data, flat){
if(_.isBoolean(data)){
flat = data;
data = undefined;
}
if(flat)
return new Backbone.Model(data);
//Warning: Possible performance impact...(default)
return new Backbone.DeepModel(data);
/////////////////////////////////////////
},
collection: function(data){
if(data && !_.isArray(data))
throw new Error('DEV::Application::collection You need to specify an array to init a collection');
return new Backbone.Collection(data);
},
//bridge extract from app.Util.deepObjectKeys
extract: function(keypath, from){
return app.Util.deepObjectKeys.extract(keypath, from);
},
//bridge pack from app.Util.deepObjectKeys
pack: function(keypathObj, to){
return app.Util.deepObjectKeys.pack(keypathObj, to);
},
mock: function(schema, provider/*optional*/, url/*optional*/){
return app.Util.mock(schema, provider, url);
},
//----------------url params---------------------------------
param: function(key, defaultVal){
var params = app.uri(window.location.href).search(true) || {};
if(key) return params[key] || defaultVal;
return params;
},
//----------------raw animation (DON'T mix with jQuery fx)---------------
//(specifically, don't call $.animate() inside updateFn)
//(you also can NOT control the rate the browser calls updateFn, its 60 FPS all the time...)
animation: function(updateFn, condition, ctx){
var id;
var stepFn = function(t){
updateFn.call(ctx);//...update...(1 tick)
if(!condition || (condition && condition.call(ctx)))//...condition...(to continue)
move();
};
var move = function(){
if(id === undefined) return;
id = app._nextFrame(stepFn);
};
var stop = function(){
app._cancelFrame(id);
id = undefined;
};
return {
start: function(){id = -1; move();},
stop: stop
};
},
_nextFrame: function(stepFn){
//return request id
return window.requestAnimationFrame(stepFn);
},
_cancelFrame: function(id){
return window.cancelAnimationFrame(id);
},
//effects see https://daneden.github.io/animate.css/
//sample usage: 'ready' --> app.animateItems();
animateItems: function(selector /*or $items*/, effect, stagger){
var $selector = $(selector);
if(_.isNumber(effect)){
stagger = effect;
effect = undefined;
}
effect = effect || 'flipInX';
stagger = stagger || 150;
var inOrOut = /In/.test(effect)? 1: (/Out/.test(effect)? -1: 0);
$selector.each(function(i, el){
var $el = $(el);
//////////////////different than region.show effect because of stagger delay//////////////////
if(inOrOut)
if(inOrOut === 1) $el.css('opacity', 0);
else $el.css('opacity', 1);
//////////////////////////////////////////////////////////////////////////////////////////////
_.delay(function($el){
var fxName = effect + ' animated';
$el.anyone(app.ADE, function(){
$el.removeClass(fxName);
}).addClass(fxName);
///////////////reset opacity immediately, not after ADE///////////////
if(inOrOut)
if(inOrOut === 1) $el.css('opacity', 1);
else $el.css('opacity', 0);
//////////////////////////////////////////////////////////////////////
}, i * stagger, $el);
});
},
//Built-in web worker utility, bridged from app.Util.worker.
worker: function(name/*web worker's name*/, coopEOrCallbackOrOpts){
return app.Util.worker(name, coopEOrCallbackOrOpts);
},
//Built-in Server-Sent Event(SSE) utility, bridged from app.Util.sse
sse: function(url/*sse's url*/, topics/*['...', '...']*/, coopEOrCallbackOrOpts){
return app.Util.sse(url, topics, coopEOrCallbackOrOpts);
},
//----------------config.rapidEventDelay wrapped util--------------------
//**Caveat**: if using cached version, pass `this` and other upper scope vars into fn as arguments, else
//these in fn will be cached forever and might no longer exist or point to the right thing when called...
throttle: function(fn, ms, cacheId){
ms = ms || app.config.rapidEventDelay;
fn = _.throttle(fn, ms);
if(!cacheId)
return fn;
//cached version (so you can call right after wrapping it)
this._tamedFns = this._tamedFns || {};
var key = fn + cacheId + '-throttle' + ms;
if(!this._tamedFns[key])
this._tamedFns[key] = fn;
return this._tamedFns[key];
},
debounce: function(fn, ms, cacheId){
ms = ms || app.config.rapidEventDelay;
fn = _.debounce(fn, ms);
if(!cacheId)
return fn;
//cached version (so you can call right after wrapping it)
this._tamedFns = this._tamedFns || {};
var key = fn + cacheId + '-debounce' + ms;
if(!this._tamedFns[key])
this._tamedFns[key] = fn;
return this._tamedFns[key];
},
//app wide e.preventDefault() util
preventDefaultE: function(e){
var $el = $(e.target);
//Caveat: this clumsy bit here is due to the in-ability to check on the 'action-*' attributes on e.target...
if($el.is('label') || $el.is('i') || $el.is('img') || $el.is('span') || $el.is('input') || $el.is('textarea') || $el.is('select') || ($el.is('a') && $el.attr('href')))
return;
e.preventDefault();
},
//wait until all targets fires e (asynchronously) then call the callback with targets (e.g [this.show(), ...], 'ready')
until: function(targets, e, callback){
targets = _.compact(targets);
cb = _.after(targets.length, function(){
callback(targets);
});
_.each(targets, function(t){
t.once(e, cb);
});
},
//----------------markdown-------------------
//options.marked, options.hljs
//https://guides.github.com/features/mastering-markdown/
//our addition:
// ^^^class class2 class3 ...
// ...
// ^^^
markdown: function(md, $anchor /*or options*/, options){
options = options || (!_.isjQueryObject($anchor) && $anchor) || {};
//render content
var html = marked(md, app.debug('marked options are', _.extend(app.config.marked, (options.marked && options.marked) || options, _.isjQueryObject($anchor) && $anchor.data('marked')))), hljs = window.hljs;
//highlight code (use ```language to specify type)
if(hljs){
hljs.configure(app.debug('hljs options are', _.extend(app.config.hljs, options.hljs, _.isjQueryObject($anchor) && $anchor.data('hljs'))));
var $html = $('<div>' + html + '</div>');
$html.find('pre code').each(function(){
hljs.highlightBlock(this);
});
html = $html.html();
}
if(_.isjQueryObject($anchor))
return $anchor.html(html).addClass('md-content');
return html;
},
//----------------notify/overlay/popover---------------------
notify: function(title /*or options*/, msg, type /*or otherOptions*/, otherOptions){
if(_.isString(title)){
if(_.isPlainObject(type)){
otherOptions = type;
type = undefined;
}
if(otherOptions && otherOptions.icon){
//theme awesome ({.icon, .more})
$.amaran(_.extend({
theme: 'awesome ' + (type || 'ok'),
//see http://ersu.me/article/amaranjs/amaranjs-themes for types
content: {
title: title,
message: msg,
info: otherOptions.more || ' ',
icon: otherOptions.icon
}
}, otherOptions));
} else {
//custom theme
$.amaran(_.extend({
content: {
themeName: 'stagejs',
title: title,
message: msg,
type: type || 'info',
},
themeTemplate: app.NOTIFYTPL
}, otherOptions));
}
}
else
$.amaran(title);
},
//overlay or popover
prompt: function(view, anchor, placement, options){
if(_.isFunction(view))
view = new view();
else if(_.isString(view))
view = app.get(view).create();
//is popover
if(_.isString(placement)){
options = options || {};
options.placement = placement;
return view.popover(anchor, options);
}
//is overlay
options = placement;
return view.overlay(anchor, options);
},
//----------------i18n-----------------------
i18n: function(key, ns){
if(key){
//insert translations to current locale
if(_.isPlainObject(key))
return I18N.insertTrans(key);
//return a translation for specified key, ns/module
return String(key).i18n(ns);
}
//otherwise, collect available strings (so far) into an i18n object.
return I18N.getResourceJSON(null, false);
},
//----------------debug----------------------
//bridge app.debug()
debug: function(){
return app.Util.debugHelper.debug.apply(null, arguments);
},
//bridge app.locate()
locate: function(name /*el or $el*/){
return app.Util.debugHelper.locate(name);
},
//bridge app.profile()
profile: function(name /*el or $el*/){
return app.Util.debugHelper.profile(name);
},
//bridge app.mark()
mark: function(name /*el or $el*/){
return app.Util.debugHelper.mark(name);
},
//bridge app.reload()
reload: function(name, override/*optional*/){
return app.Util.debugHelper.reload(name, override);
},
inject: {
js: function(){
return app.Util.inject.apply(null, arguments);
},
tpl: function(){
return app.Util.Tpl.remote.apply(app.Util.Tpl, arguments);
},
css: function(){
return loadCSS.apply(null, arguments);
}
},
detect: function(feature, provider/*optional*/){
if(!provider)
provider = Modernizr;
return app.extract(feature, provider) || false;
},
//--------3rd party lib pass-through---------
// js-cookie (former jquery-cookie)
//.set(), .get(), .remove()
cookie: Cookies,
// store.js (localStorage)
//.set(), .get(), .getAll(), .remove(), .clear()
store: store.enabled && store,
// validator.js (var type and val validation, e.g form editor validation)
validator: validator,
// moment.js (date and time)
moment: moment,
// URI.js (uri,query and hash in the url, e.g in app.param())
uri: URI,
// later.js (schedule repeated workers, e.g in app.poll())
later: later,
// faker.js (mock data generator, e.g in app.mock())
faker: faker,
});
//editor rules
app.editor.validator = app.editor.rule = function(name, fn){
if(!_.isString(name)) throw new Error('DEV::Validator:: You must specify a validator/rule name to use.');
return app.Core.Editor.addRule(name, fn);
};
//alias
app.page = app.context;
app.area = app.regional;
app.curtain = app.icing;
/**
* API summary
*/
app._apis = [
'ee', 'model', 'collection', 'mock',
//view registery
'view', 'widget', 'editor', 'editor.validator - @alias:editor.rule',
//global action locks
'lock', 'unlock', 'available',
//utils
'has', 'get', 'spray', 'coop', 'navigate', 'navPathArray', 'icing/curtain', 'i18n', 'param', 'animation', 'animateItems', 'throttle', 'debounce', 'preventDefaultE', 'until',
//com
'remote', 'download', 'upload', 'ws', 'poll', 'worker', 'sse',
//3rd-party lib short-cut
'extract', 'markdown', 'notify', 'prompt', //wraps
'cookie', 'store', 'moment', 'uri', 'validator', 'later', 'faker', //direct refs
//supportive
'debug', 'detect', 'reload', 'locate', 'profile', 'mark', 'nameToPath', 'pathToName', 'inject.js', 'inject.tpl', 'inject.css',
//@deprecated
'create - @deprecated', 'regional - @deprecated', 'context - @alias:page - @deprecated'
];
/**
* Statics
*/
//animation done events used in Animate.css
//Caveat: if you use $el.one(app.ADE) but still got 2+ callback calls, the browser is firing the default and prefixed events at the same time...
//use $el.anyone() to fix the problem in using $el.one()
app.ADE = 'animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd';
//notification template
app.NOTIFYTPL = Handlebars.compile('<div class="alert alert-dismissable alert-{{type}}"><button data-dismiss="alert" class="close" type="button">×</button><strong>{{title}}</strong> {{{message}}}</div>');
})(Application); | mr-beaver/Stage.js | implementation/js/src/infrastructure/api.js | JavaScript | mit | 32,954 | [
30522,
1013,
1008,
1008,
1008,
7705,
17928,
2015,
1006,
3795,
1011,
10439,
1012,
1008,
30524,
2615,
1008,
1030,
2580,
2325,
1012,
5718,
1012,
2756,
1008,
1030,
7172,
2418,
1012,
5840,
1012,
5840,
1008,
1013,
1025,
1006,
3853,
1006,
10439,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Sunible</title>
<link rel="shortcut icon" href="images/favicon.ico"/>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="css/flat-ui.css"/>
<link rel="stylesheet" type="text/css" href="css/general.css"/>
<link rel="stylesheet" type="text/css" href="css/fonts.css"/>
<link rel="stylesheet" type="text/css" href="css/forms.css"/>
<link rel="stylesheet" type="text/css" href="css/layout.css"/>
<link rel="stylesheet" type="text/css" href="css/pages.css"/>
<!-- IE code -->
<script type="text/javascript">var ie;</script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements. All other JS at the end of file. -->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="css/ie8.css"/>
<script type="text/javascript">ie = 8;</script>
<![endif]-->
<!--[if IE 9]>
<link rel="stylesheet" type="text/css" href="css/ie8.css"/>
<script type="text/javascript">ie = 9;</script>
<![endif]-->
<!--[if lt IE 9]>
<script type="text/javascript" src="js/html5shiv.js"></script>
<![endif]-->
<link href="css/socialproof.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="pages">
<header class="page_header homepage dashboard social_proof registration message"> <!-- header has those classes to be toggled with those pages. With that approach, no need to duplicate the header on each page we have it-->
<div class="questions">
<span class="question why_solar" data-toggle="tooltip" data-placement="bottom" title="Solar is the cleanest. most abundant source of energy on earth. Also, a solar-powered home can save on electricity from day one.">Why solar?</span><span class="question why_sunible" data-toggle="tooltip" data-placement="bottom" title="Like with flights, hotels, insurance or mobile services, there are lots of solar providers out there. We will help you compare, select and contact them. Choice is good!">Why Sunible?</span>
</div>
<a href="/" class="logo sunible"><img src="images/_project/logo_sunible.png"/></a>
</header>
<!-- HOMEPAGE -->
<div class="page homepage show_header" id="page-homepage" data-page="homepage">
<section class="ad teaser container">
<a href="#" class="teaser" id="homepage_teaser_heading">
<span class="save">Save</span>
<span class="money_with">Money with</span>
<span class="solar">Solar</span>
</a>
<form class="zip search providers container" id="homepage-search_providers_by_zip-container">
<span class="field_container">
<input type="text" class="field zip" id="homepage-field-zip_code" name="zipcode" placeholder="Zip Code" pattern="\d{5}(?:[-\s]\d{4})?" value="93210"/>
<span class="validation message"></span>
</span>
<button type="button" class="btn search providers zip" id="homepage-search_providers_by_zip-button">Go</button>
</form>
</section>
</div>
<!-- /HOMEPAGE -->
<!-- SOCIAL PROOF -->
<div class="page social_proof" id="page-social_proof" data-page="social_proof">
<h1>Fantastic, your area is very Sunible!</h1>
<div class="block">
<p>
You have selected<br/>
<span class="counter selected providers number" id="dashboard-block-number_of_providers_selected">0</span>
<br/>
providers
</p>
<p class="max_length message">30 providers max</p>
</div>
<table align="center" width="80%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="25%" align="center"><table width="65px" height="65px" border="0" cellspacing="0" cellpadding="0" style="background-image:url(images/yellowdot.png);">
<tr>
<td width="65px" align="center"><span class="socialproofaligncenterbig">23</span></td>
</tr>
</table>
<p class="socialProofAlignCenter">homes have gone solar in your area</p></td>
<td width="25%" align="center"><table width="65px" height="65px" border="0" cellspacing="0" cellpadding="0" style="background-image:url(images/yellowdot.png);">
<tr>
<td width="65" align="center"><span class="socialproofaligncenterbig">18</span></td>
</tr>
</table>
<p class="socialProofAlignCenter">of them started saving from day one</p></td>
<td width="25%" align="center"><table width="65px" height="65px" border="0" cellspacing="0" cellpadding="0" style="background-image:url(images/yellowdot.png);">
<tr>
<td width="65" align="center"><span class="socialproofaligncenterbig">14</span></td>
</tr>
</table>
<p class="socialProofAlignCenter">experienced solar providers in your area</p></td>
<td width="25%"> <table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<div id="map" style="width: 250px; height: 250px"></div>
<script src="js/leaflet.js"></script>
<script>
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>'
}).addTo(map);
L.marker([51.5, -0.09]).addTo(map)
.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();
L.circle([51.508, -0.11], 500, {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5
}).addTo(map).bindPopup("I am a circle.");
L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(map).bindPopup("I am a polygon.");
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(map);
}
map.on('click', onMapClick);
</script>
</td>
</tr>
</table>
<p class="socialProofAlignCenter">Number of solar homes in zip codes around you</p></td>
</tr>
</table>
<button type="button" class="btn view providers" id="social_proof-view_providers">View providers</button>
</div>
<!-- /SOCIAL PROOF -->
<!-- DASHBOARD -->
<div class="page dashboard" id="page-dashboard" data-page="dashboard">
<!-- <aside class="logo">
<a href="/" class="logo sunible"><img src="images/_project/logo_sunible.png"/></a>
</aside> -->
<section class="providers number_of_selected">
<div class="block">
<p>
You have selected<br/>
<span class="counter selected providers number" id="dashboard-block-number_of_providers_selected">0</span>
<br/>
providers
</p>
<p class="max_length message">30 providers max</p>
</div>
<button type="button" class="btn register" id="dashboard-open_registration_page">Let's get Sunible</button>
</section>
<section class="providers container">
<header>
<p>
<span class="text">Showing</span>
<span class="counter found providers number" id="dashboard-header-number_of_providers_found">25</span><!-- HARDCODE -->
<span class="text">providers. Click to sort by Provider, $/Watt, Homes Installed or Rating</span>
</p>
</header>
<div class="table container">
<table class="providers list grid" id="dashboard-grid-providers-list">
<thead>
<tr>
<th class="checkboxes">
<span class="text">Select</span>
</th>
<th class="name">
<span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span><br/>
<span class="text">Solar Providers</span>
</th>
<th class="cost">
<span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span><br/>
<span class="text">$/Watt</span>
</th>
<th class="number_of_homes_installed">
<span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span>
<br/>
<span class="text">Homes Installed</span>
</th>
<th class="rating">
<span class="question_mark light" data-toggle="tooltip" data-placement="bottom" title="Some tooltip for 'Homes Installed' column.">?</span><br/>
<span class="text">Rating</span>
</th>
</tr>
</thead>
<tbody>
<tr id="provider-10" class="provider row">
<td class="checkboxes">
<label class="checkbox" for="provider-10-checkbox">
<input type="checkbox" value="" id="provider-10-checkbox"/>
</label>
</td>
<td class="name">Arise Solar<img src="images/_project/providers_logos/logo_AriseSolar.png"/></td>
<td class="cost">100</td>
<td class="number_of_homes_installed">12</td>
<td class="rating"><span class="rating_stars has-4_5">*********</span></td>
</tr>
<tr id="provider-09" class="provider row">
<td class="checkboxes">
<label class="checkbox" for="provider-09-checkbox">
<input type="checkbox" value="" id="provider-09-checkbox"/>
</label>
</td>
<td class="name">Real Goods Solar<img src="images/_project/providers_logos/logo_RealGoodsSolar.png"/></td>
<td class="cost">96</td>
<td class="number_of_homes_installed">123</td>
<td class="rating"><span class="rating_stars has-2">****</span></td>
</tr>
<tr id="provider-08" class="provider row">
<td class="checkboxes">
<label class="checkbox" for="provider-08-checkbox">
<input type="checkbox" value="" id="provider-08-checkbox"/>
</label>
</td>
<td class="name">Solar City<img src="images/_project/providers_logos/logo_SolarCity.png"/></td>
<td class="cost">96</td>
<td class="number_of_homes_installed">123</td>
<td class="rating"><span class="rating_stars has-5">**********</span></td>
</tr>
<tr id="provider-07" class="provider row">
<td class="checkboxes">
<label class="checkbox" for="provider-07-checkbox">
<input type="checkbox" value="" id="provider-07-checkbox"/>
</label>
</td>
<td class="name">Sungevity<img src="images/_project/providers_logos/logo_Sungevity.png"/></td>
<td class="cost">96</td>
<td class="number_of_homes_installed">123</td>
<td class="rating"><span class="rating_stars has-1">**</span></td>
</tr>
<tr id="provider-06" class="provider row">
<td class="checkboxes">
<label class="checkbox" for="provider-06-checkbox">
<input type="checkbox" value="" id="provider-06-checkbox"/>
</label>
</td>
<td class="name">Verengo Solar<img src="images/_project/providers_logos/logo_VerengoSolar.png"/></td>
<td class="cost">96</td>
<td class="number_of_homes_installed">123</td>
<td class="rating"><span class="rating_stars has-5">**********</span></td>
</tr>
<tr id="provider-05" class="provider row">
<td class="checkboxes">
<label class="checkbox" for="provider-05-checkbox">
<input type="checkbox" value="" id="provider-05-checkbox"/>
</label>
</td>
<td class="name">Arise Solar<img src="images/_project/providers_logos/logo_AriseSolar.png"/></td>
<td class="cost">100</td>
<td class="number_of_homes_installed">12</td>
<td class="rating"><span class="rating_stars has-3">******</span></td>
</tr>
<tr id="provider-04" class="provider row">
<td class="checkboxes">
<label class="checkbox" for="provider-04-checkbox">
<input type="checkbox" value="" id="provider-04-checkbox"/>
</label>
</td>
<td class="name">Real Goods Solar<img src="images/_project/providers_logos/logo_RealGoodsSolar.png"/></td>
<td class="cost">96</td>
<td class="number_of_homes_installed">123</td>
<td class="rating"><span class="rating_stars has-4">********</span></td>
</tr>
<tr id="provider-03" class="provider row">
<td class="checkboxes">
<label class="checkbox" for="provider-03-checkbox">
<input type="checkbox" value="" id="provider-03-checkbox"/>
</label>
</td>
<td class="name">Solar City<img src="images/_project/providers_logos/logo_SolarCity.png"/></td>
<td class="cost">96</td>
<td class="number_of_homes_installed">123</td>
<td class="rating"><span class="rating_stars has-2_5">*****</span></td>
</tr>
<tr id="provider-02" class="provider row">
<td class="checkboxes">
<label class="checkbox" for="provider-02-checkbox">
<input type="checkbox" value="" id="provider-02-checkbox"/>
</label>
</td>
<td class="name">Sungevity<img src="images/_project/providers_logos/logo_Sungevity.png"/></td>
<td class="cost">96</td>
<td class="number_of_homes_installed">123</td>
<td class="rating"><span class="rating_stars has-2">****</span></td>
</tr>
<tr id="provider-01" class="provider row">
<td class="checkboxes">
<label class="checkbox" for="provider-01-checkbox">
<input type="checkbox" value="" id="provider-01-checkbox"/>
</label>
</td>
<td class="name">Verengo Solar<img src="images/_project/providers_logos/logo_VerengoSolar.png"/></td>
<td class="cost">96</td>
<td class="number_of_homes_installed">123</td>
<td class="rating"><span class="rating_stars has-3">******</span></td>
</tr>
</tbody>
</table>
</div>
</section>
</div>
<!-- /DASHBOARD -->
<!-- REGISTRATION -->
<div class="page registration" id="page-registration" data-page="registration">
<h1>
Registration <small>(Why do we collect this information <span class="question_mark dark" data-toggle="tooltip" data-placement="bottom" title="We collect this information to provide you better service">?</span>)</small>
</h1>
<form id="page-registration-form-register" class="registration_form" name="registration_form">
<p>
My name is
<!-- first name -->
<span class="field_container">
<input type="text" class="field first_name" name="first_name" placeholder="First Name" required />
<span class="validation message"></span>
</span>
<!-- last name -->
<span class="field_container">
<input type="text" class="field last_name" name="last_name" placeholder="Last Name" required/>
<span class="validation message"></span>
</span>, but you can call me
<!-- nickname -->
<span class="field_container">
<input type="text" class="field nickname" name="nickname" placeholder="Nickname" />
<span class="validation message"></span>
</span>.
<br/>
I live at
<!-- street address -->
<span class="field_container">
<input type="text" class="field street_address" name="street_address" placeholder="Street Address" required/>
<span class="validation message"></span>
</span>,
and can be reached on</span>
<!-- phone number -->
<span class="field_container">
<input type="tel" class="field phone_number" name="phone_number" placeholder="Phone Number (xxx)xxx-xxxx" pattern="^\(\d{3}\)\d{3}-\d{4}$" required/>
<span class="validation message"></span>
</span>
<br/>
or
<!-- email -->
<span class="field_container">
<input type="email" class="field email" name="email" placeholder="Email" pattern='(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))' required/>
<span class="validation message"></span>
</span>.
I
<!-- property type -->
<span class="field_container">
<select class="field property_type" name="property_type" id="registration-select-appartment-property-type">
<option>rent</option>
<option>own</option>
</select>
<span class="validation message"></span>
</span>
my place and pay about
<!-- cost per month -->
<span class="field_container">
<input type="text" class="field cost_per_month" name="cost_per_month" placeholder="$/month" min="0" required/>
<span class="validation message"></span>
</span>
<br/>
for electricity to the
<!-- people nature -->
<span class="field_container">
<select class="field people_nature" name="people_nature" id="registration-select-people-nature-type">
<option>good</option>
<option>bad</option>
<option>crazy</option>
</select>
<span class="validation message"></span>
</span>
people at
<!-- electricity provider name -->
<span class="field_container">
<select class="field electricity_provider_name" name="electricity_provider_name" id="registration-select-electricity-company-provider">
<option>Pacific Gas & Electric (PG&E)</option>
<option>Southern California Edison</option>
</select>
<span class="validation message"></span>
</span>
I have a
<!-- roof type -->
<span class="field_container">
<select class="field roof_type" name="roof_type" id="registration-select-roof-type">
<option>tiled</option>
<option>wood shake</option>
<option>composite</option>
<option>flat</option>
<option>“no idea what”</option>
</select>
<span class="validation message"></span>
</span>
roof.
</p>
<button type="button" class="btn send_registration" id="registration-submit_registration_info">Go</button>
</form>
</div>
<!-- /REGISTRATION -->
<!-- THANK YOU -->
<div class="page message" id="page-message" data-page="message"> <!-- This page is dynamic. Use it for messages like "Thank you", "Sorry", "Error", etc -->
<p class="loading message">loading...</p>
</div>
<!-- /THANK YOU -->
<!-- FOOTER -->
<footer class="page_footer homepage social_proof dashboard registration message"> <!-- footer has those classes to be toggled with those pages. With that approach, no need to duplicate the footer on each page we have it-->
<nav class="bottom navigation">
<a href="#">Blog</a>
<a href="#">FAQ</a>
<a href="#">Jobs</a>
<a href="#">Contact</a>
<a href="#">Terms</a>
</nav>
<span class="copyright">© Sunible Inc. 2013</span>
</footer>
</div>
<!-- JS -->
<script type="text/javascript" src="js/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/jquery/jquery.placeholder.js"></script>
<script type="text/javascript" src="js/jquery/jquery.validate.min.js"></script>
<script type="text/javascript" src="js/jquery/additional-methods.min.js"></script>
<script type="text/javascript" src="js/jquery/jquery.dropkick-1.0.0.js"></script>
<script type="text/javascript" src="js/jquery/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="js/bootstrap/bootstrap-tooltip.js"></script>
<script type="text/javascript" src="js/custom_checkbox_and_radio.js"></script>
<script type="text/javascript" src="js/global_methods.js"></script>
<script type="text/javascript" src="js/server_calls.js"></script>
<script type="text/javascript" src="js/validation.js"></script>
<script type="text/javascript" src="js/pages.js"></script>
<script type="text/javascript" src="js/dashboard.js"></script>
<script type="text/javascript" src="js/application_init.js"></script>
</body>
</html> | dhanur/Sunible-Beta | socialProofTest_Tanner.html | HTML | gpl-2.0 | 20,503 | [
30522,
1026,
999,
9986,
13874,
16129,
1028,
1026,
16129,
11374,
1027,
1000,
4372,
1000,
1028,
1026,
2132,
30524,
7903,
2239,
1012,
24582,
2080,
1000,
1013,
1028,
1026,
999,
1011,
1011,
20116,
2015,
1011,
1011,
1028,
1026,
4957,
2128,
2140,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package com.github.twitch4j.helix.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Data
@Setter(AccessLevel.PRIVATE)
@NoArgsConstructor
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ExtensionTransaction {
/**
* Unique identifier of the Bits in Extensions Transaction.
*/
private String id;
/**
* UTC timestamp when this transaction occurred.
*/
private String timestamp;
/**
* Twitch User ID of the channel the transaction occurred on.
*/
private String broadcasterId;
/**
* Twitch Display Name of the broadcaster.
*/
private String broadcasterName;
/**
* Twitch User ID of the user who generated the transaction.
*/
private String userId;
/**
* Twitch Display Name of the user who generated the transaction.
*/
private String userName;
/**
* Enum of the product type. Currently only BITS_IN_EXTENSION.
*/
private String productType;
/**
* Known "product_type" enum values.
*/
public static class ProductType {
// "Currently" only valid product type
public static String BITS_IN_EXTENSION = "BITS_IN_EXTENSION";
}
/**
* JSON Object representing the product acquired, as it looked at the time of the transaction.
*/
private ProductData productData;
@Data
@Setter(AccessLevel.PRIVATE)
@NoArgsConstructor
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ProductData {
/**
* Unique identifier for the product across the extension.
*/
private String sku;
/**
* JSON Object representing the cost to acquire the product.
*/
private Cost cost;
/**
* Display Name of the product.
*/
@JsonProperty("displayName")
private String displayName;
/**
* Flag used to indicate if the product is in development. Either true or false.
*/
@JsonProperty("inDevelopment")
private Boolean inDevelopment;
@Data
@Setter(AccessLevel.PRIVATE)
@NoArgsConstructor
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Cost {
/**
* Number of Bits required to acquire the product.
*/
private Integer amount;
/**
* Always the string “Bits”.
*/
private String type;
/**
* Known "type" enum values
*/
public static class CostType {
// "Currently" only valid cost type.
public static final String BITS = "bits";
}
}
}
}
| PhilippHeuer/twitch4j | rest-helix/src/main/java/com/github/twitch4j/helix/domain/ExtensionTransaction.java | Java | mit | 2,884 | [
30522,
7427,
4012,
1012,
21025,
2705,
12083,
1012,
19435,
2549,
3501,
1012,
25743,
1012,
5884,
1025,
12324,
4012,
1012,
5514,
2595,
19968,
1012,
4027,
1012,
5754,
17287,
3508,
1012,
1046,
3385,
23773,
5686,
21572,
4842,
7368,
1025,
12324,
4... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#include "cxxsource.h"
CxxSource::CxxSource()
{
}
| dmleontiev9000/AsicEditor | Cxx/cxxsource.cpp | C++ | mit | 53 | [
30522,
1001,
2421,
1000,
1039,
20348,
6499,
3126,
3401,
1012,
1044,
1000,
1039,
20348,
6499,
3126,
3401,
1024,
1024,
1039,
20348,
6499,
3126,
3401,
1006,
1007,
1063,
1065,
102,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#ifndef CPPCORO_TESTS_COUNTED_HPP_INCLUDED
#define CPPCORO_TESTS_COUNTED_HPP_INCLUDED
struct counted
{
static int default_construction_count;
static int copy_construction_count;
static int move_construction_count;
static int destruction_count;
int id;
static void reset_counts()
{
default_construction_count = 0;
copy_construction_count = 0;
move_construction_count = 0;
destruction_count = 0;
}
static int construction_count()
{
return default_construction_count + copy_construction_count + move_construction_count;
}
static int active_count()
{
return construction_count() - destruction_count;
}
counted() : id(default_construction_count++) {}
counted(const counted& other) : id(other.id) { ++copy_construction_count; }
counted(counted&& other) : id(other.id) { ++move_construction_count; other.id = -1; }
~counted() { ++destruction_count; }
};
#endif
| lewissbaker/cppcoro | test/counted.hpp | C++ | mit | 1,141 | [
30522,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
1013,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* Created by JetBrains PhpStorm.
* User: Petit
* Date: 20/02/13
* Time: 14:56
* To change this template use File | Settings | File Templates.
*/
namespace Petrae\FichierPlanteBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Categorie
{
/**
* @Assert\NotBlank()
*/
public $name;
} | PetitEucalyptus/symfonyTest | src/Petrae/FichierPlanteBundle/Entity/Categorie.php | PHP | mit | 342 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
2580,
2011,
6892,
10024,
7076,
25718,
19718,
1012,
1008,
5310,
1024,
17268,
1008,
3058,
1024,
2322,
1013,
6185,
1013,
2410,
1008,
2051,
1024,
2403,
1024,
5179,
1008,
2000,
2689,
2023,
23561,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
---
layout: post
title: "对个人要不要进入互联网行业的一些看法"
categories:
- others
tags:
- others
---
> StartTime: 2016-12-11,ModifyTime:2017-04-02
一个典型的热情进入互联网创业公司,失望退出的例子。 在南京两年半,因为所学专业原因以及其他,多多少少接触过不少创业公司和有些经历。大早上某帅气的单身狗学长发我[一篇文章](http://mp.weixin.qq.com/s?__biz=MzA4MTkxMzU3NQ==&mid=2651008248&idx=1&sn=4a9d81aab9c99affdb38dfacebc9c2e9&chksm=847a3f70b30db666f38ae3be7d7527764e95f89501c30ceb1961b46036619bf51b9ab6d3fe3f&mpshare=1&scene=1&srcid=1211IRFtOHsciWTlElXyjAWN#rd),有感于无数小伙伴的迷茫,遂发此文分享一下。
<!---more--->
首先我们得认同一个事实,互联网并不是万能的。虽然现在国内炒的一片火热,但其实这样的创业潮每隔几十年就会在世界上演(并没有查阅史料核实,只是隐约记得美国上世纪,中国90年代也有多次这样的创业潮,那时候可能不一定是互联网创业)。过去可能是美国,今天是中国,后天可能也许在欧洲。从个人所学来看,互联网只是一种普通的升级改造过去社会产业的技术手段,并不是什么灵丹妙药。
对于国家来说,这种创业潮多少会催生出一批优秀的企业,优化以前老旧的企业。
对于个人而言,则是会让无数人认清现实。个人能力不足尽量就不要步子跨太大。不要那么相信自己就是”真命天子“。就算是王子也不一定会娶到他国公主。创业从过去到今天,唯一不变的就是一切以利益为核心。中学教科书里就写了,企业的核心目标就是盈利。就算是现在所谓的社会企业概念,同样它也要盈利,不盈利就是死。避免死亡是每个正常人和企业的基本诉求。虽然看上去为了一个也许伟大的目标,大家一起努力是一件很Wonderful事情,但你首先是自己,不是公司的附属品,不是工作的奴隶。不论你是否拥有一个公司的股份,是否认同它的理念,至少你应该明白自己的底线在哪里。有的人是工作狂,可以牺牲一切时间和精力;但这不代表你必须是这样的人。从来没有一条定律说一定要大家一起疯狂的工作才能使得公司一定成功;从来没有一条定律说个人一定要疯狂工作才能获得成功。时势造英雄。所以如果你认真考虑了自己,如果你的原则或者信仰与创业潮不符合,那么早点退出。别像文章里说的认识这么晚(其实也不算太晚)当然如果你想快速获得成功和经验,的确创业公司是个很好的平台,但是万事有风险,请谨记。 文章里的姑娘我猜也许本身就不是那么喜欢超负荷工作的人,然后偏偏又遇到了不和谐的团队,最后结局肯定悲剧了。就像我也不喜欢长年累月的没有回报的工作,所以我以后也许会经常跳槽,也许在合适的工作岗位上做一辈子。社会的质疑并不代表你多么差劲,你辉煌的时候比宇宙里最亮的星星更闪耀。你只需要为你所做而负责就够了。
生活不止眼前的苟且,不止诗和远方,还有你自己的原则与信仰。文章里主角让我想起了今年6月刚搬到百家湖的时候,有天晚上和隔壁的平面设计师姐姐聊了一会,本来还想给当时离职的她介绍去我当时的公司,但她最后的告诫是“千万别进入创业公司”。现在想想也许是她也经历过类似的经历,然后明白自己想要的吧。不过不得不说,想坚持自己的原则太难了,现在整个社会的舆论环境都在炒热这个话题,你将无可避免。三人成虎的故事大家应该不陌生了(PS:如果忘记赶快去百度)。所以我也经常迷失,不过庆幸的是自己能有时间有机会安静地呆在台北这种小地方里,仿若隔绝人世的想点东西,平复心境。 如果你上面看得眼花缭乱,要么你可以再读一遍,要么你就理解成找对象谈恋爱就行了,合适的才是最好的。有人喜欢狂野,有人喜欢温柔岁月。无论怎样,你喜欢现在的生活就好。此文只是给正在互联网行业挣扎迷茫的孩子以及正在找工作的小伙伴一些参考意见,仅供参考,概不负责XDD
PS:不论成败,创业公司与创业团队都是伟大的,他们的付出和努力让人敬佩。但此文只是站在个人工作的角度来分析,告诉大家一点自己的想法。仁者见仁智者见智。如有对您造成困扰请多包含。
| 0lidaxiang/0lidaxiang.github.io | _posts/others/2016-12-11-some-points-for-internetWork.md | Markdown | mit | 4,691 | [
30522,
1011,
1011,
1011,
9621,
1024,
2695,
2516,
1024,
1000,
100,
100,
1756,
100,
1744,
100,
100,
100,
100,
100,
100,
1945,
100,
1916,
1740,
100,
100,
1901,
1000,
7236,
1024,
1011,
2500,
22073,
1024,
1011,
2500,
1011,
1011,
1011,
1028,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Generated by CoffeeScript 1.7.1
(function() {
var ERROR, IGNORE, WARN;
ERROR = 'error';
WARN = 'warn';
IGNORE = 'ignore';
module.exports = {
coffeescript_error: {
level: ERROR,
message: ''
}
};
}).call(this);
| prehnRA/lintron | src/coffeelint/lib/rules.js | JavaScript | mit | 249 | [
30522,
1013,
1013,
7013,
2011,
4157,
22483,
1015,
1012,
1021,
1012,
1015,
1006,
3853,
1006,
1007,
1063,
13075,
7561,
1010,
8568,
1010,
11582,
1025,
7561,
1027,
1005,
7561,
1005,
1025,
11582,
1027,
1005,
11582,
1005,
1025,
8568,
1027,
1005,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<!-- MOTW-DISABLED saved from url=(0014)about:internet -->
<title>Add grand totals</title>
<link rel="StyleSheet" href="css/crosstab.css" type="text/css" media="all" />
<link rel="StyleSheet" href="css/webworks.css" type="text/css" media="all" />
<link rel="StyleSheet" href="webworks.css" type="text/css" media="all" />
<script type="text/javascript" language="JavaScript1.2">
<!--
var WebWorksRootPath = "";
// -->
</script>
</head>
<body class="" style="">
<div style="text-align: left;">
<table cellspacing="0" summary="">
<tr>
<td>
<a href="crosstab.17.7.html"><img src="images/prev.gif" alt="Previous" border="0" /></a>
</td>
<td>
<a href="crosstab.17.9.html"><img src="images/next.gif" alt="Next" border="0" /></a>
</td>
</tr>
</table>
</div>
<hr align="left" />
<blockquote>
<div class="N_TutorialTask_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_TutorialTask_inner" style="white-space: nowrap;">Task 6: </div>
</td>
<td width="100%">
<div class="N_TutorialTask_inner"><a name="222142">Add grand totals</a></div>
</td>
</tr>
</table>
</div>
<p class="b_Body"><a name="222146">Each number that is displayed in the cross tab represents the sales total of a </a>particular product for a particular state. In this procedure, you add grand totals to display the total sales of all products for each state, the total sales of each product, and the total of all sales across products and states.</p>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">1 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="222149">Choose Layout to resume editing the cross tab.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">2 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="341408">Select the cross tab by clicking on the tab in the lower left corner of the </a>cross tab. Make sure you select the entire cross tab, not just a part of it. </div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">3 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="222153">In Property Editor, choose the Row Area tab.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">4 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="222154">Choose Grand Totals, then choose Add.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">5 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="341399">On Grand Total, shown in </a><a href="#341405" title="Add grand totals">Figure 17‑11</a>, use the default values, then choose OK.</div>
</td>
</tr>
</table>
</div>
<p class="i2_Image2"><a name="341403"><img class="Default" src="images/xtab_rowtotal.gif" width="686" height="334" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="Figure 17-14 Creating grand totals in the cross-tab row area" /></a></p>
<div class="fc2_FigCall2Title_outer" style="margin-left: 14.173199999999994pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="fc2_FigCall2Title_inner" style="width: 70.866pt; white-space: nowrap;">
<b class="Bold">Figure 17‑11 </b>
</div>
</td>
<td width="100%">
<div class="fc2_FigCall2Title_inner"><a name="341405">Creating grand totals in the cross-tab row area</a></div>
</td>
</tr>
</table>
</div>
<div class="N_i_Indent1"><a name="341384">A new row is added to the bottom of the cross tab, as shown in </a><a href="#341393" title="Add grand totals">Figure 17‑12</a>. In this row is a label that displays Grand Total and a data element that displays <img class="Default" src="images/crosstab.17.8.3.jpg" width="19" height="27" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="" />[EXTENDED_PRICE].</div>
<p class="i2_Image2"><a name="341391"><img class="Default" src="images/xtab_layout3.gif" width="686" height="274" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="Figure 17-15 Cross tab including a new row to display grand totals" /></a></p>
<div class="fc2_FigCall2Title_outer" style="margin-left: 14.173199999999994pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="fc2_FigCall2Title_inner" style="width: 70.866pt; white-space: nowrap;">
<b class="Bold">Figure 17‑12 </b>
</div>
</td>
<td width="100%">
<div class="fc2_FigCall2Title_inner"><a name="341393">Cross tab including a new row to display grand totals</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">6 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="222202">In Property Editor, choose the Column Area tab.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">7 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="222208">Choose Grand Totals, then choose Add.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">8 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="222212">On Grand Total, use the default values, then choose OK.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_i_Indent1"><a name="311709">A new column is added to the cross tab, as shown in </a><a href="#311715" title="Add grand totals">Figure 17‑13</a>. </div>
<p class="i2_Image2"><a name="311713"><img class="Default" src="images/xtab_layout4.gif" width="687" height="274" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="Figure 17-16 Cross tab with a new column to display grand totals" /></a></p>
<div class="fc2_FigCall2Title_outer" style="margin-left: 14.173199999999994pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="fc2_FigCall2Title_inner" style="width: 70.866pt; white-space: nowrap;">
<b class="Bold">Figure 17‑13 </b>
</div>
</td>
<td width="100%">
<div class="fc2_FigCall2Title_inner"><a name="311715">Cross tab with a new column to display grand totals</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">9 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="222242">Preview the report. Grand totals appear in the last row and last column of </a>the cross tab.</div>
</td>
</tr>
</table>
</div>
<h4 class="N_ht_HowTo"><a name="399281">How to create data sets for a multi-dataset cube</a></h4>
<p class="b1i_Bullet1-intro"><a name="399283">In this procedure, you create two data sets:</a></p>
<div class="b1_Bullet1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="b1_Bullet1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zBullet">n </span>
</div>
</td>
<td width="100%">
<div class="b1_Bullet1_inner"><a name="399284">A fact data set, SalesTotal, to retrieve the data for calculating the sales </a>totals</div>
</td>
</tr>
</table>
</div>
<div class="b1_Bullet1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="b1_Bullet1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zBullet">n </span>
</div>
</td>
<td width="100%">
<div class="b1_Bullet1_inner"><a name="399285">A dimension data set, Productlines, to retrieve data about the product </a>lines</div>
</td>
</tr>
</table>
</div>
<p class="b_Body"><a name="399286">Note that we are not creating a separate data set for the year dimension, as is </a>typical in a star schema. It is sometimes too complicated to create a pure star schema design when working with data stored in an OLTP system.</p>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">1 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="399289">Create a new data set named SalesTotal. Create the following query:</a></div>
</td>
</tr>
</table>
</div>
<div class="cfi_CodeFirstIndent"><a name="399290">select CLASSICMODELS.ORDERDETAILS.PRODUCTCODE,</a></div>
<div class="coi_CodeIndent"><a name="399291">CLASSICMODELS.ORDERS.SHIPPEDDATE,</a></div>
<div class="coi_CodeIndent"><a name="399292">CLASSICMODELS.ORDERDETAILS.QUANTITYORDERED * </a>CLASSICMODELS.ORDERDETAILS.PRICEEACH as "EXTENDED_PRICE"</div>
<div class="coi_CodeIndent"><a name="399293"> </a></div>
<div class="coi_CodeIndent"><a name="399294">from CLASSICMODELS.ORDERDETAILS, CLASSICMODELS.ORDERS</a></div>
<div class="coi_CodeIndent"><a name="399295">where CLASSICMODELS.ORDERS.ORDERNUMBER = </a>CLASSICMODELS.ORDERDETAILS.ORDERNUMBER</div>
<div class="coi_CodeIndent"><a name="399296">and CLASSICMODELS.ORDERS.STATUS = 'Shipped'</a></div>
<div class="b2_Bullet2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="b2_Bullet2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zBulletGray">n </span>
</div>
</td>
<td width="100%">
<div class="b2_Bullet2_inner"><a name="399297">The query retrieves PRODUCTCODE data because it is the key to later </a>link to the PRODUCTLINE dimension.</div>
</td>
</tr>
</table>
</div>
<div class="b2_Bullet2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="b2_Bullet2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zBulletGray">n </span>
</div>
</td>
<td width="100%">
<div class="b2_Bullet2_inner"><a name="399298">The query retrieves SHIPPEDDATE data to use for the year dimension.</a></div>
</td>
</tr>
</table>
</div>
<div class="b2_Bullet2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="b2_Bullet2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zBulletGray">n </span>
</div>
</td>
<td width="100%">
<div class="b2_Bullet2_inner"><a name="399299">The query creates a calculated column, EXTENDED_PRICE, whose </a>values will be aggregated to calculate the sales totals.</div>
</td>
</tr>
</table>
</div>
<div class="b2_Bullet2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="b2_Bullet2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zBulletGray">n </span>
</div>
</td>
<td width="100%">
<div class="b2_Bullet2_inner"><a name="399300">The query creates a join between the Orders and OrderDetails tables to </a>get all the necessary data about the orders. Because the data set is retrieving data from an OLTP database, joins are unavoidable.</div>
</td>
</tr>
</table>
</div>
<div class="b2_Bullet2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="b2_Bullet2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zBulletGray">n </span>
</div>
</td>
<td width="100%">
<div class="b2_Bullet2_inner"><a name="399301">The query contains a filter condition to retrieve order data for orders </a>that have been shipped, and therefore, that have been paid.</div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">2 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="399302">Create a new data set named Productlines. Create the following query:</a></div>
</td>
</tr>
</table>
</div>
<div class="cfi_CodeFirstIndent"><a name="399303">select CLASSICMODELS.PRODUCTS.PRODUCTLINE,</a></div>
<div class="coi_CodeIndent"><a name="399304">CLASSICMODELS.PRODUCTS.PRODUCTCODE</a></div>
<div class="coi_CodeIndent"><a name="399305">from CLASSICMODELS.PRODUCTS</a></div>
<div class="b2_Bullet2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="b2_Bullet2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zBulletGray">n </span>
</div>
</td>
<td width="100%">
<div class="b2_Bullet2_inner"><a name="399306">The query retrieves PRODUCTLINE data to use for the </a>PRODUCTLINE dimension.</div>
</td>
</tr>
</table>
</div>
<div class="b2_Bullet2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="b2_Bullet2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zBulletGray">n </span>
</div>
</td>
<td width="100%">
<div class="b2_Bullet2_inner"><a name="399307">The query retrieves PRODUCTCODE data because it is the key that the </a>SalesTotals data set will need to reference.</div>
</td>
</tr>
</table>
</div>
<h4 class="N_ht_HowTo"><a name="399308">How to create a multi-dataset cube</a></h4>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">1 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="399312">In Data Explorer, right-click Data Cubes, then choose New Data Cube.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">2 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="399315">On the Dataset page of Cross Tab Cube Builder, supply the following </a>information, as shown in <a href="#417177" title="Add grand totals">Figure 17‑14</a>:</div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">1 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="399320">In Name, specify a descriptive name, such as Sales Cube, for the cube.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">2 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="399321">In Primary dataset, select SalesTotal. In a multi-dataset cube, the fact </a>data set that retrieves the data to calculate measures is the primary data set.</div>
</td>
</tr>
</table>
</div>
<p class="i2_Image2"><a name="399330"><img class="Default" src="images/xtab_setds.gif" width="837" height="411" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="" /></a></p>
<div class="fc2_FigCall2Title_outer" style="margin-left: 14.173199999999994pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="fc2_FigCall2Title_inner" style="width: 70.866pt; white-space: nowrap;">
<b class="Bold">Figure 17‑14 </b>
</div>
</td>
<td width="100%">
<div class="fc2_FigCall2Title_inner"><a name="417177">Name and primary data set specified for a cube</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">3 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="399334">Choose Groups and Summaries to define the dimensions and measures </a>for the cube. The Groups and Summaries page, shown in <a href="#417112" title="Add grand totals">Figure 17‑15</a>, displays the available data sets and fields.</div>
</td>
</tr>
</table>
</div>
<p class="i2_Image2"><a name="417068"><img class="Default" src="images/xtab_grps&summaries.gif" width="837" height="411" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="" /></a></p>
<div class="fc2_FigCall2Title_outer" style="margin-left: 14.173199999999994pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="fc2_FigCall2Title_inner" style="width: 70.866pt; white-space: nowrap;">
<b class="Bold">Figure 17‑15 </b>
</div>
</td>
<td width="100%">
<div class="fc2_FigCall2Title_inner"><a name="417112">Groups and Summaries page shows the available data sets </a>and fields</div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">4 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="399349">Define the year dimension of the cube.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">1 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="399350">Under the Sales Totals (Primary) data set, drag SHIPPEDDATE and </a>drop it under Groups (Dimensions) in the drop location that displays (Drop a field here to create a group). </div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">2 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="399351">On Add Group, use the default group name.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_i2_Indent2"><a name="399353">Group Level displays the different ways to group the dates. To display </a>the dates as they appear in the data source, select Regular Group. To group the dates by any of the time periods, select Date Group.</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">3 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="399357">Select Date Group, then select year, as shown in </a><a href="#399363" title="Add grand totals">Figure 17‑16</a>. </div>
</td>
</tr>
</table>
</div>
<p class="i3_Image3"><a name="399361"><img class="Default" src="images/xtab_dategroup.gif" width="439" height="455" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="" /></a></p>
<div class="fc3_FigCall3Title_outer" style="margin-left: 28.346400000000002pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="fc3_FigCall3Title_inner" style="width: 70.866pt; white-space: nowrap;">
<b class="Bold">Figure 17‑16 </b>
</div>
</td>
<td width="100%">
<div class="fc3_FigCall3Title_inner"><a name="399363">Group Level showing the year group selected</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">4 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="399365">Choose OK to save the year dimension.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">5 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="399366">Define the product line dimension.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">1 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="399367">Under the Productlines data set, drag PRODUCTLINE and drop it </a>under Groups (Dimensions) in the drop location that displays (Drop a field here to create a group). On Add Group, use the default group name.</div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">2 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="399368">Under the Productlines data set, drag PRODUCTCODE and drop it on </a>the PRODUCTLINE dimension. This action creates a hierarchical relationship between PRODUCTLINE and PRODUCTCODE.</div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">6 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="399369">Define the cube’s measure. Under the Sales Totals (Primary) data set, drag </a>EXTENDED_PRICE and drop it under Summary Fields (Measures) in the drop location that displays (Drop a field here to create a summary field).</div>
</td>
</tr>
</table>
</div>
<div class="N_i_Indent1"><a name="399373">The Groups and Summaries page, shown in </a><a href="#417282" title="Add grand totals">Figure 17‑17</a>, displays the dimensions and measure that you define.</div>
<p class="i2_Image2"><a name="417263"><img class="Default" src="images/xtab_dimensions&measures.gif" width="835" height="430" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="" /></a></p>
<div class="fc2_FigCall2Title_outer" style="margin-left: 14.173199999999994pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="fc2_FigCall2Title_inner" style="width: 70.866pt; white-space: nowrap;">
<b class="Bold">Figure 17‑17 </b>
</div>
</td>
<td width="100%">
<div class="fc2_FigCall2Title_inner"><a name="417282">Groups and Summaries page shows the dimensions and </a>measure</div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">7 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="399384">Link the data in the dimensions with the fact data set.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">1 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="399385">Choose Link Groups. The Link Groups page displays the Productline </a>dimension you created and the primary (fact) data set.</div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">2 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="399389">Link the PRODUCTCODE field in both items, as shown in </a><a href="#417328" title="Add grand totals">Figure 17‑18</a>.</div>
</td>
</tr>
</table>
</div>
<p class="i3_Image3"><a name="417301"><img class="Default" src="images/xtab_linkgroups.gif" width="835" height="381" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="" /></a></p>
<div class="fc3_FigCall3Title_outer" style="margin-left: 28.346400000000002pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="fc3_FigCall3Title_inner" style="width: 70.866pt; white-space: nowrap;">
<b class="Bold">Figure 17‑18 </b>
</div>
</td>
<td width="100%">
<div class="fc3_FigCall3Title_inner"><a name="417328">Link Groups page shows how the dimension and fact </a>data sets are linked</div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">8 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="399400">Choose OK to save the cube. You can now build a cross tab that uses data </a>from this cube.</div>
</td>
</tr>
</table>
</div>
<p class="b_Body"><a href="#399410" title="Add grand totals" name="399404">Figure 17‑19</a> shows a cross tab that uses the year and PRODUCTLINE dimensions and the EXTENDED_PRICE measure from the cube.</p>
<p class="i1_Image1"><a name="399408"><img class="Default" src="images/xtab_salesxproductxyear_design.gif" width="719" height="289" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="" /></a></p>
<div class="fc_FigCalloutTitle_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="fc_FigCalloutTitle_inner" style="width: 70.866pt; white-space: nowrap;">
<b class="Bold">Figure 17‑19 </b>
</div>
</td>
<td width="100%">
<div class="fc_FigCalloutTitle_inner"><a name="399410">Cross tab design</a></div>
</td>
</tr>
</table>
</div>
<p class="b_Body"><a href="#399423" title="Add grand totals" name="399417">Figure 17‑20</a> shows the generated cross tab.</p>
<p class="i1_Image1"><a name="399421"><img class="Default" src="images/xtab_salesxproductxyear_output.gif" width="719" height="318" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="" /></a></p>
<div class="fc_FigCalloutTitle_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="fc_FigCalloutTitle_inner" style="width: 70.866pt; white-space: nowrap;">
<b class="Bold">Figure 17‑20 </b>
</div>
</td>
<td width="100%">
<div class="fc_FigCalloutTitle_inner"><a name="399423">Cross tab output</a></div>
</td>
</tr>
</table>
</div>
</blockquote>
<hr align="left" />
<table align="right" summary="">
<tr>
<td class="WebWorks_Company_Name_Bottom">
<a href="notices.html">(c) Copyright Actuate Corporation 2009</a>
</td>
</tr>
</table>
</body>
</html> | 00wendi00/MyProject | W_myeclipse/plugins/org.eclipse.birt.doc_2.5.2.me201003052220/birt/crosstab.17.8.html | HTML | apache-2.0 | 39,347 | [
30522,
1026,
1029,
20950,
2544,
1027,
1000,
1015,
1012,
1014,
1000,
17181,
1027,
1000,
21183,
2546,
1011,
1022,
1000,
1029,
1028,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
1060,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* 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.ode.bpel.dao;
import javax.sql.DataSource;
/**
* Extension of the {@link BpelDAOConnectionFactory} interface for DAOs that
* are based on J2EE/JDBC data sources.
*
* @author Maciej Szefler - m s z e f l e r @ g m a i l . c o m
*/
public interface BpelDAOConnectionFactoryJDBC extends BpelDAOConnectionFactory {
/**
* Set the managed data source (transactions tied to transaction manager).
* @param ds
*/
public void setDataSource(DataSource ds);
/**
* Set the unmanaged data source.
* @param ds
*/
public void setUnmanagedDataSource(DataSource ds);
/**
* Set the transaction manager.
* @param tm
*/
public void setTransactionManager(Object tm);
}
| mproch/apache-ode | bpel-dao/src/main/java/org/apache/ode/bpel/dao/BpelDAOConnectionFactoryJDBC.java | Java | apache-2.0 | 1,565 | [
30522,
1013,
1008,
1008,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
1008,
2030,
2062,
12130,
6105,
10540,
1012,
2156,
1996,
5060,
5371,
1008,
5500,
2007,
2023,
2147,
2005,
3176,
2592,
1008,
4953,
9385,
6095,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*Common*/
.hide { display: none;}
.fixed {
height: 100%;
overflow: hidden;
}
.theme-options-page h2 span {
padding-left: 20px;
font-size: 12px;
text-transform: uppercase;
color: #999999; }
.theme-options-page { margin-bottom: 20px; }
.theme-options-page textarea { width: 98%;}
.theme-options-page .description {
color: #999999;
}
.theme-options-page .description span {
background: #E5E5E5;
color: #222222;
}
.theme-options-page .unit,
.theme-options-page .checkbox-description {
padding-left: 5px;
}
.theme-options-page input,
.theme-options-page textarea,
.theme-options-page select {
font-family: Arial,Helvetica,sans-serif,'Lucida Grande';
}
.theme-options-page select {
width: 300px;
}
.theme-options-page .colorSelector {
float: left;
width: 36px;
margin-right: 10px;
}
.theme-options-page input.color-text {
text-transform: uppercase;
margin-top: 8px;
margin-right: 10px;
}
.theme-box {
background: #F5F5F5;
border: 1px solid #DFDFDF;
padding: 10px 15px;
}
.theme-options-table {
margin: 10px 0 20px;
}
.theme-options-table th {
padding-left: 0;
padding-right: 30px;
width: 190px;
}
.theme-options-subtitle h3 {
font-size: 16px;
font-weight: 100;
padding-bottom: 5px;
margin-bottom: 0;
border-bottom: 1px solid #DFDFDF;
color: #2680AA;
} | lfhsuhfliur/orial | wp-content/themes/mu-types/wraps/assets/css/theme-options.css | CSS | gpl-2.0 | 1,397 | [
30522,
1013,
1008,
2691,
1008,
1013,
1012,
5342,
1063,
4653,
1024,
3904,
1025,
1065,
1012,
4964,
1063,
4578,
1024,
2531,
1003,
1025,
2058,
12314,
1024,
5023,
1025,
1065,
1012,
4323,
1011,
7047,
1011,
3931,
1044,
2475,
8487,
1063,
11687,
4... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
namespace spec\PhpSpec\Wrapper\Subject\Expectation;
use PhpSpec\Matcher\MatcherInterface;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class PositiveSpec extends ObjectBehavior
{
function let(MatcherInterface $matcher)
{
$this->beConstructedWith($matcher);
}
function it_calls_a_positive_match_on_matcher(MatcherInterface $matcher)
{
$alias = 'somealias';
$subject = 'subject';
$arguments = array();
$matcher->positiveMatch($alias, $subject, $arguments)->shouldBeCalled();
$this->match($alias, $subject, $arguments);
}
}
| ruitiagocosta/veinteractive | www/veinteractive/vendor/phpspec/phpspec/spec/PhpSpec/Wrapper/Subject/Expectation/PositiveSpec.php | PHP | mit | 610 | [
30522,
1026,
1029,
25718,
3415,
15327,
28699,
1032,
25718,
13102,
8586,
1032,
10236,
4842,
1032,
3395,
1032,
17626,
1025,
2224,
25718,
13102,
8586,
1032,
2674,
2121,
1032,
2674,
23282,
3334,
12172,
1025,
2224,
25718,
13102,
30524,
1032,
6685,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<div class="homepage-main" role="main">
<?php echo torch_get_default_slider();?>
<?php
global $torch_home_sections;
if($torch_home_sections !=""){
$home_sections_array = json_decode($torch_home_sections, true);
if(isset($home_sections_array['section-widget-area-name']) && is_array($home_sections_array['section-widget-area-name']) ){
$num = count($home_sections_array['section-widget-area-name']);
for($i=0; $i<$num; $i++ ){
$areaname = isset($home_sections_array['section-widget-area-name'][$i])?$home_sections_array['section-widget-area-name'][$i]:"";
$sanitize_areaname = sanitize_title($areaname);
$color = isset($home_sections_array['list-item-color'][$i])?$home_sections_array['list-item-color'][$i]:"";
$image = isset($home_sections_array['list-item-image'][$i])?$home_sections_array['list-item-image'][$i]:"";
$repeat = isset($home_sections_array['list-item-repeat'][$i])?$home_sections_array['list-item-repeat'][$i]:"";
$position = isset($home_sections_array['list-item-position'][$i])?$home_sections_array['list-item-position'][$i]:"";
$attachment = isset($home_sections_array['list-item-attachment'][$i])?$home_sections_array['list-item-attachment'][$i]:"";
$layout = isset($home_sections_array['widget-area-layout'][$i])?$home_sections_array['widget-area-layout'][$i]:"";
$padding = isset($home_sections_array['widget-area-padding'][$i])?$home_sections_array['widget-area-padding'][$i]:"";
$column = isset($home_sections_array['widget-area-column'][$i])?$home_sections_array['widget-area-column'][$i]:"";
$columns = isset($home_sections_array['widget-area-column-item'][$sanitize_areaname ])?$home_sections_array['widget-area-column-item'][$sanitize_areaname ]:"";
$background_style = "";
if ($image!="") {
$background_style .= "background-image:url('".$image. "');background-repeat:".$repeat.";background-position:".$position.";background-attachment:".$attachment.";";
}
if( $color !=""){
$background_style .= "background-color:".$color.";";
}
if(is_numeric($padding))
{
$background_style .= "padding-top:".$padding."px;padding-bottom:".$padding."px;";
}
if($layout == "full"){
$container = 'full-width';
}else{
$container = 'container';
}
$column_num = count($columns);
$j = 1;
echo '<section class="home-section '.$sanitize_areaname.'" style="'.$background_style.'"><div class="'.$container.'">';
if(is_array($columns)){
echo '<div class="row">';
foreach($columns as $columnItem){
if($column_num > 1){
$widget_name = $areaname." Column ".$j;
}else{
$widget_name = $areaname;
}
echo '<div class="col-md-'.$columnItem.'">';
dynamic_sidebar(sanitize_title($widget_name));
echo '</div>';
$j++;
}
echo '</div>';
}else{
echo '<div class="col-md-full">';
dynamic_sidebar($sanitize_areaname);
echo '</div>';
}
echo '<div class="clear"></div></div></section>';
}
}
}
?>
</div> | aminkhoshzahmat/articlex | wp-content/themes/torch/featured-content.php | PHP | gpl-2.0 | 3,265 | [
30522,
1026,
4487,
2615,
2465,
1027,
1000,
2188,
13704,
1011,
2364,
30524,
1035,
5433,
999,
1027,
1000,
1000,
1007,
1063,
1002,
2188,
1035,
5433,
1035,
9140,
1027,
1046,
3385,
1035,
21933,
3207,
1006,
1002,
12723,
1035,
2188,
1035,
5433,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* Copyright (c) 2013 itemis AG and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mark Broerkens - initial API and implementation
*
*/
package org.eclipse.rmf.reqif10.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.rmf.reqif10.AttributeDefinitionDate;
import org.eclipse.rmf.reqif10.AttributeValueDate;
import org.eclipse.rmf.reqif10.DatatypeDefinitionDate;
import org.eclipse.rmf.reqif10.ReqIF10Package;
/**
* <!-- begin-user-doc --> An implementation of the model object '<em><b>Attribute Definition Date</b></em>'. <!--
* end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.eclipse.rmf.reqif10.impl.AttributeDefinitionDateImpl#getType <em>Type</em>}</li>
* <li>{@link org.eclipse.rmf.reqif10.impl.AttributeDefinitionDateImpl#getDefaultValue <em>Default Value</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class AttributeDefinitionDateImpl extends AttributeDefinitionSimpleImpl implements AttributeDefinitionDate {
/**
* The cached value of the '{@link #getType() <em>Type</em>}' reference. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @see #getType()
* @generated
* @ordered
*/
protected DatatypeDefinitionDate type;
/**
* This is true if the Type reference has been set. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
* @ordered
*/
protected boolean typeESet;
/**
* The cached value of the '{@link #getDefaultValue() <em>Default Value</em>}' containment reference. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @see #getDefaultValue()
* @generated
* @ordered
*/
protected AttributeValueDate defaultValue;
/**
* This is true if the Default Value containment reference has been set. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
* @ordered
*/
protected boolean defaultValueESet;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected AttributeDefinitionDateImpl() {
super();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
protected EClass eStaticClass() {
return ReqIF10Package.Literals.ATTRIBUTE_DEFINITION_DATE;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public DatatypeDefinitionDate getType() {
if (type != null && type.eIsProxy()) {
InternalEObject oldType = (InternalEObject) type;
type = (DatatypeDefinitionDate) eResolveProxy(oldType);
if (type != oldType) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE, oldType, type));
}
}
return type;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public DatatypeDefinitionDate basicGetType() {
return type;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setType(DatatypeDefinitionDate newType) {
DatatypeDefinitionDate oldType = type;
type = newType;
boolean oldTypeESet = typeESet;
typeESet = true;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE, oldType, type, !oldTypeESet));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void unsetType() {
DatatypeDefinitionDate oldType = type;
boolean oldTypeESet = typeESet;
type = null;
typeESet = false;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.UNSET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE, oldType, null, oldTypeESet));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public boolean isSetType() {
return typeESet;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public AttributeValueDate getDefaultValue() {
return defaultValue;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public NotificationChain basicSetDefaultValue(AttributeValueDate newDefaultValue, NotificationChain msgs) {
AttributeValueDate oldDefaultValue = defaultValue;
defaultValue = newDefaultValue;
boolean oldDefaultValueESet = defaultValueESet;
defaultValueESet = true;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE,
oldDefaultValue, newDefaultValue, !oldDefaultValueESet);
if (msgs == null)
msgs = notification;
else
msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setDefaultValue(AttributeValueDate newDefaultValue) {
if (newDefaultValue != defaultValue) {
NotificationChain msgs = null;
if (defaultValue != null)
msgs = ((InternalEObject) defaultValue).eInverseRemove(this, EOPPOSITE_FEATURE_BASE
- ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, null, msgs);
if (newDefaultValue != null)
msgs = ((InternalEObject) newDefaultValue).eInverseAdd(this, EOPPOSITE_FEATURE_BASE
- ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, null, msgs);
msgs = basicSetDefaultValue(newDefaultValue, msgs);
if (msgs != null)
msgs.dispatch();
} else {
boolean oldDefaultValueESet = defaultValueESet;
defaultValueESet = true;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, newDefaultValue,
newDefaultValue, !oldDefaultValueESet));
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public NotificationChain basicUnsetDefaultValue(NotificationChain msgs) {
AttributeValueDate oldDefaultValue = defaultValue;
defaultValue = null;
boolean oldDefaultValueESet = defaultValueESet;
defaultValueESet = false;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.UNSET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE,
oldDefaultValue, null, oldDefaultValueESet);
if (msgs == null)
msgs = notification;
else
msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void unsetDefaultValue() {
if (defaultValue != null) {
NotificationChain msgs = null;
msgs = ((InternalEObject) defaultValue).eInverseRemove(this, EOPPOSITE_FEATURE_BASE
- ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, null, msgs);
msgs = basicUnsetDefaultValue(msgs);
if (msgs != null)
msgs.dispatch();
} else {
boolean oldDefaultValueESet = defaultValueESet;
defaultValueESet = false;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.UNSET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, null, null,
oldDefaultValueESet));
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public boolean isSetDefaultValue() {
return defaultValueESet;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE:
return basicUnsetDefaultValue(msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE:
if (resolve)
return getType();
return basicGetType();
case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE:
return getDefaultValue();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE:
setType((DatatypeDefinitionDate) newValue);
return;
case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE:
setDefaultValue((AttributeValueDate) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE:
unsetType();
return;
case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE:
unsetDefaultValue();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE:
return isSetType();
case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE:
return isSetDefaultValue();
}
return super.eIsSet(featureID);
}
} // AttributeDefinitionDateImpl
| ModelWriter/Demonstrations | org.eclipse.rmf.reqif10/src/org/eclipse/rmf/reqif10/impl/AttributeDefinitionDateImpl.java | Java | epl-1.0 | 9,651 | [
30522,
1013,
1008,
1008,
1008,
9385,
1006,
1039,
1007,
2286,
8875,
2483,
12943,
1998,
2500,
1012,
1008,
2035,
2916,
9235,
1012,
2023,
2565,
1998,
1996,
10860,
4475,
1008,
2024,
2081,
2800,
2104,
1996,
3408,
1997,
1996,
13232,
2270,
6105,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过下列特性集
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Web")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Web")]
[assembly: AssemblyCopyright("版权所有(C) Microsoft 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的某个类型,
// 请针对该类型将 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("c041effd-97b4-4bad-8d51-badbb5d742c5")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“修订号”和“内部版本号”的默认值,
// 方法是按如下所示使用“*”:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| lsyuan/yzxzgl | Web/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,326 | [
30522,
2478,
2291,
1012,
9185,
1025,
2478,
2291,
1012,
2448,
7292,
1012,
21624,
8043,
7903,
2229,
1025,
2478,
2291,
1012,
2448,
7292,
1012,
6970,
11923,
2121,
7903,
2229,
1025,
1013,
1013,
1873,
100,
100,
100,
100,
1916,
100,
100,
1767,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
const S$ = require('S$');
function loadSrc(obj, src) {
throw src;
}
const cookies = S$.symbol('Cookie', '');
const world = {};
if (cookies) {
if (/iPhone/.exec(cookies)) {
loadSrc(world, '/resources/' + cookies);
}
loadSrc(world, '/resources/unknown');
} else {
loadSrc(world, '/resources/fresh');
}
| ExpoSEJS/ExpoSE | tests/regex/cookies/t1.js | JavaScript | mit | 332 | [
30522,
9530,
3367,
1055,
1002,
1027,
5478,
1006,
1005,
1055,
1002,
1005,
1007,
1025,
3853,
15665,
11890,
1006,
27885,
3501,
1010,
5034,
2278,
1007,
1063,
5466,
5034,
2278,
1025,
1065,
9530,
3367,
16324,
1027,
1055,
1002,
1012,
6454,
1006,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {global} from '../../src/util/global';
// Not yet available in TypeScript: https://github.com/Microsoft/TypeScript/pull/29332
declare var globalThis: any /** TODO #9100 */;
{
describe('global', () => {
it('should be global this value', () => {
const _global = new Function('return this')();
expect(global).toBe(_global);
});
if (typeof globalThis !== 'undefined') {
it('should use globalThis as global reference', () => {
expect(global).toBe(globalThis);
});
}
});
}
| wKoza/angular | packages/core/test/util/global_spec.ts | TypeScript | mit | 732 | [
30522,
1013,
1008,
1008,
1008,
1030,
6105,
1008,
9385,
8224,
11775,
2035,
2916,
9235,
1012,
1008,
1008,
2224,
1997,
2023,
3120,
3642,
2003,
9950,
2011,
2019,
10210,
1011,
2806,
6105,
2008,
2064,
2022,
1008,
2179,
1999,
1996,
6105,
5371,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>almost-full: 54 s 🏆</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.10.2 / almost-full - 8.12.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
almost-full
<small>
8.12.0
<span class="label label-success">54 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-01-09 17:44:16 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-09 17:44:16 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.10.2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "palmskog@gmail.com"
homepage: "https://github.com/coq-community/almost-full"
dev-repo: "git+https://github.com/coq-community/almost-full.git"
bug-reports: "https://github.com/coq-community/almost-full/issues"
license: "MIT"
synopsis: "Almost-full relations in Coq for proving termination"
description: """
Coq development of almost-full relations, including the Ramsey
Theorem, useful for proving termination."""
build: [make "-j%{jobs}%"]
install: [make "install"]
depends: [
"coq" {>= "8.10" & < "8.13~"}
]
tags: [
"category:Computer Science/Data Types and Data Structures"
"keyword:Ramsey theorem"
"keyword:termination"
"logpath:AlmostFull"
"date:2020-07-26"
]
authors: [
"Dimitrios Vytiniotis"
"Thierry Coquand"
"David Wahlstedt"
]
url {
src: "https://github.com/coq-community/almost-full/archive/v8.12.0.tar.gz"
checksum: "sha512=17785dafabd90361183d1f6f88a71864bdd019b878e2e83921c4619d348119b35de958d45331d1510548ef103844dc88678ee7cb706182cffb6dbe6c0174a441"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-almost-full.8.12.0 coq.8.10.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-almost-full.8.12.0 coq.8.10.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>12 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-almost-full.8.12.0 coq.8.10.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>54 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 3 M</p>
<ul>
<li>630 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AFExamples.vo</code></li>
<li>630 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AFExamples.vo</code></li>
<li>403 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AlmostFullInduction.vo</code></li>
<li>402 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AlmostFullInduction.vo</code></li>
<li>138 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AFConstructions.vo</code></li>
<li>121 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AFConstructions.vo</code></li>
<li>78 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AlmostFullGeneralized.vo</code></li>
<li>71 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AFExamples.glob</code></li>
<li>71 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AlmostFull.vo</code></li>
<li>69 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AlmostFullInduction.glob</code></li>
<li>69 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AFExamples.glob</code></li>
<li>67 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AlmostFullInduction.glob</code></li>
<li>65 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AFConstructions.glob</code></li>
<li>48 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AlmostFull.vo</code></li>
<li>48 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AFConstructions.glob</code></li>
<li>42 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/Terminator.vo</code></li>
<li>42 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/Terminator.vo</code></li>
<li>42 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AlmostFullGeneralized.glob</code></li>
<li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AlmostFull.glob</code></li>
<li>19 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AlmostFull.glob</code></li>
<li>19 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AFConstructions.v</code></li>
<li>16 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AlmostFullInduction.v</code></li>
<li>16 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AlmostFullInduction.v</code></li>
<li>15 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AFExamples.v</code></li>
<li>15 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AFExamples.v</code></li>
<li>13 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AFConstructions.v</code></li>
<li>10 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/AlmostFull.v</code></li>
<li>9 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AlmostFullGeneralized.v</code></li>
<li>6 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/Terminator.glob</code></li>
<li>6 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/Terminator.glob</code></li>
<li>6 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/AlmostFull.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/Default/Terminator.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/AlmostFull/PropBounded/Terminator.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-almost-full.8.12.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.05.0-2.0.1/released/8.10.2/almost-full/8.12.0.html | HTML | mit | 11,079 | [
30522,
1026,
999,
9986,
13874,
30524,
1026,
2516,
1028,
2471,
1011,
2440,
1024,
5139,
1055,
100,
1026,
1013,
2516,
1028,
1026,
4957,
2128,
2140,
1027,
1000,
2460,
12690,
12696,
1000,
2828,
1027,
1000,
3746,
1013,
1052,
3070,
1000,
17850,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(231,233,237)'
};
ES.WidgetLive = ES.Widget.extend({
init: function() {
var me = this,
idInstance = ES.getActiveInstanceId();
me._super('widget-livedata');
var $component = $('#'+ me.cssId);
$component.find('.widget-body').append('<canvas id="testChart"></canvas>');
var config = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
backgroundColor: window.chartColors.red,
borderColor: window.chartColors.red,
data: [
10,
2,
5,
7,
2,
1,
8
],
fill: false
}, {
label: "My Second dataset",
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [
10,
6,
6,
7,
2,
7,
8
]
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
title:{
display:true,
text:'Chart.js Line Chart'
},
tooltips: {
mode: 'index',
intersect: false
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
};
window.myLine = new Chart($("#testChart"), config);
//ES.ajax({
// url: BASE_URL + "api/instances/"+ idInstance +"/data",
// success: function(data) {
// debugger;
// }
//});
}
// var me = this;
// me._super('widget-live');
//
// setInterval(function() {
// me.requestChartData()
// }, 120000);
//
// this.temperatureChart = new Highcharts.Chart({
// chart: {
// renderTo: 'temperatureChart',
// marginTop: 50,
// height: 320,
// defaultSeriesType: 'spline'
// }, credits: {
// enabled: false
// },
// title: {
// text: ''
// },
// exporting: {
// enabled: false
// },
// legend: {
// verticalAlign: 'top'
// },
// scrollbar: {
// enabled: roomTemperatureData.length > 10
// },
// xAxis: {
// type: 'datetime',
// min: roomTemperatureData.length > 10 ? roomTemperatureData[roomTemperatureData.length - 11].x : null,
// max: roomTemperatureData.length > 10 ? roomTemperatureData[roomTemperatureData.length -1].x : null
// },
// yAxis: {
// minPadding: 0.2,
// maxPadding: 0.2,
// minRange: 0.5,
// title: {
// text: I18n.valueInCelsius,
// margin: 25
// },
// plotBands: [{ // Cold
// from: 0,
// to: 18,
// color: 'rgba(68, 170, 213, 0.1)',
// label: {
// text: I18n.cold,
// style: {
// color: '#606060'
// }
// }
// }, { // Hot
// from: 35,
// to: 60,
// color: 'rgba(191, 11, 35, 0.1)',
// label: {
// text: I18n.hot,
// style: {
// color: '#606060'
// }
// }
// }]
// },
// series: [{
// name: I18n.roomTemperature + ' (°C)',
// color: '#BF0B23',
// dashStyle: 'ShortDash',
// data: roomTemperatureData
// },{
// name: I18n.tankTemperature + '(°C)',
// color: '#0066FF',
// dashStyle: 'ShortDash',
// data: tankTemperatureData
// }]
// });
//
// this.humidityChart = new Highcharts.Chart({
// chart: {
// renderTo: 'humidityChart',
// marginTop: 50,
// height: 320,
// defaultSeriesType: 'spline'
// },
// credits: {
// enabled: false
// },
// title: {
// text: ''
// },
// exporting: {
// enabled: false
// },
// legend: {
// verticalAlign: 'top'
// },
// scrollbar: {
// enabled: humidityData.length > 10
// },
// xAxis: {
// type: 'datetime',
// min: humidityData.length > 10 ? humidityData[humidityData.length - 11].x : null,
// max: humidityData.length > 10 ? humidityData[humidityData.length -1].x : null
// },
// yAxis: {
// minPadding: 0.5,
// maxPadding: 0.5,
// minRange: 5,
// max: 100,
// min: 0,
// title: {
// text: I18n.valueInPercent,
// margin: 25
// },
// plotBands: [{ // Low
// from: 0,
// to: 20,
// color: 'rgba(191, 11, 35, 0.1)',
// label: {
// text: I18n.low,
// style: {
// color: '#606060'
// }
// }
// }, { // High
// from: 50,
// to: 100,
// color: 'rgba(68, 170, 213, 0.1)',
// label: {
// text: I18n.high,
// style: {
// color: '#606060'
// }
// }
// }]
// },
// series: [{
// name: I18n.humidityPercent,
// color: '#44aad5',
// dashStyle: 'ShortDash',
// data: humidityData
// }]
// });
//},
//requestChartData: function() {
// var me = this;
// $.ajax({
// url: BASE_URL + 'ajax/chartLiveData/' + ES.getActiveInstanceId(),
// cache: false,
// dataType: "json",
// success: function(point) {
// /*if(point.roomTemperature.length > 0 &&
// temperatureChart.series[0].data.length > 0 &&
// temperatureChart.series[0].data[temperatureChart.series[0].data.length-1].x != point.roomTemperature[0]) {
// var series = temperatureChart.series[0],
// shift = series.data.length > 40;
//
// temperatureChart.series[0].addPoint(eval(point.roomTemperature), true, shift);
// }*/
//
// me.addChartData(point.roomTemperature, me.temperatureChart.series[0]);
//
// /*if(point.tankTemperature.length > 0 &&
// temperatureChart.series[1].data.length > 0 &&
// temperatureChart.series[1].data[temperatureChart.series[1].data.length-1].x != point.tankTemperature[0]) {
// var series = temperatureChart.series[1],
// shift = series.data.length > 40;
//
// temperatureChart.series[1].addPoint(eval(point.tankTemperature), true, shift);
// }*/
//
// me.addChartData(point.tankTemperature, me.temperatureChart.series[1]);
// }
// });
//},
//addChartData: function(data, chartSerie) {
// if(data.length > 0 &&
// chartSerie.data.length > 0 &&
// chartSerie.data[chartSerie.data.length-1].x != data[0]) {
// var shift = chartSerie.data.length > 80;
//
// chartSerie.addPoint(eval(data), true, shift);
// }
//}
}); | eoto88/EcoSystems | assets/js/widgets/live.js | JavaScript | gpl-2.0 | 9,559 | [
30522,
3332,
1012,
3673,
18717,
2015,
1027,
1063,
2417,
1024,
1005,
1054,
18259,
1006,
20637,
1010,
5585,
1010,
14078,
1007,
1005,
1010,
4589,
1024,
1005,
1054,
18259,
1006,
20637,
1010,
18914,
1010,
4185,
1007,
1005,
1010,
3756,
1024,
1005... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace Clash82\EzPlatformStudioTipsBlockBundle\Installer;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use eZ\Publish\API\Repository\ContentTypeService;
use eZ\Publish\API\Repository\Exceptions\ForbiddenException;
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
use eZ\Publish\API\Repository\Exceptions\UnauthorizedException;
use eZ\Publish\API\Repository\Repository;
use eZ\Publish\API\Repository\UserService;
class ContentTypeInstaller extends Command
{
/** @var int */
const ADMIN_USER_ID = 14;
/** @var \eZ\Publish\API\Repository\Repository */
private $repository;
/** @var \eZ\Publish\API\Repository\UserService */
private $userService;
/** @var \eZ\Publish\API\Repository\ContentTypeService */
private $contentTypeService;
/**
* @param \eZ\Publish\API\Repository\Repository $repository
* @param \eZ\Publish\API\Repository\UserService $userService
* @param \eZ\Publish\API\Repository\ContentTypeService $contentTypeService
*/
public function __construct(
Repository $repository,
UserService $userService,
ContentTypeService $contentTypeService
) {
$this->repository = $repository;
$this->userService = $userService;
$this->contentTypeService = $contentTypeService;
parent::__construct();
}
protected function configure()
{
$this->setName('ezstudio:tips-block:install')
->setHelp('Creates a new `Tip` ContentType.')
->addOption(
'name',
null,
InputOption::VALUE_OPTIONAL,
'replaces default ContentType <info>name</info>',
'Tip'
)
->addOption(
'identifier',
null,
InputOption::VALUE_OPTIONAL,
'replaces default ContentType <info>identifier</info>',
'tip'
)
->addOption(
'group_identifier',
null,
InputOption::VALUE_OPTIONAL,
'replaces default ContentType <info>group_identifier</info>',
'Content'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$groupIdentifier = $input->getOption('group_identifier');
$identifier = $input->getOption('identifier');
$name = $input->getOption('name');
try {
$contentTypeGroup = $this->contentTypeService->loadContentTypeGroupByIdentifier($groupIdentifier);
} catch (NotFoundException $e) {
$output->writeln(sprintf('ContentType group with identifier %s not found', $groupIdentifier));
return;
}
// create basic ContentType structure
$contentTypeCreateStruct = $this->contentTypeService->newContentTypeCreateStruct($identifier);
$contentTypeCreateStruct->mainLanguageCode = 'eng-GB';
$contentTypeCreateStruct->nameSchema = '<title>';
$contentTypeCreateStruct->names = [
'eng-GB' => $identifier,
];
$contentTypeCreateStruct->descriptions = [
'eng-GB' => 'Tip of the day',
];
// add Title field
$titleFieldCreateStruct = $this->contentTypeService->newFieldDefinitionCreateStruct('title', 'ezstring');
$titleFieldCreateStruct->names = [
'eng-GB' => 'Title',
];
$titleFieldCreateStruct->descriptions = [
'eng-GB' => 'Title',
];
$titleFieldCreateStruct->fieldGroup = 'content';
$titleFieldCreateStruct->position = 1;
$titleFieldCreateStruct->isTranslatable = true;
$titleFieldCreateStruct->isRequired = true;
$titleFieldCreateStruct->isSearchable = true;
$contentTypeCreateStruct->addFieldDefinition($titleFieldCreateStruct);
// add Description field
$bodyFieldCreateStruct = $this->contentTypeService->newFieldDefinitionCreateStruct('body', 'ezrichtext');
$bodyFieldCreateStruct->names = [
'eng-GB' => 'Body',
];
$bodyFieldCreateStruct->descriptions = [
'eng-GB' => 'Body',
];
$bodyFieldCreateStruct->fieldGroup = 'content';
$bodyFieldCreateStruct->position = 2;
$bodyFieldCreateStruct->isTranslatable = true;
$bodyFieldCreateStruct->isRequired = true;
$bodyFieldCreateStruct->isSearchable = true;
$contentTypeCreateStruct->addFieldDefinition($bodyFieldCreateStruct);
try {
$contentTypeDraft = $this->contentTypeService->createContentType($contentTypeCreateStruct, [
$contentTypeGroup,
]);
$this->contentTypeService->publishContentTypeDraft($contentTypeDraft);
$output->writeln(sprintf(
'<info>%s ContentType created with ID %d</info>',
$name, $contentTypeDraft->id
));
} catch (UnauthorizedException $e) {
$output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
return;
} catch (ForbiddenException $e) {
$output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
return;
}
$output->writeln(sprintf(
'Place all your <info>%s</info> content objects into desired folder and then select it as a Parent container in eZ Studio Tips Block options form.',
$name
));
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->repository->setCurrentUser(
$this->userService->loadUser(self::ADMIN_USER_ID)
);
}
}
| omniproject/ezstudio-tips-block | bundle/Installer/ContentTypeInstaller.php | PHP | mit | 5,989 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
1030,
6105,
2005,
2440,
9385,
1998,
6105,
2592,
3193,
6105,
5371,
5500,
2007,
2023,
3120,
3642,
1012,
1008,
1013,
3415,
15327,
13249,
2620,
2475,
1032,
1041,
2480,
24759,
4017,
22694,
8525,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Birdgame.Main;
namespace Birdgame.Main
{
public class BirdEvolutionAnimation : MonoBehaviour
{
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void EndEvolution()
{
gameObject.SetActive(false);
}
}
}
| SeongBongJang/amuzlabBonRepo | NGUI_Test/NGUI_Sample/Assets/Scripts/Main/BirdEvolutionAnimation.cs | C# | mit | 464 | [
30522,
2478,
2291,
1012,
6407,
1025,
2478,
2291,
1012,
6407,
1012,
12391,
1025,
2478,
8499,
13159,
3170,
1025,
2478,
4743,
16650,
1012,
2364,
1025,
3415,
15327,
4743,
16650,
1012,
2364,
1063,
2270,
2465,
4743,
6777,
4747,
13700,
7088,
28649... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//
// SettingVCPopAnimator.h
// BlackNoise
//
// Created by 李金 on 2016/11/24.
// Copyright © 2016年 kingandyoga. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SettingVCPopAnimator : NSObject<UIViewControllerAnimatedTransitioning>
@end
| kingandyoga/BlackNoise | BlackNoise/BlackNoise/SettingVCPopAnimator.h | C | mit | 271 | [
30522,
1013,
1013,
1013,
1013,
4292,
25465,
16340,
7088,
18900,
2953,
1012,
1044,
1013,
1013,
2304,
3630,
5562,
1013,
1013,
1013,
1013,
2580,
2011,
1877,
1964,
2006,
2355,
1013,
2340,
1013,
2484,
1012,
1013,
1013,
9385,
1075,
2355,
1840,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
namespace TYPO3\CMS\Extbase\Tests\Unit\Persistence\Generic\Mapper;
/**
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Core\Tests\AccessibleObjectInterface;
use TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap;
use TYPO3\CMS\Core\DataHandling\TableColumnType;
use TYPO3\CMS\Core\DataHandling\TableColumnSubType;
/**
* Test case
*/
class DataMapFactoryTest extends \TYPO3\CMS\Core\Tests\UnitTestCase {
/**
* @return array
*/
public function oneToOneRelation() {
return array(
array('Tx_Myext_Domain_Model_Foo'),
array('TYPO3\\CMS\\Extbase\\Domain\\Model\\FrontendUser')
);
}
/**
* @test
* @dataProvider oneToOneRelation
*/
public function setRelationsDetectsOneToOneRelation($className) {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'foreign_field' => 'parentid'
);
$propertyMetaData = array(
'type' => $className,
'elementType' => NULL
);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', 'setOneToManyRelation', 'setManyToManyRelation'), array(), '', FALSE);
$mockDataMapFactory->expects($this->once())->method('setOneToOneRelation')->will($this->returnValue($mockColumnMap));
$mockDataMapFactory->expects($this->never())->method('setOneToManyRelation');
$mockDataMapFactory->expects($this->never())->method('setManyToManyRelation');
$mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData);
}
/**
* @test
*/
public function settingOneToOneRelationSetsRelationTableMatchFields() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$matchFields = array(
'fieldname' => 'foo_model'
);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'foreign_field' => 'parentid',
'foreign_match_fields' => $matchFields
);
$mockColumnMap->expects($this->once())
->method('setRelationTableMatchFields')
->with($matchFields);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE);
$mockDataMapFactory->_call('setOneToOneRelation', $mockColumnMap, $columnConfiguration);
}
/**
* @test
*/
public function settingOneToManyRelationSetsRelationTableMatchFields() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$matchFields = array(
'fieldname' => 'foo_model'
);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'foreign_field' => 'parentid',
'foreign_match_fields' => $matchFields
);
$mockColumnMap->expects($this->once())
->method('setRelationTableMatchFields')
->with($matchFields);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE);
$mockDataMapFactory->_call('setOneToManyRelation', $mockColumnMap, $columnConfiguration);
}
/**
* @test
*/
public function setRelationsDetectsOneToOneRelationWithIntermediateTable() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'MM' => 'tx_myextension_mm'
);
$propertyMetaData = array(
'type' => 'Tx_Myext_Domain_Model_Foo',
'elementType' => NULL
);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', 'setOneToManyRelation', 'setManyToManyRelation'), array(), '', FALSE);
$mockDataMapFactory->expects($this->never())->method('setOneToOneRelation');
$mockDataMapFactory->expects($this->never())->method('setOneToManyRelation');
$mockDataMapFactory->expects($this->once())->method('setManyToManyRelation')->will($this->returnValue($mockColumnMap));
$mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData);
}
/**
* @test
*/
public function setRelationsDetectsOneToManyRelation() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'foreign_field' => 'parentid',
'foreign_table_field' => 'parenttable'
);
$propertyMetaData = array(
'type' => 'TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage',
'elementType' => 'Tx_Myext_Domain_Model_Foo'
);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', 'setOneToManyRelation', 'setManyToManyRelation'), array(), '', FALSE);
$mockDataMapFactory->expects($this->never())->method('setOneToOneRelation');
$mockDataMapFactory->expects($this->once())->method('setOneToManyRelation')->will($this->returnValue($mockColumnMap));
$mockDataMapFactory->expects($this->never())->method('setManyToManyRelation');
$mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData);
}
/**
* @test
*/
public function setRelationsDetectsManyToManyRelationOfTypeSelect() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$columnConfiguration = array(
'type' => 'select',
'foreign_table' => 'tx_myextension_bar',
'MM' => 'tx_myextension_mm'
);
$propertyMetaData = array(
'type' => 'TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage',
'elementType' => 'Tx_Myext_Domain_Model_Foo'
);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', 'setOneToManyRelation', 'setManyToManyRelation'), array(), '', FALSE);
$mockDataMapFactory->expects($this->never())->method('setOneToOneRelation');
$mockDataMapFactory->expects($this->never())->method('setOneToManyRelation');
$mockDataMapFactory->expects($this->once())->method('setManyToManyRelation')->will($this->returnValue($mockColumnMap));
$mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData);
}
/**
* @test
*/
public function setRelationsDetectsManyToManyRelationOfTypeInlineWithIntermediateTable() {
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$columnConfiguration = array(
'type' => 'inline',
'foreign_table' => 'tx_myextension_righttable',
'MM' => 'tx_myextension_mm'
);
$propertyMetaData = array(
'type' => 'TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage',
'elementType' => 'Tx_Myext_Domain_Model_Foo'
);
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('setOneToOneRelation', 'setOneToManyRelation', 'setManyToManyRelation'), array(), '', FALSE);
$mockDataMapFactory->expects($this->never())->method('setOneToOneRelation');
$mockDataMapFactory->expects($this->never())->method('setOneToManyRelation');
$mockDataMapFactory->expects($this->once())->method('setManyToManyRelation')->will($this->returnValue($mockColumnMap));
$mockDataMapFactory->_callRef('setRelations', $mockColumnMap, $columnConfiguration, $propertyMetaData);
}
/**
* @test
*/
public function columnMapIsInitializedWithManyToManyRelationOfTypeSelect() {
$leftColumnsDefinition = array(
'rights' => array(
'type' => 'select',
'foreign_table' => 'tx_myextension_righttable',
'foreign_table_where' => 'WHERE 1=1',
'MM' => 'tx_myextension_mm',
'MM_table_where' => 'WHERE 2=2'
)
);
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$mockColumnMap->expects($this->once())->method('setTypeOfRelation')->with($this->equalTo(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY));
$mockColumnMap->expects($this->once())->method('setRelationTableName')->with($this->equalTo('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('setChildTableName')->with($this->equalTo('tx_myextension_righttable'));
$mockColumnMap->expects($this->once())->method('setChildTableWhereStatement')->with($this->equalTo('WHERE 1=1'));
$mockColumnMap->expects($this->once())->method('setChildSortByFieldName')->with($this->equalTo('sorting'));
$mockColumnMap->expects($this->once())->method('setParentKeyFieldName')->with($this->equalTo('uid_local'));
$mockColumnMap->expects($this->never())->method('setParentTableFieldName');
$mockColumnMap->expects($this->never())->method('setRelationTableMatchFields');
$mockColumnMap->expects($this->never())->method('setRelationTableInsertFields');
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE);
$mockDataMapFactory->_callRef('setManyToManyRelation', $mockColumnMap, $leftColumnsDefinition['rights']);
}
/**
* @test
*/
public function columnMapIsInitializedWithOppositeManyToManyRelationOfTypeSelect() {
$rightColumnsDefinition = array(
'lefts' => array(
'type' => 'select',
'foreign_table' => 'tx_myextension_lefttable',
'MM' => 'tx_myextension_mm',
'MM_opposite_field' => 'rights'
)
);
$leftColumnsDefinition['rights']['MM_opposite_field'] = 'opposite_field';
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$mockColumnMap->expects($this->once())->method('setTypeOfRelation')->with($this->equalTo(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY));
$mockColumnMap->expects($this->once())->method('setRelationTableName')->with($this->equalTo('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('setChildTableName')->with($this->equalTo('tx_myextension_lefttable'));
$mockColumnMap->expects($this->once())->method('setChildTableWhereStatement')->with(NULL);
$mockColumnMap->expects($this->once())->method('setChildSortByFieldName')->with($this->equalTo('sorting_foreign'));
$mockColumnMap->expects($this->once())->method('setParentKeyFieldName')->with($this->equalTo('uid_foreign'));
$mockColumnMap->expects($this->never())->method('setParentTableFieldName');
$mockColumnMap->expects($this->never())->method('setRelationTableMatchFields');
$mockColumnMap->expects($this->never())->method('setRelationTableInsertFields');
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'), array(), '', FALSE);
$mockDataMapFactory->_callRef('setManyToManyRelation', $mockColumnMap, $rightColumnsDefinition['lefts']);
}
/**
* @test
*/
public function columnMapIsInitializedWithManyToManyRelationOfTypeInlineAndIntermediateTable() {
$leftColumnsDefinition = array(
'rights' => array(
'type' => 'inline',
'foreign_table' => 'tx_myextension_righttable',
'MM' => 'tx_myextension_mm',
'foreign_sortby' => 'sorting'
)
);
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$mockColumnMap->expects($this->once())->method('setTypeOfRelation')->with($this->equalTo(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY));
$mockColumnMap->expects($this->once())->method('setRelationTableName')->with($this->equalTo('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('setChildTableName')->with($this->equalTo('tx_myextension_righttable'));
$mockColumnMap->expects($this->once())->method('setChildTableWhereStatement');
$mockColumnMap->expects($this->once())->method('setChildSortByFieldName')->with($this->equalTo('sorting'));
$mockColumnMap->expects($this->once())->method('setParentKeyFieldName')->with($this->equalTo('uid_local'));
$mockColumnMap->expects($this->never())->method('setParentTableFieldName');
$mockColumnMap->expects($this->never())->method('setRelationTableMatchFields');
$mockColumnMap->expects($this->never())->method('setRelationTableInsertFields');
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('getColumnsDefinition'), array(), '', FALSE);
$mockDataMapFactory->expects($this->never())->method('getColumnsDefinition');
$mockDataMapFactory->_callRef('setManyToManyRelation', $mockColumnMap, $leftColumnsDefinition['rights']);
}
/**
* @test
*/
public function columnMapIsInitializedWithManyToManyRelationWithoutPidColumn() {
$leftColumnsDefinition = array(
'rights' => array(
'type' => 'select',
'foreign_table' => 'tx_myextension_righttable',
'foreign_table_where' => 'WHERE 1=1',
'MM' => 'tx_myextension_mm'
)
);
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$mockColumnMap->expects($this->once())->method('setRelationTableName')->with($this->equalTo('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('getRelationTableName')->will($this->returnValue('tx_myextension_mm'));
$mockColumnMap->expects($this->never())->method('setrelationTablePageIdColumnName');
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('getControlSection'), array(), '', FALSE);
$mockDataMapFactory->expects($this->once())->method('getControlSection')->with($this->equalTo('tx_myextension_mm'))->will($this->returnValue(NULL));
$mockDataMapFactory->_callRef('setManyToManyRelation', $mockColumnMap, $leftColumnsDefinition['rights']);
}
/**
* @test
*/
public function columnMapIsInitializedWithManyToManyRelationWithPidColumn() {
$leftColumnsDefinition = array(
'rights' => array(
'type' => 'select',
'foreign_table' => 'tx_myextension_righttable',
'foreign_table_where' => 'WHERE 1=1',
'MM' => 'tx_myextension_mm'
)
);
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array(), '', FALSE);
$mockColumnMap->expects($this->once())->method('setRelationTableName')->with($this->equalTo('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('getRelationTableName')->will($this->returnValue('tx_myextension_mm'));
$mockColumnMap->expects($this->once())->method('setrelationTablePageIdColumnName')->with($this->equalTo('pid'));
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('getControlSection'), array(), '', FALSE);
$mockDataMapFactory->expects($this->once())->method('getControlSection')->with($this->equalTo('tx_myextension_mm'))->will($this->returnValue(array('ctrl' => array('foo' => 'bar'))));
$mockDataMapFactory->_callRef('setManyToManyRelation', $mockColumnMap, $leftColumnsDefinition['rights']);
}
/**
* @return array
*/
public function columnMapIsInitializedWithFieldEvaluationsForDateTimeFieldsDataProvider() {
return array(
'date field' => array('date', 'date'),
'datetime field' => array('datetime', 'datetime'),
'no date/datetime field' => array('', NULL),
);
}
/**
* @param string $type
* @param NULL|string $expectedValue
* @test
* @dataProvider columnMapIsInitializedWithFieldEvaluationsForDateTimeFieldsDataProvider
*/
public function columnMapIsInitializedWithFieldEvaluationsForDateTimeFields($type, $expectedValue) {
$columnDefinition = array(
'type' => 'input',
'dbType' => $type,
'eval' => $type,
);
$mockColumnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array('setDateTimeStorageFormat'), array(), '', FALSE);
if ($expectedValue !== NULL) {
$mockColumnMap->expects($this->once())->method('setDateTimeStorageFormat')->with($this->equalTo($type));
} else {
$mockColumnMap->expects($this->never())->method('setDateTimeStorageFormat');
}
$accessibleClassName = $this->buildAccessibleProxy('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory');
$accessibleDataMapFactory = new $accessibleClassName();
$accessibleDataMapFactory->_callRef('setFieldEvaluations', $mockColumnMap, $columnDefinition);
}
/**
* @test
* @expectedException \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidClassException
*/
public function buildDataMapThrowsExceptionIfClassNameIsNotKnown() {
$mockDataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('getControlSection'), array(), '', FALSE);
$cacheMock = $this->getMock('TYPO3\\CMS\\Core\\Cache\\Frontend\\VariableFrontend', array('get'), array(), '', FALSE);
$cacheMock->expects($this->any())->method('get')->will($this->returnValue(FALSE));
$mockDataMapFactory->_set('dataMapCache', $cacheMock);
$mockDataMapFactory->buildDataMap('UnknownObject');
}
/**
* @test
*/
public function buildDataMapFetchesSubclassesRecursively() {
$this->markTestSkipped('Incomplete mocking in a complex scenario. This should be a functional test');
$configuration = array(
'persistence' => array(
'classes' => array(
'TYPO3\\CMS\\Extbase\\Domain\\Model\\FrontendUser' => array(
'subclasses' => array(
'Tx_SampleExt_Domain_Model_LevelOne1' => 'Tx_SampleExt_Domain_Model_LevelOne1',
'Tx_SampleExt_Domain_Model_LevelOne2' => 'Tx_SampleExt_Domain_Model_LevelOne2'
)
),
'Tx_SampleExt_Domain_Model_LevelOne1' => array(
'subclasses' => array(
'Tx_SampleExt_Domain_Model_LevelTwo1' => 'Tx_SampleExt_Domain_Model_LevelTwo1',
'Tx_SampleExt_Domain_Model_LevelTwo2' => 'Tx_SampleExt_Domain_Model_LevelTwo2'
)
),
'Tx_SampleExt_Domain_Model_LevelOne2' => array(
'subclasses' => array()
)
)
)
);
$expectedSubclasses = array(
'Tx_SampleExt_Domain_Model_LevelOne1',
'Tx_SampleExt_Domain_Model_LevelTwo1',
'Tx_SampleExt_Domain_Model_LevelTwo2',
'Tx_SampleExt_Domain_Model_LevelOne2'
);
/** @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject $objectManager */
$objectManager = $this->getMock('TYPO3\\CMS\\Extbase\\Object\\ObjectManager', array('dummy'), array(), '', FALSE);
/** @var $configurationManager \TYPO3\CMS\Extbase\Configuration\ConfigurationManager|\PHPUnit_Framework_MockObject_MockObject */
$configurationManager = $this->getMock('TYPO3\\CMS\\Extbase\\Configuration\\ConfigurationManager');
$configurationManager->expects($this->once())->method('getConfiguration')->with('Framework')->will($this->returnValue($configuration));
/** @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapFactory $dataMapFactory */
$dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('test'));
$dataMapFactory->_set('reflectionService', new \TYPO3\CMS\Extbase\Reflection\ReflectionService());
$dataMapFactory->_set('objectManager', $objectManager);
$dataMapFactory->_set('configurationManager', $configurationManager);
$cacheMock = $this->getMock('TYPO3\\CMS\\Core\\Cache\\Frontend\\VariableFrontend', array(), array(), '', FALSE);
$cacheMock->expects($this->any())->method('get')->will($this->returnValue(FALSE));
$dataMapFactory->_set('dataMapCache', $cacheMock);
$dataMap = $dataMapFactory->buildDataMap('TYPO3\\CMS\\Extbase\\Domain\\Model\\FrontendUser');
$this->assertSame($expectedSubclasses, $dataMap->getSubclasses());
}
/**
* @return array
*/
public function classNameTableNameMappings() {
return array(
'Core classes' => array('TYPO3\\CMS\\Belog\\Domain\\Model\\LogEntry', 'tx_belog_domain_model_logentry'),
'Core classes with namespaces and leading backslash' => array('\\TYPO3\\CMS\\Belog\\Domain\\Model\\LogEntry', 'tx_belog_domain_model_logentry'),
'Extension classes' => array('ExtbaseTeam\\BlogExample\\Domain\\Model\\Blog', 'tx_blogexample_domain_model_blog'),
'Extension classes with namespaces and leading backslash' => array('\\ExtbaseTeam\\BlogExample\\Domain\\Model\\Blog', 'tx_blogexample_domain_model_blog'),
'Extension classes without namespace' => array('Tx_News_Domain_Model_News', 'tx_news_domain_model_news'),
'Extension classes without namespace but leading slash' => array('\\Tx_News_Domain_Model_News', 'tx_news_domain_model_news'),
);
}
/**
* @test
* @dataProvider classNameTableNameMappings
*/
public function resolveTableNameReturnsExpectedTablenames($className, $expected) {
$dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'));
$this->assertSame($expected, $dataMapFactory->_call('resolveTableName', $className));
}
/**
* @test
*/
public function createColumnMapReturnsAValidColumnMap() {
/** @var $dataMapFactory \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapFactory */
$dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'));
/** @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject $objectManager */
$objectManager = $this->getMock('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$columnMap = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\ColumnMap', array(), array('column', 'property'));
$objectManager->expects($this->once())->method('get')->will($this->returnValue($columnMap));
$dataMapFactory->_set('objectManager', $objectManager);
$this->assertEquals(
$columnMap,
$dataMapFactory->_call('createColumnMap', 'column', 'property')
);
}
/**
* @return array
*/
public function tcaConfigurationsContainingTypeAndInternalType() {
return array(
array(array('type' => 'input'), TableColumnType::INPUT, NULL),
array(array('type' => 'text'), TableColumnType::TEXT, NULL),
array(array('type' => 'check'), TableColumnType::CHECK, NULL),
array(array('type' => 'radio'), TableColumnType::RADIO, NULL),
array(array('type' => 'select'), TableColumnType::SELECT, NULL),
array(array('type' => 'group', 'internal_type' => 'db'), TableColumnType::GROUP, TableColumnSubType::DB),
array(array('type' => 'group', 'internal_type' => 'file'), TableColumnType::GROUP, TableColumnSubType::FILE),
array(array('type' => 'group', 'internal_type' => 'file_reference'), TableColumnType::GROUP, TableColumnSubType::FILE_REFERENCE),
array(array('type' => 'group', 'internal_type' => 'folder'), TableColumnType::GROUP, TableColumnSubType::FOLDER),
array(array('type' => 'none'), TableColumnType::NONE, NULL),
array(array('type' => 'passthrough'), TableColumnType::PASSTHROUGH, NULL),
array(array('type' => 'user'), TableColumnType::USER, NULL),
array(array('type' => 'flex'), TableColumnType::FLEX, NULL),
array(array('type' => 'inline'), TableColumnType::INLINE, NULL),
);
}
/**
* @test
* @dataProvider tcaConfigurationsContainingTypeAndInternalType
*
* @param array $columnConfiguration
* @param string $type
* @param string $internalType
*/
public function setTypeDetectsTypeAndInternalTypeProperly(array $columnConfiguration, $type, $internalType) {
/** @var $dataMapFactory \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapFactory | AccessibleObjectInterface */
$dataMapFactory = $this->getAccessibleMock('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapFactory', array('dummy'));
/** @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap $columnMap */
$columnMap = $this->getAccessibleMock('TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap', array('dummy'), array(), '', FALSE);
$dataMapFactory->_call('setType', $columnMap, $columnConfiguration);
$this->assertEquals($type, (string) $columnMap->getType());
$this->assertEquals($internalType, (string) $columnMap->getInternalType());
}
}
| TimboDynamite/TYPO3-Testprojekt | typo3/sysext/extbase/Tests/Unit/Persistence/Generic/Mapper/DataMapFactoryTest.php | PHP | gpl-2.0 | 24,950 | [
30522,
1026,
1029,
25718,
3415,
15327,
5939,
6873,
2509,
1032,
4642,
2015,
1032,
4654,
2102,
15058,
1032,
5852,
1032,
3131,
1032,
28297,
1032,
12391,
1032,
4949,
4842,
1025,
1013,
1008,
1008,
1008,
2023,
5371,
2003,
2112,
1997,
1996,
5939,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
namespace App\Modules\OAuth\Controllers;
use App\Http\Controllers\Controller;
use App\Modules\Users\Controllers\UserController;
use App\Modules\Users\Models\User;
use App\Modules\Users\Supports\MailCheckSupport;
use Laravel\Socialite\Facades\Socialite as Socialite;
use Illuminate\Http\Request;
use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
/**
* Class LoginController
* @package App\Modules\OAuth\Controllers
*/
class LoginController extends Controller
{
/**
* @var JWTAuth
*/
protected $jwt;
/**
* @var UserController
*/
public $userController;
/**
* LoginController constructor.
* @param JWTAuth $jwt
* @param UserController $userController
*/
public function __construct(JWTAuth $jwt, UserController $userController)
{
$this->jwt = $jwt;
$this->userController = $userController;
}
/**
* @param $provider
* @return mixed
*/
public function redirectToProvider($provider)
{
return Socialite::driver($provider)
->stateless()
->redirect();
}
/**
* @param $provider
* @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory
*/
public function handleProviderCallback($provider)
{
try {
/**
* get user infos with callback provider token
*/
$user = Socialite::driver($provider)
->stateless()
->user();
/**
* check if user email exists in database
*/
if(!MailCheckSupport::userEmailCheck($user->email)) {
/**
* create user array infos to save in database
*/
$userInfos = [
'name' => $user->name,
'email' => $user->email,
'password' => null,
'remember_token' => str_random(10),
'provider' => $provider,
'provider_id' => $user->id,
'avatar_url' => $user->avatar
];
/**
* generate a personal token access from this new user
*/
$token = $this->userController->createUserFromProvider($userInfos);
} else {
/**
* search existent user in database and generate your personal token access
*/
$existsUser = User::where('email',$user->email)->first();
$token = $this->jwt->fromUser($existsUser);
}
if ( env('REDIR_URL') ) {
if (env('REDIR_TOKEN_AS_PARAM')) {
$redirWithToken = env('REDIR_URL') . "/token:{$token}";
} else {
$redirWithToken = env('REDIR_URL') . "?token={$token}";
}
return redirect($redirWithToken);
}
return response()->json(compact('token'));
} catch (\Exception $ex) {
return response($ex->getMessage(),500);
}
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function authenticate(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255',
'password' => 'required',
]);
try {
if (! $token = $this->jwt->attempt($request->only('email', 'password'))) {
return response()->json(['user_not_found'], 404);
}
} catch (TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (JWTException $e) {
return response()->json(['token_absent' => $e->getMessage()], $e->getStatusCode());
}
return response()->json(compact('token'));
}
} | alissonphp/lumen-api-skeleton | app/Modules/OAuth/Controllers/LoginController.php | PHP | mit | 4,190 | [
30522,
1026,
1029,
25718,
3415,
15327,
10439,
1032,
14184,
1032,
1051,
4887,
2705,
1032,
21257,
1025,
2224,
10439,
1032,
8299,
1032,
21257,
1032,
11486,
1025,
2224,
10439,
1032,
14184,
1032,
5198,
1032,
21257,
1032,
5310,
8663,
13181,
10820,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package org.spincast.tests.json;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import org.junit.Test;
import org.spincast.core.json.JsonArray;
import org.spincast.core.json.JsonManager;
import org.spincast.core.json.JsonObject;
import org.spincast.shaded.org.apache.commons.lang3.time.DateUtils;
import org.spincast.testing.defaults.NoAppTestingBase;
import com.google.inject.Inject;
public class JsonPathsSelectTest extends NoAppTestingBase {
@Inject
protected JsonManager jsonManager;
protected JsonManager getJsonManager() {
return this.jsonManager;
}
@Test
public void directString() throws Exception {
JsonObject obj = getJsonManager().create();
obj.set("key1", "value1");
String result = obj.getString("key1");
assertEquals("value1", result);
result = obj.getString(".key1");
assertEquals("value1", result);
result = obj.getString("['key1']");
assertEquals("value1", result);
result = obj.getString("[\"key1\"]");
assertEquals("value1", result);
result = obj.getString("nope", "defaultVal");
assertEquals("defaultVal", result);
}
@Test
public void directInteger() throws Exception {
JsonObject obj = getJsonManager().create();
obj.set("key1", 123);
Integer result = obj.getInteger("key1");
assertEquals(new Integer(123), result);
result = obj.getInteger("['key1']");
assertEquals(new Integer(123), result);
result = obj.getInteger("[\"key1\"]");
assertEquals(new Integer(123), result);
result = obj.getInteger("nope", 456);
assertEquals(new Integer(456), result);
}
@Test
public void directLong() throws Exception {
JsonObject obj = getJsonManager().create();
obj.set("key1", 123L);
Long result = obj.getLong("key1");
assertEquals(new Long(123), result);
result = obj.getLong("['key1']");
assertEquals(new Long(123), result);
result = obj.getLong("[\"key1\"]");
assertEquals(new Long(123), result);
result = obj.getLong("nope", 456L);
assertEquals(new Long(456), result);
}
@Test
public void directFloat() throws Exception {
JsonObject obj = getJsonManager().create();
obj.set("key1", 12.34F);
Float result = obj.getFloat("key1");
assertEquals(new Float(12.34), result);
result = obj.getFloat("['key1']");
assertEquals(new Float(12.34), result);
result = obj.getFloat("[\"key1\"]");
assertEquals(new Float(12.34), result);
result = obj.getFloat("nope", 56.78F);
assertEquals(new Float(56.78), result);
}
@Test
public void directDouble() throws Exception {
JsonObject obj = getJsonManager().create();
obj.set("key1", 12.34);
Double result = obj.getDouble("key1");
assertEquals(new Double(12.34), result);
result = obj.getDouble("['key1']");
assertEquals(new Double(12.34), result);
result = obj.getDouble("[\"key1\"]");
assertEquals(new Double(12.34), result);
result = obj.getDouble("nope", 56.78);
assertEquals(new Double(56.78), result);
}
@Test
public void directBoolean() throws Exception {
JsonObject obj = getJsonManager().create();
obj.set("key1", true);
Boolean result = obj.getBoolean("key1");
assertEquals(true, result);
result = obj.getBoolean("['key1']");
assertEquals(true, result);
result = obj.getBoolean("[\"key1\"]");
assertEquals(true, result);
result = obj.getBoolean("nope", true);
assertEquals(true, result);
}
@Test
public void directBigDecimal() throws Exception {
JsonObject obj = getJsonManager().create();
obj.set("key1", new BigDecimal("1234"));
BigDecimal result = obj.getBigDecimal("key1");
assertEquals(new BigDecimal("1234"), result);
result = obj.getBigDecimal("['key1']");
assertEquals(new BigDecimal("1234"), result);
result = obj.getBigDecimal("[\"key1\"]");
assertEquals(new BigDecimal("1234"), result);
result = obj.getBigDecimal("nope", new BigDecimal("567"));
assertEquals(new BigDecimal("567"), result);
}
@Test
public void directBytes() throws Exception {
JsonObject obj = getJsonManager().create();
obj.set("key1", "test".getBytes("UTF-8"));
byte[] result = obj.getBytesFromBase64String("key1");
assertTrue(Arrays.equals("test".getBytes("UTF-8"), result));
result = obj.getBytesFromBase64String("['key1']");
assertTrue(Arrays.equals("test".getBytes("UTF-8"), result));
result = obj.getBytesFromBase64String("[\"key1\"]");
assertTrue(Arrays.equals("test".getBytes("UTF-8"), result));
result = obj.getBytesFromBase64String("nope", "test2".getBytes("UTF-8"));
assertTrue(Arrays.equals("test2".getBytes("UTF-8"), result));
}
@Test
public void directDate() throws Exception {
Date date = new Date();
JsonObject obj = getJsonManager().create();
obj.set("key1", date);
Date result = obj.getDate("key1");
assertEquals(date, result);
result = obj.getDate("['key1']");
assertEquals(date, result);
result = obj.getDate("[\"key1\"]");
assertEquals(date, result);
Date newDate = DateUtils.addHours(date, 1);
result = obj.getDate("nope", newDate);
assertEquals(newDate, result);
}
@Test
public void obj() throws Exception {
JsonObject inner = getJsonManager().create();
inner.set("key1", "value1");
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
JsonObject result = obj.getJsonObject("inner");
assertNotNull(result);
assertEquals("value1", result.getString("key1"));
result = obj.getJsonObject("nope");
assertNull(result);
result = obj.getJsonObjectOrEmpty("nope");
assertNotNull(result);
JsonObject defaultObj = getJsonManager().create();
defaultObj.set("key2", "value2");
result = obj.getJsonObject("nope", defaultObj);
assertNotNull(result);
assertEquals("value2", result.getString("key2"));
}
@Test
public void array() throws Exception {
JsonArray inner = getJsonManager().createArray();
inner.add("value1");
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
JsonArray result = obj.getJsonArray("inner");
assertNotNull(result);
assertEquals("value1", result.getString(0));
result = obj.getJsonArray("nope");
assertNull(result);
result = obj.getJsonArrayOrEmpty("nope");
assertNotNull(result);
JsonArray defaultArray = getJsonManager().createArray();
defaultArray.add("value2");
result = obj.getJsonArray("nope", defaultArray);
assertNotNull(result);
assertEquals("value2", result.getString(0));
}
@Test
public void objString() throws Exception {
JsonObject inner = getJsonManager().create();
inner.set("key1", "value1");
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
String result = obj.getString("inner.key1");
assertEquals("value1", result);
result = obj.getString("nope", "defaultVal");
assertEquals("defaultVal", result);
result = obj.getString("inner.nope", "defaultVal");
assertEquals("defaultVal", result);
}
@Test
public void objInteger() throws Exception {
JsonObject inner = getJsonManager().create();
inner.set("key1", 123);
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
Integer result = obj.getInteger("inner.key1");
assertEquals(new Integer(123), result);
result = obj.getInteger("nope", 456);
assertEquals(new Integer(456), result);
result = obj.getInteger("inner.nope", 456);
assertEquals(new Integer(456), result);
}
@Test
public void objObjString() throws Exception {
JsonObject inner2 = getJsonManager().create();
inner2.set("key1", "value1");
JsonObject inner = getJsonManager().create();
inner.set("inner2", inner2);
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
String result = obj.getString("inner.inner2.key1");
assertEquals("value1", result);
result = obj.getString("inner.nope.key1");
assertEquals(null, result);
result = obj.getString("inner.nope.key1", "defaultVal");
assertEquals("defaultVal", result);
result = obj.getString("nope", "defaultVal");
assertEquals("defaultVal", result);
result = obj.getString("inner.nope", "defaultVal");
assertEquals("defaultVal", result);
}
@Test
public void arrayString() throws Exception {
JsonArray inner = getJsonManager().createArray();
inner.add("value1");
inner.add("value2");
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
String result = obj.getString("inner[0]");
assertEquals("value1", result);
result = obj.getString("inner[1]");
assertEquals("value2", result);
result = obj.getString("inner[2]");
assertEquals(null, result);
result = obj.getString("inner[2]", "defaultVal");
assertEquals("defaultVal", result);
}
@Test
public void arrayArrayString() throws Exception {
JsonArray inner2 = getJsonManager().createArray();
inner2.add("value1");
inner2.add("value2");
JsonArray inner = getJsonManager().createArray();
inner.add("value3");
inner.add(inner2);
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
String result = obj.getString("inner[0]");
assertEquals("value3", result);
result = obj.getString("inner[1][0]");
assertEquals("value1", result);
result = obj.getString("inner[1][1]");
assertEquals("value2", result);
result = obj.getString("inner[1][2]");
assertEquals(null, result);
result = obj.getString("inner[1][2]", "defaultVal");
assertEquals("defaultVal", result);
}
@Test
public void objArrayString() throws Exception {
JsonArray inner2 = getJsonManager().createArray();
inner2.add("value1");
inner2.add("value2");
JsonObject inner = getJsonManager().create();
inner.set("inner2", inner2);
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
String result = obj.getString("inner.inner2[0]");
assertEquals("value1", result);
result = obj.getString("inner.inner2[1]");
assertEquals("value2", result);
result = obj.getString("inner.inner2[2]");
assertEquals(null, result);
result = obj.getString("inner.inner2[2]", "defaultVal");
assertEquals("defaultVal", result);
}
@Test
public void arrayObjString() throws Exception {
JsonObject inner2 = getJsonManager().create();
inner2.set("key1", "value1");
JsonArray inner = getJsonManager().createArray();
inner.add("value3");
inner.add(inner2);
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
String result = obj.getString("inner[0]");
assertEquals("value3", result);
result = obj.getString("inner[1].key1");
assertEquals("value1", result);
result = obj.getString("inner[1].nope");
assertEquals(null, result);
result = obj.getString("inner[1].nope", "defaultVal");
assertEquals("defaultVal", result);
}
@Test
public void lots() throws Exception {
Date date = new Date();
JsonArray inner7 = getJsonManager().createArray();
inner7.add("value7");
inner7.add(123);
inner7.add(12.34);
inner7.add(true);
inner7.add(date);
JsonObject inner6 = getJsonManager().create();
inner6.set("key5", inner7);
inner6.set("key6", "value6");
JsonObject inner5 = getJsonManager().create();
inner5.set("key3", "value3");
inner5.set("key4", inner6);
JsonArray inner4 = getJsonManager().createArray();
inner4.add("value2");
inner4.add(inner5);
JsonArray inner3 = getJsonManager().createArray();
inner3.add(inner4);
JsonObject inner2 = getJsonManager().create();
inner2.set("key1", "value1");
inner2.set("key2", inner3);
JsonArray inner = getJsonManager().createArray();
inner.add("value0");
inner.add(inner2);
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
String result = obj.getString("inner[0]");
assertEquals("value0", result);
result = obj.getString("inner[1].key1");
assertEquals("value1", result);
result = obj.getString("inner[1].key2[0][0]");
assertEquals("value2", result);
result = obj.getString("inner[1].key2[0][1].key3");
assertEquals("value3", result);
result = obj.getString("inner[1].key2[0][1].key4.key6");
assertEquals("value6", result);
result = obj.getString("inner[1].key2[0][1].key4.key5[0]");
assertEquals("value7", result);
result = obj.getString("inner[1]['key2'][0][1]['key4']['key5'][0]");
assertEquals("value7", result);
result = obj.getString("inner[1][\"key2\"][0][1][\"key4\"][\"key5\"][0]");
assertEquals("value7", result);
Integer resultInt = obj.getInteger("inner[1].key2[0][1].key4.key5[1]");
assertEquals(new Integer(123), resultInt);
Double resultDouble = obj.getDouble("inner[1].key2[0][1].key4.key5[2]");
assertEquals(new Double(12.34), resultDouble);
Boolean resultBoolean = obj.getBoolean("inner[1].key2[0][1].key4.key5[3]");
assertEquals(true, resultBoolean);
Date resultDate = obj.getDate("inner[1].key2[0][1].key4.key5[4]");
assertEquals(date, resultDate);
}
@Test
public void fromArrayString() throws Exception {
JsonArray array = getJsonManager().createArray();
array.add("value1");
String result = array.getString("[0]");
assertEquals("value1", result);
result = array.getString("[1]", "defaultVal");
assertEquals("defaultVal", result);
}
@Test
public void fromArrayArrayString() throws Exception {
JsonArray inner = getJsonManager().createArray();
inner.add("value2");
JsonArray array = getJsonManager().createArray();
array.add("value1");
array.add(inner);
String result = array.getString("[0]");
assertEquals("value1", result);
result = array.getString("[1][0]");
assertEquals("value2", result);
result = array.getString("[1][1]");
assertEquals(null, result);
result = array.getString("[1][1]", "defaultVal");
assertEquals("defaultVal", result);
}
@Test
public void fromArrayObjectString() throws Exception {
JsonObject inner = getJsonManager().create();
inner.set("key2", "value2");
JsonArray array = getJsonManager().createArray();
array.add("value1");
array.add(inner);
String result = array.getString("[0]");
assertEquals("value1", result);
result = array.getString("[1].key2");
assertEquals("value2", result);
result = array.getString("[1]['key2']");
assertEquals("value2", result);
result = array.getString("[1][\"key2\"]");
assertEquals("value2", result);
}
@Test
public void fromArrayLots() throws Exception {
JsonArray inner7 = getJsonManager().createArray();
inner7.add("value7");
JsonObject inner6 = getJsonManager().create();
inner6.set("key5", inner7);
inner6.set("key6", "value6");
JsonObject inner5 = getJsonManager().create();
inner5.set("key3", "value3");
inner5.set("key4", inner6);
JsonArray inner4 = getJsonManager().createArray();
inner4.add("value2");
inner4.add(inner5);
JsonArray inner3 = getJsonManager().createArray();
inner3.add(inner4);
JsonObject inner2 = getJsonManager().create();
inner2.set("key1", "value1");
inner2.set("key2", inner3);
JsonArray inner = getJsonManager().createArray();
inner.add("value0");
inner.add(inner2);
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
JsonArray array = getJsonManager().createArray();
array.add("toto");
array.add(obj);
String result = array.getString("[0]");
assertEquals("toto", result);
result = array.getString("[1].inner[1].key2[0][1]['key4'].key5[0]");
assertEquals("value7", result);
}
@Test
public void invalidUnclosedBrackets() throws Exception {
JsonArray inner = getJsonManager().createArray();
inner.add("value1");
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
try {
obj.getString("inner[2", "defaultVal");
fail();
} catch (Exception ex) {
}
}
@Test
public void invalidEmptyKey() throws Exception {
JsonObject inner = getJsonManager().create();
inner.set("key1", "value1");
JsonObject obj = getJsonManager().create();
obj.set("inner", inner);
try {
obj.getString("inner..inner", "defaultVal");
fail();
} catch (Exception ex) {
System.out.println(ex);
}
}
@Test
public void jsonPathIsUsedAsIsWithBracketsAndQuotesAndCorrectEscaping() throws Exception {
JsonObject obj = getJsonManager().create();
obj.setNoKeyParsing("this'.\"is[\\a.key[x", "value1", false);
String result = obj.getString("[\"this'.\\\"is[\\\\a.key[x\"]", "defaultVal");
assertEquals("value1", result);
result = obj.getString("['this\\'.\"is[\\\\a.key[x']", "defaultVal");
assertEquals("value1", result);
result = obj.getString("this'.\"is[\\a.key[x", "defaultVal");
assertEquals("defaultVal", result);
}
@Test
public void jsonPathOnImmutableObjets() throws Exception {
JsonObject obj = getJsonManager().create();
obj.set("aaa.bbb[2].ccc", "Stromgol");
obj = obj.clone(false);
assertFalse(obj.isMutable());
assertEquals("Stromgol", obj.getString("aaa.bbb[2].ccc"));
JsonArray array = obj.getJsonArray("aaa.bbb");
assertNotNull(array);
assertFalse(array.isMutable());
obj = obj.getJsonObject("aaa.bbb[2]");
assertNotNull(obj);
assertFalse(obj.isMutable());
assertEquals("Stromgol", obj.getString(".ccc"));
assertEquals("Stromgol", obj.getString("ccc"));
assertEquals("Stromgol", obj.getString("['ccc']"));
assertEquals("Stromgol", obj.getString("[\"ccc\"]"));
}
}
| spincast/spincast-framework | spincast-core-parent/spincast-core-tests/src/test/java/org/spincast/tests/json/JsonPathsSelectTest.java | Java | apache-2.0 | 19,925 | [
30522,
7427,
8917,
1012,
6714,
10526,
1012,
5852,
1012,
1046,
3385,
1025,
12324,
10763,
8917,
1012,
12022,
4183,
1012,
20865,
1012,
20865,
2063,
26426,
2015,
1025,
12324,
10763,
8917,
1012,
12022,
4183,
1012,
20865,
1012,
20865,
7011,
4877,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//
// Copyright (c) 2015 CNRS
//
// This file is part of Pinocchio and is mainly inspired
// by software hpp-model-urdf
// Pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_collada_to_fcl_hpp__
#define __se3_collada_to_fcl_hpp__
#include <limits>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <assimp/DefaultLogger.h>
#include <assimp/assimp.hpp>
#include <assimp/aiScene.h>
#include <assimp/aiPostProcess.h>
#include <assimp/IOStream.h>
#include <assimp/IOSystem.h>
#include <hpp/fcl/BV/OBBRSS.h>
#include <hpp/fcl/BVH/BVH_model.h>
typedef fcl::BVHModel< fcl::OBBRSS > PolyhedronType;
typedef boost::shared_ptr <PolyhedronType> PolyhedronPtrType;
struct TriangleAndVertices
{
void clear()
{
vertices_.clear ();
triangles_.clear ();
}
std::vector <fcl::Vec3f> vertices_;
std::vector <fcl::Triangle> triangles_;
};
/**
* @brief Recursive procedure for building a mesh
*
* @param[in] scale Scale to apply when reading the ressource
* @param[in] scene Pointer to the assimp scene
* @param[in] node Current node of the scene
* @param subMeshIndexes Submesh triangles indexes interval
* @param[in] mesh The mesh that must be built
* @param tv Triangles and Vertices of the mesh submodels
*/
inline void buildMesh (const ::urdf::Vector3& scale, const aiScene* scene, const aiNode* node,
std::vector<unsigned>& subMeshIndexes, const PolyhedronPtrType& mesh,
TriangleAndVertices& tv)
{
if (!node) return;
aiMatrix4x4 transform = node->mTransformation;
aiNode *pnode = node->mParent;
while (pnode)
{
// Don't convert to y-up orientation, which is what the root node in
// Assimp does
if (pnode->mParent != NULL)
{
transform = pnode->mTransformation * transform;
}
pnode = pnode->mParent;
}
for (uint32_t i = 0; i < node->mNumMeshes; i++)
{
aiMesh* input_mesh = scene->mMeshes[node->mMeshes[i]];
unsigned oldNbPoints = mesh->num_vertices;
unsigned oldNbTriangles = mesh->num_tris;
// Add the vertices
for (uint32_t j = 0; j < input_mesh->mNumVertices; j++)
{
aiVector3D p = input_mesh->mVertices[j];
p *= transform;
tv.vertices_.push_back (fcl::Vec3f (p.x * scale.x,
p.y * scale.y,
p.z * scale.z));
}
// add the indices
for (uint32_t j = 0; j < input_mesh->mNumFaces; j++)
{
aiFace& face = input_mesh->mFaces[j];
// FIXME: can add only triangular faces.
tv.triangles_.push_back (fcl::Triangle( oldNbPoints + face.mIndices[0],
oldNbPoints + face.mIndices[1],
oldNbPoints + face.mIndices[2]));
}
// Save submesh triangles indexes interval.
if (subMeshIndexes.size () == 0)
{
subMeshIndexes.push_back (0);
}
subMeshIndexes.push_back (oldNbTriangles + input_mesh->mNumFaces);
}
for (uint32_t i=0; i < node->mNumChildren; ++i)
{
buildMesh(scale, scene, node->mChildren[i], subMeshIndexes, mesh, tv);
}
}
/**
* @brief Convert an assimp scene to a mesh
*
* @param[in] name File (ressource) transformed into an assimp scene in loa
* @param[in] scale Scale to apply when reading the ressource
* @param[in] scene Pointer to the assimp scene
* @param[in] mesh The mesh that must be built
*/
inline void meshFromAssimpScene (const std::string& name, const ::urdf::Vector3& scale,
const aiScene* scene,const PolyhedronPtrType& mesh)
{
TriangleAndVertices tv;
if (!scene->HasMeshes())
{
throw std::runtime_error (std::string ("No meshes found in file ")+
name);
}
std::vector<unsigned> subMeshIndexes;
int res = mesh->beginModel ();
if (res != fcl::BVH_OK)
{
std::ostringstream error;
error << "fcl BVHReturnCode = " << res;
throw std::runtime_error (error.str ());
}
tv.clear();
buildMesh (scale, scene, scene->mRootNode, subMeshIndexes, mesh, tv);
mesh->addSubModel (tv.vertices_, tv.triangles_);
mesh->endModel ();
}
/**
* @brief Read a mesh file and convert it to a polyhedral mesh
*
* @param[in] resource_path Path to the ressource mesh file to be read
* @param[in] scale Scale to apply when reading the ressource
* @param[in] polyhedron The resulted polyhedron
*/
inline void loadPolyhedronFromResource ( const std::string& resource_path, const ::urdf::Vector3& scale,
const PolyhedronPtrType& polyhedron)
{
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(resource_path.c_str(), aiProcess_SortByPType| aiProcess_GenNormals|
aiProcess_Triangulate|aiProcess_GenUVCoords|
aiProcess_FlipUVs);
if (!scene)
{
throw std::runtime_error (std::string ("Could not load resource ") + resource_path + std::string ("\n") +
importer.GetErrorString ());
}
meshFromAssimpScene (resource_path, scale, scene, polyhedron);
}
/**
* @brief Transform a cURL readable path (package://..) to an absolute path for urdf collision path
*
* @param urdf_mesh_path The path given in the urdf file (package://..)
* @param[in] meshRootDir Root path to the directory where meshes are located
*
* @return The absolute path to the mesh file
*/
inline std::string fromURDFMeshPathToAbsolutePath(std::string & urdf_mesh_path, std::string meshRootDir)
{
std::string absolutePath = std::string(meshRootDir +
urdf_mesh_path.substr(10, urdf_mesh_path.size()));
return absolutePath;
}
#endif // __se3_collada_to_fcl_hpp__
| aelkhour/pinocchio | src/multibody/parser/from-collada-to-fcl.hpp | C++ | bsd-2-clause | 6,613 | [
30522,
1013,
1013,
1013,
1013,
9385,
1006,
1039,
1007,
2325,
27166,
2869,
1013,
1013,
1013,
1013,
2023,
5371,
2003,
2112,
1997,
9231,
10085,
23584,
1998,
2003,
3701,
4427,
1013,
1013,
2011,
4007,
6522,
2361,
1011,
2944,
1011,
24471,
20952,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<div class="commune_descr limited">
<p>
Gasville-Oisème est
une commune localisée dans le département de l'Eure-et-Loir en Centre. Elle totalisait 1 176 habitants en 2008.</p>
<p>La commune propose quelques équipements sportifs, elle propose entre autres un centre d'équitation et une boucle de randonnée.</p>
<p>Le nombre d'habitations, à Gasville-Oisème, se décomposait en 2011 en 17 appartements et 496 maisons soit
un marché plutôt équilibré.</p>
<p>À Gasville-Oisème, le prix moyen à la vente d'un appartement s'évalue à 12 611 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 739 € du m². À la location la valorisation moyenne se situe à 19,59 € du m² par mois.</p>
<p>Gasville-Oisème est situé à seulement 7 Kilomètres de Chartres, les étudiants qui aurons besoin de se loger à pas cher pourront envisager de louer un appartement à Gasville-Oisème. Gasville-Oisème est aussi un bon placement locatif du fait de sa proximité de Chartres et de ses Universités. Il sera envisageable de trouver un appartement à acheter. </p>
<p>À proximité de Gasville-Oisème sont situées les villes de
<a href="{{VLROOT}}/immobilier/saint-prest_28358/">Saint-Prest</a> localisée à 2 km, 2 135 habitants,
<a href="{{VLROOT}}/immobilier/leves_28209/">Lèves</a> située à 6 km, 4 405 habitants,
<a href="{{VLROOT}}/immobilier/soulaires_28379/">Soulaires</a> située à 4 km, 427 habitants,
<a href="{{VLROOT}}/immobilier/poisvilliers_28301/">Poisvilliers</a> située à 7 km, 327 habitants,
<a href="{{VLROOT}}/immobilier/jouy_28201/">Jouy</a> située à 3 km, 1 888 habitants,
<a href="{{VLROOT}}/immobilier/champseru_28073/">Champseru</a> située à 7 km, 305 habitants,
entre autres. De plus, Gasville-Oisème est située à seulement sept km de <a href="{{VLROOT}}/immobilier/chartres_28085/">Chartres</a>.</p>
</div>
| donaldinou/frontend | src/Viteloge/CoreBundle/Resources/descriptions/28173.html | HTML | mit | 1,962 | [
30522,
1026,
4487,
2615,
2465,
1027,
1000,
5715,
1035,
4078,
26775,
3132,
1000,
1028,
1026,
1052,
1028,
3806,
3077,
1011,
1051,
5562,
4168,
9765,
16655,
5715,
2334,
5562,
2063,
18033,
3393,
18280,
13665,
2139,
1048,
1005,
7327,
2890,
1011,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//----------------------------------------------------------------------------//
// //
// A l i g n m e n t T e s t //
// //
//----------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr"> //
// Copyright (C) Hervé Bitteur 2000-2011. All rights reserved. //
// This software is released under the GNU General Public License. //
// Goto http://kenai.com/projects/audiveris to report bugs or suggestions. //
//----------------------------------------------------------------------------//
// </editor-fold>
package omr.ui.symbol;
import omr.ui.symbol.Alignment.Horizontal;
import static omr.ui.symbol.Alignment.Horizontal.*;
import omr.ui.symbol.Alignment.Vertical;
import static omr.ui.symbol.Alignment.Vertical.*;
import static org.junit.Assert.*;
import org.junit.Test;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Class {@code AlignmentTest}
*
* @author Hervé Bitteur
*/
public class AlignmentTest
{
//~ Instance fields --------------------------------------------------------
/** Map Alignment -> Point */
Map<Alignment, Point> points = new HashMap<>();
//~ Constructors -----------------------------------------------------------
/**
* Creates a new AlignmentTest object.
*/
public AlignmentTest ()
{
}
//~ Methods ----------------------------------------------------------------
/**
* Test of toPoint method, of class Alignment.
*/
@Test
public void testToPoint ()
{
System.out.println("toPoint");
Rectangle rect = new Rectangle(-6, -26, 50, 38);
assignPoints();
for (Vertical vert : Vertical.values()) {
for (Horizontal hori : Horizontal.values()) {
Alignment instance = new Alignment(vert, hori);
Point start = points.get(instance);
for (Vertical v : Vertical.values()) {
for (Horizontal h : Horizontal.values()) {
Alignment expAlign = new Alignment(v, h);
Point to = instance.toPoint(expAlign, rect);
Point target = new Point(start);
target.translate(to.x, to.y);
System.out.print(
instance + " + " + to + " = " + target);
Alignment align = getAlign(target);
Point expTarget = points.get(expAlign);
System.out.println(" " + expAlign + " =? " + align);
assertEquals("Different points", expTarget, target);
assertEquals("Different aligns", expAlign, align);
}
}
System.out.println();
}
}
}
// /**
// * Test of toPoint method, of class Alignment.
// */
// @Test
// public void testToPoint2D ()
// {
// System.out.println("toPoint2D");
//
// Rectangle2D rect = new Rectangle2D.Float(-5.8f, -26.0f, 50.0f, 37.4f);
// Point2D expTo = null;
//
// for (Vertical vert : Vertical.values()) {
// for (Horizontal hori : Horizontal.values()) {
// Alignment instance = new Alignment(vert, hori);
//
// for (Vertical v : Vertical.values()) {
// for (Horizontal h : Horizontal.values()) {
// Alignment that = new Alignment(v, h);
// Point2D to = instance.toPoint(that, rect);
//
// System.out.println(
// instance + " + " + to + " = " + that);
// }
// }
//
// System.out.println();
// }
// }
// }
private Alignment getAlign (Point target)
{
for (Entry<Alignment, Point> entry : points.entrySet()) {
if (entry.getValue()
.equals(target)) {
return entry.getKey();
}
}
return null;
}
private void assignPoints ()
{
points.put(new Alignment(TOP, LEFT), new Point(-6, -26));
points.put(new Alignment(TOP, CENTER), new Point(19, -26));
points.put(new Alignment(TOP, RIGHT), new Point(44, -26));
points.put(new Alignment(TOP, XORIGIN), new Point(0, -26));
points.put(new Alignment(MIDDLE, LEFT), new Point(-6, -7));
points.put(new Alignment(MIDDLE, CENTER), new Point(19, -7));
points.put(new Alignment(MIDDLE, RIGHT), new Point(44, -7));
points.put(new Alignment(MIDDLE, XORIGIN), new Point(0, -7));
points.put(new Alignment(BOTTOM, LEFT), new Point(-6, 12));
points.put(new Alignment(BOTTOM, CENTER), new Point(19, 12));
points.put(new Alignment(BOTTOM, RIGHT), new Point(44, 12));
points.put(new Alignment(BOTTOM, XORIGIN), new Point(0, 12));
points.put(new Alignment(BASELINE, LEFT), new Point(-6, 0));
points.put(new Alignment(BASELINE, CENTER), new Point(19, 0));
points.put(new Alignment(BASELINE, RIGHT), new Point(44, 0));
points.put(new Alignment(BASELINE, XORIGIN), new Point(0, 0));
}
}
| jlpoolen/libreveris | src/test/omr/ui/symbol/AlignmentTest.java | Java | lgpl-3.0 | 5,699 | [
30522,
1013,
1013,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package com.ash6390.jarcraft.utility;
import com.ash6390.jarcraft.reference.References;
import cpw.mods.fml.common.FMLLog;
import org.apache.logging.log4j.Level;
public class LogHelper
{
public static void log(Level logLevel, Object object)
{
FMLLog.log(References.NAME, logLevel, String.valueOf(object));
}
public static void all(Object object) { log(Level.ALL, object); }
public static void debug(Object object) { log(Level.DEBUG, object); }
public static void error(Object object) { log(Level.ERROR, object); }
public static void fatal(Object object) { log(Level.FATAL, object); }
public static void info(Object object) { log(Level.INFO, object); }
public static void off(Object object) { log(Level.OFF, object); }
public static void trace(Object object) { log(Level.TRACE, object); }
public static void warn(Object object) { log(Level.WARN, object); }
}
| Ash6390/JarCraft | src/main/java/com/ash6390/jarcraft/utility/LogHelper.java | Java | lgpl-3.0 | 920 | [
30522,
7427,
4012,
1012,
6683,
2575,
23499,
2692,
1012,
15723,
10419,
1012,
9710,
1025,
12324,
4012,
1012,
6683,
2575,
23499,
2692,
1012,
15723,
10419,
1012,
4431,
1012,
7604,
1025,
12324,
18133,
2860,
1012,
16913,
2015,
1012,
4718,
2140,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package ch.cyberduck.binding.application;
/*
* Copyright (c) 2002-2009 David Kocher. All rights reserved.
*
* http://cyberduck.ch/
*
* 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.
*
* Bug fixes, suggestions and comments should be sent to:
* dkocher@cyberduck.ch
*/
import org.rococoa.Selector;
/// <i>native declaration : /System/Library/Frameworks/AppKit.framework/Headers/NSUserInterfaceValidation.h:69</i>
public interface NSValidatedUserInterfaceItem {
/**
* Original signature : <code>action()</code><br>
* <i>native declaration : /System/Library/Frameworks/AppKit.framework/Headers/NSUserInterfaceValidation.h:70</i>
*/
Selector action();
/**
* Original signature : <code>NSInteger tag()</code><br>
* <i>native declaration : /System/Library/Frameworks/AppKit.framework/Headers/NSUserInterfaceValidation.h:71</i>
*/
int tag();
}
| iterate-ch/cyberduck | binding/src/main/java/ch/cyberduck/binding/application/NSValidatedUserInterfaceItem.java | Java | gpl-3.0 | 1,346 | [
30522,
7427,
10381,
1012,
16941,
8566,
3600,
1012,
8031,
1012,
4646,
1025,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
2526,
1011,
2268,
2585,
15259,
2121,
1012,
2035,
2916,
9235,
1012,
1008,
1008,
8299,
1024,
1013,
1013,
16941,
8566,
3600,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# unibot-matka
Matka plugin for UniBot.
| tarlepp/unibot-matka | README.md | Markdown | mit | 40 | [
30522,
1001,
4895,
12322,
4140,
1011,
13523,
2912,
13523,
2912,
13354,
2378,
2005,
4895,
12322,
4140,
1012,
102,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* For JavaDocs.
*@author dgagarsky
*@since 01.12.2016
*/
package ru.job4j; | degauhta/dgagarsky | chapter_001/src/test/java/ru/job4j/package-info.java | Java | apache-2.0 | 81 | [
30522,
1013,
1008,
1008,
1008,
2005,
9262,
3527,
6169,
1012,
1008,
1030,
3166,
1040,
3654,
6843,
5874,
1008,
1030,
2144,
5890,
1012,
2260,
1012,
2355,
1008,
1013,
7427,
21766,
1012,
3105,
2549,
3501,
1025,
102,
0,
0,
0,
0,
0,
0,
0,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
!=====================================================================!
!
!=====================================================================!
! http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Hashtable.java#Hashtable
module hashtable_class
use iso_fortran_env, only : dp => REAL64
use object_class, only : object
implicit none
private
public :: hashtable
type, extends(object) :: hashtable
class(object), allocatable, dimension(:) :: table ! table of values
type(integer) :: count ! number of keys
type(integer) :: threshold ! threshold for rehashing
type(integer) :: load_factor ! factor to increase the size
type(integer) :: mod_count ! number of rehashings happened since creation
contains
! overridden print method
procedure :: print
!procedure :: rehash
end type hashtable
! Constructor
interface hashtable
module procedure create_hashtable
end interface hashtable
contains
type(hashtable) function create_hashtable(initial_capacity, load_factor) &
& result(this)
type(integer) , intent(in) :: initial_capacity
type(real(dp)), intent(in) :: load_factor
! Sanity check in the initial capacity of hashtable
if (initial_capacity .le. 0) then
print *, "Invalid initial capacity", initial_capacity
stop
end if
! Sanity check on the load factor
if (load_factor .le. 0 .or. load_factor .ne. load_factor) then
print *, "Invalid load factor", load_factor
stop
end if
! Store the values into the object
this % load_factor = load_factor
this % threshold = int(initial_capacity*load_factor)
! Allocate space for entries
!allocate( this % table (initial_capacity) )
! Set the number of entries
this % count = size(this % table)
! Zero the number of size modifications so far (rehashing)
this % mod_count = 0
end function create_hashtable
subroutine print(this)
class(hashtable), intent(in) :: this
print *, "hashtable@ ", this % hashcode()
print *, " count: ", this % count
print *, " threshold: ", this % threshold
print *, " load_factor: ", this % load_factor
print *, " mod_count: ", this % mod_count
end subroutine print
end module hashtable_class
| komahanb/collections | hashtable_class.f90 | FORTRAN | mit | 2,402 | [
30522,
999,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/usr/bin/env python
import sys
from collections import namedtuple
import poppler
import cairo
from os.path import abspath
Point = namedtuple('Point', ['x', 'y'])
Line = namedtuple('Line', ['start', 'end'])
Polygon = namedtuple('Polygon', 'points')
Rectangle = namedtuple('Rectangle', ['top_left', 'bottom_right'])
AnnotationGroup = namedtuple('AnnotationGroup', ['name', 'color', 'shapes'])
Color = namedtuple('Color', ['red', 'green', 'blue'])
__all__ = [
'render_page',
'make_annotations',
]
def draw_line(context, line):
context.move_to(line.start.x, line.start.y)
context.line_to(line.end.x, line.end.y)
context.stroke()
def draw_polygon(context, polygon):
if len(polygon.points) == 0:
return
first_point = polygon.points[0]
context.move_to(first_point.x, first_point.y)
for line in polygon.points[1:]:
context.line_to(line.x, line.y)
context.stroke()
def draw_rectangle(context, rectangle):
width = abs(rectangle.bottom_right.x - rectangle.top_left.x)
height = abs(rectangle.bottom_right.y - rectangle.top_left.y)
context.rectangle(rectangle.top_left.x,
rectangle.top_left.y,
width,
height)
context.stroke()
RENDERERS = {}
RENDERERS[Line] = draw_line
RENDERERS[Rectangle] = draw_rectangle
RENDERERS[Polygon] = draw_polygon
class CairoPdfPageRenderer(object):
def __init__(self, pdf_page, svg_filename, png_filename):
self._svg_filename = abspath(svg_filename)
self._png_filename = abspath(png_filename) if png_filename else None
self._context, self._surface = self._get_context(
svg_filename, *pdf_page.get_size())
white = poppler.Color()
white.red = white.green = white.blue = 65535
black = poppler.Color()
black.red = black.green = black.blue = 0
# red = poppler.Color()
# red.red = red.green = red.blue = 0
# red.red = 65535
width = pdf_page.get_size()[0]
# We render everything 3 times, moving
# one page-width to the right each time.
self._offset_colors = [
(0, white, white, True),
(width, black, white, True),
(2 * width, black, black, False)
]
for offset, fg_color, bg_color, render_graphics in self._offset_colors:
# Render into context, with a different offset
# each time.
self._context.save()
self._context.translate(offset, 0)
sel = poppler.Rectangle()
sel.x1, sel.y1 = (0, 0)
sel.x2, sel.y2 = pdf_page.get_size()
if render_graphics:
pdf_page.render(self._context)
pdf_page.render_selection(
self._context, sel, sel, poppler.SELECTION_GLYPH,
fg_color, bg_color)
self._context.restore()
@staticmethod
def _get_context(filename, width, height):
SCALE = 1
# left, middle, right
N_RENDERINGS = 3
surface = cairo.SVGSurface(
filename, N_RENDERINGS * width * SCALE, height * SCALE)
# srf = cairo.ImageSurface(
# cairo.FORMAT_RGB24, int(w*SCALE), int(h*SCALE))
context = cairo.Context(surface)
context.scale(SCALE, SCALE)
# Set background color to white
context.set_source_rgb(1, 1, 1)
context.paint()
return context, surface
def draw(self, shape, color):
self._context.save()
self._context.set_line_width(1)
self._context.set_source_rgba(color.red,
color.green,
color.blue,
0.5)
self._context.translate(self._offset_colors[1][0], 0)
RENDERERS[type(shape)](self._context, shape)
self._context.restore()
def flush(self):
if self._png_filename is not None:
self._surface.write_to_png(self._png_filename)
# NOTE! The flush is rather expensive, since it writes out the svg
# data. The profile will show a large amount of time spent inside it.
# Removing it won't help the execution time at all, it will just move
# it somewhere that the profiler can't see it
# (at garbage collection time)
self._surface.flush()
self._surface.finish()
def render_page(pdf_filename, page_number, annotations, svg_file=None,
png_file=None):
"""
Render a single page of a pdf with graphical annotations added.
"""
page = extract_pdf_page(pdf_filename, page_number)
renderer = CairoPdfPageRenderer(page, svg_file, png_file)
for annotation in annotations:
assert isinstance(annotation, AnnotationGroup), (
"annotations: {0}, annotation: {1}".format(
annotations, annotation))
for shape in annotation.shapes:
renderer.draw(shape, annotation.color)
renderer.flush()
def extract_pdf_page(filename, page_number):
file_uri = "file://{0}".format(abspath(filename))
doc = poppler.document_new_from_file(file_uri, "")
page = doc.get_page(page_number)
return page
def make_annotations(table_container):
"""
Take the output of the table-finding algorithm (TableFinder) and create
AnnotationGroups. These can be drawn on top of the original PDF page to
visualise how the algorithm arrived at its output.
"""
annotations = []
annotations.append(
AnnotationGroup(
name='all_glyphs',
color=Color(0, 1, 0),
shapes=convert_rectangles(table_container.all_glyphs)))
annotations.append(
AnnotationGroup(
name='all_words',
color=Color(0, 0, 1),
shapes=convert_rectangles(table_container.all_words)))
annotations.append(
AnnotationGroup(
name='text_barycenters',
color=Color(0, 0, 1),
shapes=convert_barycenters(table_container.all_glyphs)))
annotations.append(
AnnotationGroup(
name='hat_graph_vertical',
color=Color(0, 1, 0),
shapes=make_hat_graph(
table_container._y_point_values,
table_container._center_lines,
direction="vertical")))
for table in table_container:
annotations.append(
AnnotationGroup(
name='row_edges',
color=Color(1, 0, 0),
shapes=convert_horizontal_lines(
table.row_edges, table.bounding_box)))
annotations.append(
AnnotationGroup(
name='column_edges',
color=Color(1, 0, 0),
shapes=convert_vertical_lines(
table.column_edges, table.bounding_box)))
annotations.append(
AnnotationGroup(
name='glyph_histogram_horizontal',
color=Color(1, 0, 0),
shapes=make_glyph_histogram(
table._x_glyph_histogram, table.bounding_box,
direction="horizontal")))
annotations.append(
AnnotationGroup(
name='glyph_histogram_vertical',
color=Color(1, 0, 0),
shapes=make_glyph_histogram(
table._y_glyph_histogram, table.bounding_box,
direction="vertical")))
annotations.append(
AnnotationGroup(
name='horizontal_glyph_above_threshold',
color=Color(0, 0, 0),
shapes=make_thresholds(
table._x_threshold_segs, table.bounding_box,
direction="horizontal")))
annotations.append(
AnnotationGroup(
name='vertical_glyph_above_threshold',
color=Color(0, 0, 0),
shapes=make_thresholds(
table._y_threshold_segs, table.bounding_box,
direction="vertical")))
# Draw bounding boxes last so that they appear on top
annotations.append(
AnnotationGroup(
name='table_bounding_boxes',
color=Color(0, 0, 1),
shapes=convert_rectangles(table_container.bounding_boxes)))
return annotations
def make_thresholds(segments, box, direction):
lines = []
for segment in segments:
if direction == "horizontal":
lines.append(Line(Point(segment.start, box.bottom + 10),
Point(segment.end, box.bottom + 10)))
else:
lines.append(Line(Point(10, segment.start),
Point(10, segment.end)))
return lines
def make_hat_graph(hats, center_lines, direction):
"""
Draw estimated text barycenter
"""
max_value = max(v for _, v in hats)
DISPLAY_WIDTH = 25
points = []
polygon = Polygon(points)
def point(x, y):
points.append(Point(x, y))
for position, value in hats:
point(((value / max_value - 1) * DISPLAY_WIDTH), position)
lines = []
for position in center_lines:
lines.append(Line(Point(-DISPLAY_WIDTH, position),
Point(0, position)))
return [polygon] + lines
def make_glyph_histogram(histogram, box, direction):
# if direction == "vertical":
# return []
bin_edges, bin_values = histogram
if not bin_edges:
# There are no glyphs, and nothing to render!
return []
points = []
polygon = Polygon(points)
def point(x, y):
points.append(Point(x, y))
# def line(*args):
# lines.append(Line(*args))
previous_value = 0 if direction == "horizontal" else box.bottom
x = zip(bin_edges, bin_values)
for edge, value in x:
if direction == "horizontal":
value *= 0.75
value = box.bottom - value
point(edge, previous_value)
point(edge, value)
else:
value *= 0.25
value += 7 # shift pixels to the right
point(previous_value, edge)
point(value, edge)
previous_value = value
# Final point is at 0
if direction == "horizontal":
point(edge, 0)
else:
point(box.bottom, edge)
# Draw edge density plot (not terribly interesting, should probably be
# deleted)
# lines = []
# if direction == "horizontal":
# for edge in bin_edges:
# lines.append(Line(Point(edge, box.bottom),
# Point(edge, box.bottom + 5)))
# else:
# for edge in bin_edges:
# lines.append(Line(Point(0, edge), Point(5, edge)))
return [polygon] # + lines
def convert_rectangles(boxes):
return [Rectangle(Point(b.left, b.top), Point(b.right, b.bottom))
for b in boxes]
def convert_barycenters(boxes):
return [Line(Point(b.left, b.barycenter.midpoint),
Point(b.right, b.barycenter.midpoint))
for b in boxes if b.barycenter is not None]
def convert_horizontal_lines(y_edges, bbox):
return [Line(Point(bbox.left, y), Point(bbox.right, y))
for y in y_edges]
def convert_vertical_lines(x_edges, bbox):
return [Line(Point(x, bbox.top), Point(x, bbox.bottom))
for x in x_edges]
if __name__ == '__main__':
annotations = [
AnnotationGroup(
name='',
color=Color(1, 0, 0),
shapes=[Rectangle(Point(100, 100), Point(200, 200))])
]
render_page(sys.argv[1], 0, annotations)
| drj11/pdftables | pdftables/diagnostics.py | Python | bsd-2-clause | 11,691 | [
30522,
1001,
999,
1013,
2149,
2099,
1013,
8026,
1013,
4372,
2615,
18750,
12324,
25353,
2015,
2013,
6407,
12324,
2315,
8525,
10814,
12324,
3769,
10814,
2099,
12324,
11096,
2013,
9808,
1012,
4130,
12324,
14689,
15069,
2391,
1027,
2315,
8525,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/usr/bin/env python
from distutils.core import setup
from dangagearman import __version__ as version
setup(
name = 'danga-gearman',
version = version,
description = 'Client for the Danga (Perl) Gearman implementation',
author = 'Samuel Stauffer',
author_email = 'samuel@descolada.com',
url = 'http://github.com/saymedia/python-danga-gearman/tree/master',
packages = ['dangagearman'],
classifiers = [
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| saymedia/python-danga-gearman | setup.py | Python | mit | 699 | [
30522,
1001,
999,
1013,
2149,
2099,
1013,
8026,
1013,
4372,
2615,
18750,
2013,
4487,
3367,
21823,
4877,
1012,
4563,
12324,
16437,
2013,
4907,
3654,
3351,
27292,
2319,
12324,
1035,
1035,
2544,
1035,
1035,
2004,
2544,
16437,
1006,
2171,
1027,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CC.Common.Compression.Demo.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| CanyonCounty/CC.Common.Compression | CC.Common.Compression.Demo/Properties/Settings.Designer.cs | C# | gpl-2.0 | 1,061 | [
30522,
1013,
1013,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import {Component, OnInit} from 'angular2/core';
import {HatenaRssFeed, HatenaRssFeedService} from './HatenaRssFeed.service';
@Component({
selector: 'hatena-rss-feed',
templateUrl: '/app/template/hatena-rss-feed.html'
})
export class HatenaRssFeedComponent implements OnInit {
private hatenaRssFeeds: HatenaRssFeed[]
private newHatenaRssFeed: HatenaRssFeed
private errorMessage: string
private waitingResponse: boolean
constructor(private _hatenaRssItemService: HatenaRssFeedService) {
this.errorMessage = ""
}
ngOnInit() {
this.newHatenaRssFeed = {
Title : "",
URL : "",
BookmarkCountThreshold : 0
}
this.refresh()
}
isValidNewFeed(): boolean {
return this.newHatenaRssFeed.URL.length > 0 && (this.hatenaRssFeeds.findIndex(v => { return v.URL == this.newHatenaRssFeed.URL }) == -1) && this.newHatenaRssFeed.Title.length > 0
}
add() {
if(this.newHatenaRssFeed.URL == "") {
return
}
this.waitingResponse = true
this._hatenaRssItemService.post(this.newHatenaRssFeed).subscribe(
resp => {
this.hatenaRssFeeds = this.hatenaRssFeeds.concat(this.newHatenaRssFeed)
this.newHatenaRssFeed.URL = ""
this.newHatenaRssFeed.Title = ""
this.newHatenaRssFeed.BookmarkCountThreshold = 0
},
error => {
this.errorMessage = <string>error
this.waitingResponse = false
}
)
}
delete(url:string) {
this._hatenaRssItemService.delete(url).subscribe(
resp => {
this.hatenaRssFeeds = this.hatenaRssFeeds.filter((val, i, arr) => { return val.URL != url })
},
error => {
this.errorMessage = <string>error
this.waitingResponse = false
}
)
}
refresh() {
this.waitingResponse = true
this._hatenaRssItemService.get().subscribe(
items => {
this.hatenaRssFeeds = items
this.waitingResponse = false
},
error => {
this.errorMessage = <string>error
this.waitingResponse = false
}
);
}
} | tkyjhr/go-newstweeter | src/frontend/app/HatenaRssFeed.component.ts | TypeScript | mit | 2,465 | [
30522,
12324,
1063,
6922,
1010,
2006,
5498,
2102,
1065,
2013,
1005,
16108,
2475,
1013,
4563,
1005,
1025,
12324,
1063,
5223,
11802,
4757,
7959,
2098,
1010,
5223,
11802,
4757,
7959,
2098,
8043,
7903,
2063,
1065,
2013,
1005,
1012,
1013,
5223,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* * Copyright (c) 2014, 2015 Zhang Xianyi
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/
#include <stdlib.h>
#include <math.h>
#include <openvml_reference.h>
void OpenVML_FUNCNAME_REF(vsExp)(const VML_INT n, const float * a, float * y){
VML_INT i;
if (n<=0) return;
if (a==NULL || y==NULL) return;
for(i=0; i<n; i++){
y[i]=expf(a[i]);
}
}
void OpenVML_FUNCNAME_REF(vdExp)(const VML_INT n, const double * a, double * y){
VML_INT i;
if (n<=0) return;
if (a==NULL || y==NULL) return;
for(i=0; i<n; i++){
y[i]=exp(a[i]);
}
}
| liyancas/OpenVML | reference/vexp.c | C | bsd-2-clause | 1,885 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
2297,
1010,
2325,
9327,
8418,
19092,
2072,
1008,
2035,
2916,
9235,
1012,
1008,
1008,
25707,
1998,
2224,
1999,
3120,
1998,
12441,
3596,
1010,
2007,
2030,
2302,
14080,
1010,
1008,
2024,
7936,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2015 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$languages = '';
if ($handle = opendir('./languages/')) {
while (false !== ($file = readdir($handle))) {
if (is_dir('./languages/' . $file) && $file != ".." && $file != "." && $file != ".svn") {
$languages .= '<a href="index.php?lang=' . $file . '"><img src="../images/languages/' . $file . '.gif"
alt="' . $file . '"></a>';
}
}
closedir($handle);
}
?>
<tr>
<td id="step" align="center" colspan="2">
<span class="steps start" id="active"><?php echo $_language->module['step0']; ?></span>
<span class="steps"><?php echo $_language->module['step1']; ?></span>
<span class="steps"><?php echo $_language->module['step2']; ?></span>
<span class="steps"><?php echo $_language->module['step3']; ?></span>
<span class="steps"><?php echo $_language->module['step4']; ?></span>
<span class="steps"><?php echo $_language->module['step5']; ?></span>
<span class="steps end"><?php echo $_language->module['step6']; ?></span>
</td>
</tr>
<tr id="headline">
<td id="title" colspan="2"><?php echo $_language->module['welcome']; ?></td>
</tr>
<tr>
<td id="content" colspan="2">
<b><?php echo $_language->module['welcome_to']; ?></b><br><br>
<b><?php echo $_language->module['select_a_language']; ?>:</b> <span
class="padding"><?php echo $languages; ?></span><br><br>
<?php echo $_language->module['welcome_text']; ?>
<br><br><br>
<?php echo $_language->module['webspell_team']; ?><br>
- <a href="http://www.webspell.org" target="_blank">www.webspell.org</a>
<div align="right"><br><a href="javascript:document.ws_install.submit()"><img src="images/next.jpg" alt=""></a>
</div>
</td>
</tr>
| nerdiabet/webSPELL | install/step0.php | PHP | gpl-3.0 | 3,517 | [
30522,
1026,
1029,
25718,
1013,
1008,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
1001,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* common.h
* CHRONICLES PHYSICS ENGINE
* by Greg Tourville
* Copyright (c) 2007
* Tuesday Jan 23 -
* All Rights Reserved.
**/
#ifndef _PHYSICS_COMMON_H
#define _PHYSICS_COMMON_H
#ifndef RADS
# define RADS (0.017453f)
#endif
#define DEGS (57.29578f)
#ifndef PI
# define PI (3.141593f)
#endif
#define HALF_PI (1.570796f)
#ifndef ROOT_TWO
# define ROOT_TWO (1.414214f)
#endif
struct SPoint;
struct SVector;
struct SBox;
SPoint ClosestPointOnLineSegment( SPoint* line1, SPoint* line2, SPoint* point );
float atan( SPoint* );
float atan( SVector* );
struct SPoint
{
SPoint();
SPoint( float, float );
float x, y;
void Set( float x, float y );
void Translate( SVector* v );
void Difference( SPoint* p2, SVector* ret );
void Add( SPoint* p );
void Copy( SPoint* dest );
};
struct SVector
{
SVector();
SVector( float, float );
float x, y;
void Set( float, float );
void Copy( SVector* ret );
void Flip();
void Add( SVector* v );
void Subtract( SVector* v );
float Length(); // Real Length
float LengthSquared(); // Length without sqrt()
float SquareLength(); // Fast Cartesian Length
void Scale( float s, SVector* ret );
void Scale( float s );
void Normalize();
float DotProduct( SVector* );
void Rotate( float deg );
};
struct SBox
{
SBox();
SBox( SPoint*, SPoint* );
bool IntersectsWithBox( SBox* box );
bool IntersectsWithBoxX( SBox* box );
bool IntersectsWithBoxY( SBox* box );
void FindBoxFromPoints( SPoint* p1, SPoint* p2 );
SPoint position;
SPoint size;
};
#endif
| gregtour/chronicles-game | src/engine/physics/common.h | C | cc0-1.0 | 1,633 | [
30522,
1013,
1008,
1008,
1008,
2691,
1012,
1044,
1008,
11906,
5584,
3194,
1008,
2011,
6754,
2778,
3077,
1008,
9385,
1006,
1039,
1007,
2289,
1008,
9857,
5553,
2603,
1011,
1008,
2035,
2916,
9235,
1012,
1008,
1008,
1013,
1001,
2065,
13629,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* SPDX-License-Identifier: GPL-2.0+ */
/*
* Configuation settings for the Renesas Technology R0P7785LC0011RL board
*
* Copyright (C) 2008 Yoshihiro Shimoda <shimoda.yoshihiro@renesas.com>
*/
#ifndef __SH7785LCR_H
#define __SH7785LCR_H
#define CONFIG_CPU_SH7785 1
#define CONFIG_EXTRA_ENV_SETTINGS \
"bootdevice=0:1\0" \
"usbload=usb reset;usbboot;usb stop;bootm\0"
#define CONFIG_DISPLAY_BOARDINFO
#undef CONFIG_SHOW_BOOT_PROGRESS
/* MEMORY */
#if defined(CONFIG_SH_32BIT)
/* 0x40000000 - 0x47FFFFFF does not use */
#define CONFIG_SH_SDRAM_OFFSET (0x8000000)
#define SH7785LCR_SDRAM_PHYS_BASE (0x40000000 + CONFIG_SH_SDRAM_OFFSET)
#define SH7785LCR_SDRAM_BASE (0x80000000 + CONFIG_SH_SDRAM_OFFSET)
#define SH7785LCR_SDRAM_SIZE (384 * 1024 * 1024)
#define SH7785LCR_FLASH_BASE_1 (0xa0000000)
#define SH7785LCR_FLASH_BANK_SIZE (64 * 1024 * 1024)
#define SH7785LCR_USB_BASE (0xa6000000)
#else
#define SH7785LCR_SDRAM_BASE (0x08000000)
#define SH7785LCR_SDRAM_SIZE (128 * 1024 * 1024)
#define SH7785LCR_FLASH_BASE_1 (0xa0000000)
#define SH7785LCR_FLASH_BANK_SIZE (64 * 1024 * 1024)
#define SH7785LCR_USB_BASE (0xb4000000)
#endif
#define CONFIG_SYS_PBSIZE 256
#define CONFIG_SYS_BAUDRATE_TABLE { 115200 }
/* SCIF */
#define CONFIG_CONS_SCIF1 1
#define CONFIG_SCIF_EXT_CLOCK 1
#define CONFIG_SYS_MEMTEST_START (SH7785LCR_SDRAM_BASE)
#define CONFIG_SYS_MEMTEST_END (CONFIG_SYS_MEMTEST_START + \
(SH7785LCR_SDRAM_SIZE) - \
4 * 1024 * 1024)
#undef CONFIG_SYS_MEMTEST_SCRATCH
#undef CONFIG_SYS_LOADS_BAUD_CHANGE
#define CONFIG_SYS_SDRAM_BASE (SH7785LCR_SDRAM_BASE)
#define CONFIG_SYS_SDRAM_SIZE (SH7785LCR_SDRAM_SIZE)
#define CONFIG_SYS_LOAD_ADDR (CONFIG_SYS_SDRAM_BASE + 16 * 1024 * 1024)
#define CONFIG_SYS_MONITOR_BASE (SH7785LCR_FLASH_BASE_1)
#define CONFIG_SYS_MONITOR_LEN (512 * 1024)
#define CONFIG_SYS_MALLOC_LEN (512 * 1024)
#define CONFIG_SYS_BOOTMAPSZ (8 * 1024 * 1024)
/* FLASH */
#define CONFIG_FLASH_CFI_DRIVER
#define CONFIG_SYS_FLASH_CFI
#undef CONFIG_SYS_FLASH_QUIET_TEST
#define CONFIG_SYS_FLASH_EMPTY_INFO
#define CONFIG_SYS_FLASH_BASE (SH7785LCR_FLASH_BASE_1)
#define CONFIG_SYS_MAX_FLASH_SECT 512
#define CONFIG_SYS_MAX_FLASH_BANKS 1
#define CONFIG_SYS_FLASH_BANKS_LIST { CONFIG_SYS_FLASH_BASE + \
(0 * SH7785LCR_FLASH_BANK_SIZE) }
#define CONFIG_SYS_FLASH_ERASE_TOUT (3 * 1000)
#define CONFIG_SYS_FLASH_WRITE_TOUT (3 * 1000)
#define CONFIG_SYS_FLASH_LOCK_TOUT (3 * 1000)
#define CONFIG_SYS_FLASH_UNLOCK_TOUT (3 * 1000)
#undef CONFIG_SYS_FLASH_PROTECTION
#undef CONFIG_SYS_DIRECT_FLASH_TFTP
/* R8A66597 */
#define CONFIG_USB_R8A66597_HCD
#define CONFIG_R8A66597_BASE_ADDR SH7785LCR_USB_BASE
#define CONFIG_R8A66597_XTAL 0x0000 /* 12MHz */
#define CONFIG_R8A66597_LDRV 0x8000 /* 3.3V */
#define CONFIG_R8A66597_ENDIAN 0x0000 /* little */
/* PCI Controller */
#define CONFIG_SH4_PCI
#define CONFIG_SH7780_PCI
#if defined(CONFIG_SH_32BIT)
#define CONFIG_SH7780_PCI_LSR 0x1ff00001
#define CONFIG_SH7780_PCI_LAR 0x5f000000
#define CONFIG_SH7780_PCI_BAR 0x5f000000
#else
#define CONFIG_SH7780_PCI_LSR 0x07f00001
#define CONFIG_SH7780_PCI_LAR CONFIG_SYS_SDRAM_SIZE
#define CONFIG_SH7780_PCI_BAR CONFIG_SYS_SDRAM_SIZE
#endif
#define CONFIG_PCI_SCAN_SHOW 1
#define CONFIG_PCI_MEM_BUS 0xFD000000 /* Memory space base addr */
#define CONFIG_PCI_MEM_PHYS CONFIG_PCI_MEM_BUS
#define CONFIG_PCI_MEM_SIZE 0x01000000 /* Size of Memory window */
#define CONFIG_PCI_IO_BUS 0xFE200000 /* IO space base address */
#define CONFIG_PCI_IO_PHYS CONFIG_PCI_IO_BUS
#define CONFIG_PCI_IO_SIZE 0x00200000 /* Size of IO window */
#if defined(CONFIG_SH_32BIT)
#define CONFIG_PCI_SYS_PHYS SH7785LCR_SDRAM_PHYS_BASE
#else
#define CONFIG_PCI_SYS_PHYS CONFIG_SYS_SDRAM_BASE
#endif
#define CONFIG_PCI_SYS_BUS CONFIG_SYS_SDRAM_BASE
#define CONFIG_PCI_SYS_SIZE CONFIG_SYS_SDRAM_SIZE
/* ENV setting */
#define CONFIG_ENV_OVERWRITE 1
#define CONFIG_ENV_SECT_SIZE (256 * 1024)
#define CONFIG_ENV_SIZE (CONFIG_ENV_SECT_SIZE)
#define CONFIG_ENV_ADDR (CONFIG_SYS_FLASH_BASE + CONFIG_SYS_MONITOR_LEN)
#define CONFIG_ENV_OFFSET (CONFIG_ENV_ADDR - CONFIG_SYS_FLASH_BASE)
#define CONFIG_ENV_SIZE_REDUND (CONFIG_ENV_SECT_SIZE)
/* Board Clock */
/* The SCIF used external clock. system clock only used timer. */
#define CONFIG_SYS_CLK_FREQ 50000000
#define CONFIG_SH_TMU_CLK_FREQ CONFIG_SYS_CLK_FREQ
#define CONFIG_SH_SCIF_CLK_FREQ CONFIG_SYS_CLK_FREQ
#define CONFIG_SYS_TMU_CLK_DIV 4
#endif /* __SH7785LCR_H */
| ev3dev/u-boot | include/configs/sh7785lcr.h | C | gpl-2.0 | 4,450 | [
30522,
1013,
1008,
23772,
2595,
1011,
6105,
1011,
8909,
4765,
18095,
1024,
14246,
2140,
1011,
1016,
1012,
1014,
1009,
1008,
1013,
1013,
1008,
1008,
9530,
8873,
19696,
3508,
10906,
2005,
1996,
10731,
20939,
2974,
1054,
2692,
2361,
2581,
2581... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
module TasksFileMutations
AddFilesToTask = GraphQL::Relay::Mutation.define do
name 'AddFilesToTask'
input_field :id, !types.ID
return_field :task, TaskType
resolve -> (_root, inputs, ctx) {
task = GraphqlCrudOperations.object_from_id_if_can(inputs['id'], ctx['ability'])
files = [ctx[:file]].flatten.reject{ |f| f.blank? }
if task.is_a?(Task) && !files.empty?
task.add_files(files)
end
{ task: task }
}
end
RemoveFilesFromTask = GraphQL::Relay::Mutation.define do
name 'RemoveFilesFromTask'
input_field :id, !types.ID
input_field :filenames, types[types.String]
return_field :task, TaskType
resolve -> (_root, inputs, ctx) {
task = GraphqlCrudOperations.object_from_id_if_can(inputs['id'], ctx['ability'])
filenames = inputs['filenames']
if task.is_a?(Task) && !filenames.empty?
task.remove_files(filenames)
end
{ task: task }
}
end
end
| meedan/check-api | app/graph/mutations/tasks_file_mutations.rb | Ruby | mit | 972 | [
30522,
11336,
8518,
8873,
16930,
26117,
2015,
5587,
8873,
4244,
3406,
10230,
2243,
1027,
10629,
4160,
2140,
1024,
1024,
8846,
1024,
1024,
16221,
1012,
9375,
2079,
2171,
1005,
5587,
8873,
4244,
3406,
10230,
2243,
1005,
7953,
1035,
2492,
1024... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>0.9.9 API documenation: wrap.hpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="logo-mini.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">0.9.9 API documenation
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_934f46a345653ef2b3014a1b37a162c1.html">G:</a></li><li class="navelem"><a class="el" href="dir_98f7f9d41f9d3029bd68cf237526a774.html">Source</a></li><li class="navelem"><a class="el" href="dir_9344afb825aed5e2f5be1d2015dde43c.html">G-Truc</a></li><li class="navelem"><a class="el" href="dir_45973f864e07b2505003ae343b7c8af7.html">glm</a></li><li class="navelem"><a class="el" href="dir_304be5dfae1339a7705426c0b536faf2.html">glm</a></li><li class="navelem"><a class="el" href="dir_e8f3c1046ba4b357711397765359cd18.html">gtx</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">wrap.hpp File Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><a class="el" href="a00236.html">GLM_GTX_wrap</a>
<a href="#details">More...</a></p>
<p><a href="a00139_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:ga6c0cc6bd1d67ea1008d2592e998bad33"><td class="memTemplParams" colspan="2">template<typename genType > </td></tr>
<tr class="memitem:ga6c0cc6bd1d67ea1008d2592e998bad33"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00236.html#ga6c0cc6bd1d67ea1008d2592e998bad33">clamp</a> (genType const &Texcoord)</td></tr>
<tr class="memdesc:ga6c0cc6bd1d67ea1008d2592e998bad33"><td class="mdescLeft"> </td><td class="mdescRight">Simulate GL_CLAMP OpenGL wrap mode. <a href="a00236.html#ga6c0cc6bd1d67ea1008d2592e998bad33">More...</a><br /></td></tr>
<tr class="separator:ga6c0cc6bd1d67ea1008d2592e998bad33"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:gaa6856a0a048d2749252848da35e10c8b"><td class="memTemplParams" colspan="2">template<typename genType > </td></tr>
<tr class="memitem:gaa6856a0a048d2749252848da35e10c8b"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00236.html#gaa6856a0a048d2749252848da35e10c8b">mirrorClamp</a> (genType const &Texcoord)</td></tr>
<tr class="memdesc:gaa6856a0a048d2749252848da35e10c8b"><td class="mdescLeft"> </td><td class="mdescRight">Simulate GL_MIRRORED_REPEAT OpenGL wrap mode. <a href="a00236.html#gaa6856a0a048d2749252848da35e10c8b">More...</a><br /></td></tr>
<tr class="separator:gaa6856a0a048d2749252848da35e10c8b"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga16a89b0661b60d5bea85137bbae74d73"><td class="memTemplParams" colspan="2">template<typename genType > </td></tr>
<tr class="memitem:ga16a89b0661b60d5bea85137bbae74d73"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00236.html#ga16a89b0661b60d5bea85137bbae74d73">mirrorRepeat</a> (genType const &Texcoord)</td></tr>
<tr class="memdesc:ga16a89b0661b60d5bea85137bbae74d73"><td class="mdescLeft"> </td><td class="mdescRight">Simulate GL_MIRROR_REPEAT OpenGL wrap mode. <a href="a00236.html#ga16a89b0661b60d5bea85137bbae74d73">More...</a><br /></td></tr>
<tr class="separator:ga16a89b0661b60d5bea85137bbae74d73"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga809650c6310ea7c42666e918c117fb6f"><td class="memTemplParams" colspan="2">template<typename genType > </td></tr>
<tr class="memitem:ga809650c6310ea7c42666e918c117fb6f"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00236.html#ga809650c6310ea7c42666e918c117fb6f">repeat</a> (genType const &Texcoord)</td></tr>
<tr class="memdesc:ga809650c6310ea7c42666e918c117fb6f"><td class="mdescLeft"> </td><td class="mdescRight">Simulate GL_REPEAT OpenGL wrap mode. <a href="a00236.html#ga809650c6310ea7c42666e918c117fb6f">More...</a><br /></td></tr>
<tr class="separator:ga809650c6310ea7c42666e918c117fb6f"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p><a class="el" href="a00236.html">GLM_GTX_wrap</a> </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00155.html" title="The core of GLM, which implements exactly and only the GLSL specification to the degree possible...">GLM Core</a> (dependence) </dd></dl>
<p>Definition in file <a class="el" href="a00139_source.html">wrap.hpp</a>.</p>
</div></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.10
</small></address>
</body>
</html>
| sTorro/CViewGL | extern/glm-0.9.7.1/doc/api/a00139.html | HTML | gpl-3.0 | 8,350 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
1060,
11039,
19968,
1015,
1012,
1014,
17459,
1013,
1013,
4372,
1000,
1000,
8299,
1024,
1013,
1013,
7479,
1012,
1059,
2509,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
'use strict';
//debugger;
//pageSetUp();
var soProfiling;
var soProfileInstance = function() {
soProfiling = new soProfilingObject();
soProfiling.Load();
};
var soProfilingObject = function() {
var THIS = this;
var numberFormat = d3.format(",f");
THIS.type = "materialCount";
//constructTabs(THIS);
this.Load = function(obj) {
//enableLoading();
var source = $(obj).data("source");
THIS.source = source || $("#myTab").find("li.active").data("source");
var request = {
"source" : THIS.source,
"viewType" : "default"
};
drawChart();
/*callAjaxService("JiraProfile", callbackSuccessSOProfile, callBackFailure,
request, "POST");*/
};
this.loadViewType = function(viewType) {
//enableLoading();
THIS.type = viewType;
setTimeout(function() {
drawChart();
//disableLoading();
}, 50);
};
var callbackSuccessSOProfile = function(data) {
/*
* private String soCount; a private String companyCode; b private
* String companyName; c private String salesOrg; d private String
* salesOrgName; e private String salesGroup; f private String
* salesGroupName; g private String division; h private String
* divisionName; i private String salesDocType; j private String
* plantGroup; k private String plantName; l private String netValue; m
* private String source; n private String region; o private String
* lastChanged; p private String materialType; q private String soType;
* r
*/
//disableLoading();
if (data && data.isException){
showNotification("error",data.customMessage);
return;
}
if (data != undefined && data != null
&& data["aggregatedSalesOrderList"] != undefined
&& data["aggregatedSalesOrderList"] != null && data["aggregatedSalesOrderList"].length > 0) {
THIS.data = data["aggregatedSalesOrderList"];
drawChart();
}
};
var drawChart = function() {
d3.csv("data/jiraData.csv", function(error, experiments) {
console.log(experiments);
experiments.forEach(function(x) {
x.count = 1;
});
/*var chart = dc.pieChart("#test");*/
var ndx = crossfilter(experiments);
THIS.pieChartIssueType = dc.pieChart("#pie-chart-IssueType");
var pieChartIssueTypeDimension = ndx.dimension(function(d){return d.Issue_Type; });
var pieIssueType = pieChartIssueTypeDimension.group();
THIS.pieChartStatus = dc.pieChart("#pie-chart-Status");
var pieChartStatusDimension = ndx.dimension(function(d){return d.Status; });
var pieStatus = pieChartStatusDimension.group();
THIS.pieChartFixVersions = dc.pieChart("#pie-chart-FixVersions");
var pieChartFixVersionsDimension = ndx.dimension(function(d){return d.FixVersions; });
var pieFixVersions = pieChartFixVersionsDimension.group();
THIS.pieChartPriority = dc.pieChart("#pie-chart-Priority");
var pieChartPriorityDimension = ndx.dimension(function(d){return d.Priority; });
var piePriority = pieChartPriorityDimension.group();
THIS.pieChartResolution = dc.pieChart("#pie-chart-Resolution");
var pieChartResolutionDimension = ndx.dimension(function(d){return d.Resolution; });
var pieResolution = pieChartResolutionDimension.group();
THIS.pieChartComponents = dc.pieChart("#pie-chart-Components");
var pieChartComponentsDimension = ndx.dimension(function(d){return d.Components; });
var pieComponents = pieChartComponentsDimension.group();
THIS.pieChartEpicTheme = dc.pieChart("#pie-chart-EpicTheme");
var pieChartEpicThemeDimension = ndx.dimension(function(d){return d.Epic_theme; });
var pieEpicTheme = pieChartEpicThemeDimension.group();
THIS.rowChartAssignee = dc.pieChart("#row-Chart-Assignee");
var rowChartAssigneeDimension = ndx.dimension(function(d){return d.Assignee; });
var rowAssignee = rowChartAssigneeDimension.group();
THIS.pieChartReporter = dc.pieChart("#pie-chart-Reporter");
var pieChartReporterDimension = ndx.dimension(function(d){return d.Reporter; });
var pieReporter = pieChartReporterDimension.group();
THIS.horzBarChartProject = dc.rowChart("#row-chart-Project");
var barChartProjectDimension = ndx.dimension(function(d){return d.project; });
var barProject = barChartProjectDimension.group();
THIS.horzBarChartProject
.width(250).height(600)
.dimension(barChartProjectDimension)
.group(barProject)
.elasticX(true);
THIS.timelineAreaChart1 = dc.lineChart("#timeline-area-chart1");
var timelineAreaChart1Dimension = ndx.dimension(function(d){return d.TimeSpent; });
var timelineAreaProject = timelineAreaChart1Dimension.group();
THIS.timelineAreaChart1
.width(250).height(300)
.dimension(barChartProjectDimension)
.group(barProject)
.elasticX(true);
THIS.pieChartIssueType.width(170).height(150).radius(60)
.dimension(pieChartIssueTypeDimension)
.group(pieIssueType)
.renderlet(function (chart) {
//console.log(chart.filters());
});;
THIS.pieChartStatus.width(170).height(150).radius(60)
.dimension(pieChartStatusDimension)
.group(pieStatus)
.renderlet(function (chart) {
//console.log(chart.filters());
});;
THIS.pieChartFixVersions.width(170).height(150).radius(60)
.dimension(pieChartFixVersionsDimension)
.group(pieFixVersions)
.renderlet(function (chart) {
//console.log(chart.filters());
});;
THIS.pieChartPriority.width(170).height(150).radius(60).innerRadius(30)
.dimension(pieChartPriorityDimension)
.group(piePriority)
.renderlet(function (chart) {
//console.log(chart.filters());
});;
THIS.pieChartResolution.width(170).height(150).radius(60)
.dimension(pieChartResolutionDimension)
.group(pieResolution)
.renderlet(function (chart) {
//console.log(chart.filters());
});;
THIS.rowChartAssignee
.width(170).height(150).radius(60)
.dimension(rowChartAssigneeDimension)
.group(rowAssignee);
THIS.pieChartComponents.width(170).height(150).radius(60).innerRadius(30)
.dimension(pieChartComponentsDimension)
.group(pieComponents)
.renderlet(function (chart) {
//console.log(chart.filters());
});;
THIS.pieChartEpicTheme.width(170).height(150).radius(60)
.dimension(pieChartEpicThemeDimension)
.group(pieEpicTheme)
.renderlet(function (chart) {
});;
THIS.pieChartReporter
.width(170).height(150).radius(60)
.dimension(pieChartReporterDimension)
.group(pieReporter);
THIS.pieChartIssueType.render();
THIS.pieChartStatus.render();
THIS.pieChartFixVersions.render();
THIS.pieChartPriority.render();
THIS.pieChartResolution.render();
THIS.pieChartComponents.render();
THIS.pieChartEpicTheme.render();
THIS.rowChartAssignee.render();
THIS.horzBarChartProject.render();
THIS.pieChartReporter.render();
});
/*var data = THIS.data;
$("[id^=pie-chart] h4").addClass("hide");
if (THIS.source == "JDE")
$("#pie-chart-SalesGroup .axisLabel").html("Sales Territory");
else
$("#pie-chart-SalesGroup .axisLabel").html("Sales Group");
var dateFormat = d3.time.format("%m/%d/%Y");
data.forEach(function(d) {
d.dd = dateFormat.parse(d.p);
d.month = d3.time.month(d.dd);
d.a = +d.a;
d.m = +d.m;
d.zz = (THIS.type == "netvalue") ? isNaN(d.m) ? 0 : d.m
: isNaN(d.a) ? 0 : d.a;
});
var ndx = crossfilter(data);
var all = ndx.groupAll();
THIS.pieChartCompanyCode = dc.pieChart("#pie-chart-CompanyCode");
var pieChartCompanyCodeDimension = ndx.dimension(function(d) {
return (d.b || "Others") + "-" + (d.c || "Not Available");
});
var pieCompanyCode = pieChartCompanyCodeDimension.group();
if (pieCompanyCode.size() > 1
|| pieCompanyCode.all()[0].key.split("-")[0] != "Others") {
pieCompanyCode = pieCompanyCode.reduceSum(
function(d) {
return d.zz;
});
} else {
$("#pie-chart-CompanyCode h4").removeClass("hide");
pieCompanyCode = pieCompanyCode.reduceSum(
function() {
return 0;
});
}
THIS.pieChartDivision = dc.pieChart("#pie-chart-Division");
var pieChartDivisionDimension = ndx.dimension(function(d) {
return (d.h || "Others") + "-" + (d.i || "Not Available");
});
var pieDivision = pieChartDivisionDimension.group();
if (pieDivision.size() > 1
|| pieDivision.all()[0].key.split("-")[0] != "Others") {
pieDivision = pieDivision.reduceSum(
function(d) {
return d.zz;
});
} else {
$("#pie-chart-Division h4").removeClass("hide");
pieDivision = pieDivision.reduceSum(
function() {
return 0;
});
}
// for orderreason pie - begin
THIS.pieChartOrderReason = dc.pieChart("#pie-chart-OrderReason");
var pieChartOrderReasonDimension = ndx.dimension(function(d) {
return (d.t || "Others") + "-" + (d.u || "Not Available");
});
var pieOrderReason = pieChartOrderReasonDimension.group();
if (pieOrderReason.size() > 1
|| pieOrderReason.all()[0].key.split("-")[0] != "Others") {
pieOrderReason = pieOrderReason.reduceSum(
function(d) {
return d.zz;
});
} else {
$("#pie-chart-OrderReason h4").removeClass("hide");
pieOrderReason = pieOrderReason.reduceSum(
function() {
return 0;
});
}
// for orderreason pie - End
// for ordercategory pie - Start
THIS.pieChartOrderCategory = dc.pieChart("#pie-chart-OrderCategory");
var pieChartOrderCategoryDimension = ndx.dimension(function(d) {
return d.v|| "Others";
});
var pieOrderCategory = pieChartOrderCategoryDimension.group();
if (pieOrderCategory.size() > 1
|| pieOrderCategory.all()[0].key.split("-")[0] != "Others") {
pieOrderCategory = pieOrderCategory.reduceSum(
function(d) {
return d.zz;
});
} else {
$("#pie-chart-OrderCategory h4").removeClass("hide");
pieOrderCategory = pieOrderCategory.reduceSum(
function() {
return 0;
});
}
// for ordercategory pie - End
THIS.pieChartPlant = dc.pieChart("#pie-chart-plant");
var pieChartPlantDimension = ndx.dimension(function(d) {
return (d.k || "Others") + "-" + (d.l || "Not Available");
});
var piePlant = pieChartPlantDimension.group();
if (piePlant.size() > 1
|| piePlant.all()[0].key.split("-")[0] != "Others") {
piePlant = piePlant.reduceSum(function(d) {
return d.zz;
});
}else {
$("#pie-chart-plant h4").removeClass("hide");
piePlant = piePlant.reduceSum(
function() {
return 0;
});
}
THIS.pieChartMaterialType = dc.pieChart("#pie-chart-MaterialType");
var pieChartMaterialTypeDimension = ndx.dimension(function(d) {
return d.q || "Others";
});
var pieMaterialType = null;
if (pieChartMaterialTypeDimension.group().size() > 1
|| pieChartMaterialTypeDimension.group().all()[0].key.split("-")[0] != "Others") {
pieMaterialType = pieChartMaterialTypeDimension.group().reduceSum(
function(d) {
return d.zz;
});
} else{
$("#pie-chart-MaterialType h4").removeClass("hide");
pieMaterialType = pieChartMaterialTypeDimension.group().reduceSum(
function() {
return 0;
});
}
THIS.pieChartSalesDocType = dc.pieChart("#pie-chart-Sales-Doc-Type");
var pieChartSalesDocTypeDimension = ndx.dimension(function(d) {
return (d.j || "Others") + "-" + (d.s || "Not Available");
});
var pieSalesDocType = null;
if (pieChartSalesDocTypeDimension.group().size() > 1
|| pieChartSalesDocTypeDimension.group().all()[0].key.split("-")[0] != "Others") {
pieSalesDocType = pieChartSalesDocTypeDimension.group().reduceSum(
function(d) {
return d.zz;
});
} else {
$("#pie-chart-Sales-Doc-Type h4").removeClass("hide");
pieSalesDocType = pieChartSalesDocTypeDimension.group().reduceSum(
function() {
return 0;
});
}
THIS.pieChartSalesOrg = dc.pieChart("#pie-chart-SalesOrg");
var pieChartSalesOrgpDimension = ndx.dimension(function(d) {
return (d.d || "Others") + "-" + (d.e || "Not Available");
});
var pieSalesOrg = pieChartSalesOrgpDimension.group();
if (pieSalesOrg.size() > 1
|| pieSalesOrg.all()[0].key.split("-")[0] != "Others") {
pieSalesOrg = pieSalesOrg.reduceSum(
function(d) {
return d.zz;
});
} else {
$("#pie-chart-SalesOrg h4").removeClass("hide");
pieSalesOrg = pieSalesOrg.reduceSum(
function() {
return 0;
});
}
THIS.pieChartSalesGroup = dc.pieChart("#pie-chart-SalesGroup");
var pieChartSalesGroupDimension = ndx.dimension(function(d) {
return (d.f || "Others") + "-" + (d.g || "Not Available");
});
var pieSalesGroup = pieChartSalesGroupDimension.group();
if (pieSalesGroup.size() > 1
|| pieSalesGroup.all()[0].key.split("-")[0] != "Others") {
pieSalesGroup = pieSalesGroup.reduceSum(
function(d) {
return d.zz;
});
} else {
$("#pie-chart-SalesGroup h4").removeClass("hide");
pieSalesGroup = pieSalesGroup.reduceSum(
function() {
return 0;
});
}
THIS.horzBarChart = dc.rowChart("#row-chart");
THIS.timelineAreaChart = dc.lineChart("#timeline-area-chart");
THIS.timelineChart = dc.barChart("#timeline-chart");
var timelineDimension = ndx.dimension(function(d) {
return d.month;
});
var timelineGroup = timelineDimension.group().reduceSum(function(d) {
return d.zz;
});
var timelineAreaGroup = timelineDimension.group().reduce(
function(p, v) {
++p.count;
if (isNaN(v.m))
v.m = 0;
p.total += v.m;// (v.open + v.close) / 2;
return p;
}, function(p, v) {
--p.count;
if (isNaN(v.m))
v.m = 0;
p.total -= v.m;// (v.open + v.close) / 2;
return p;
}, function() {
return {
count : 0,
total : 0,
};
});
// counts per weekday
var horzBarDimension = ndx.dimension(function(d) {
return d.r || "";
});
var horzBarGrp = horzBarDimension.group().reduceSum(function(d) {
return d.zz;
});
THIS.pieChartCompanyCode.width(170).height(150).radius(60).dimension(
pieChartCompanyCodeDimension).group(pieCompanyCode).label(
function(d) {
var companyCode = d.key.split("-");
return companyCode[0];
}).on('filtered', function(chart) {
THIS.refreshTable(pieChartCompanyCodeDimension);
}).title(
function(d) {
return THIS.type == "netvalue" ? d.key + ': $'
+ numberFormat(d.value) : d.key + ': '
+ numberFormat(d.value);
});
THIS.pieChartDivision.width(170).height(150).radius(60).innerRadius(30)
.dimension(pieChartDivisionDimension).group(pieDivision).label(
function(d) {
var division = d.key.split("-");
return division[0];
}).on('filtered', function(chart) {
THIS.refreshTable(pieChartDivisionDimension);
}).title(
function(d) {
return THIS.type == "netvalue" ? d.key + ': $'
+ numberFormat(d.value) : d.key + ': '
+ numberFormat(d.value);
});
THIS.pieChartPlant.width(170).height(150).radius(60)
// .colors(colorScale)
.dimension(pieChartPlantDimension).group(piePlant).label(function(d) {
var plantGroup = d.key.split("-");
return plantGroup[0];
}).on('filtered', function(chart) {
THIS.refreshTable(pieChartPlantDimension);
}).title(
function(d) {
return THIS.type == "netvalue" ? d.key + ': $'
+ numberFormat(d.value) : d.key + ': '
+ numberFormat(d.value);
});
THIS.pieChartSalesOrg.width(170).height(150).radius(60).innerRadius(30)
.dimension(pieChartSalesOrgpDimension).group(pieSalesOrg)
.label(function(d) {
var purchaseOrg = d.key.split("-");
return purchaseOrg[0];
}).on('filtered', function(chart) {
THIS.refreshTable(pieChartSalesOrgpDimension);
}).title(
function(d) {
return THIS.type == "netvalue" ? d.key + ': $'
+ numberFormat(d.value) : d.key + ': '
+ numberFormat(d.value);
});
THIS.pieChartMaterialType.width(170).height(150).radius(60)
.innerRadius(30).dimension(pieChartMaterialTypeDimension)
.group(pieMaterialType).on('filtered', function(chart) {
THIS.refreshTable(pieChartMaterialTypeDimension);
}).title(
function(d) {
return THIS.type == "netvalue" ? d.key + ': $'
+ numberFormat(d.value) : d.key + ': '
+ numberFormat(d.value);
});
THIS.pieChartSalesDocType.width(170).height(150).radius(60)
.innerRadius(30).dimension(pieChartSalesDocTypeDimension)
.group(pieSalesDocType).on('filtered', function(chart) {
THIS.refreshTable(pieChartSalesDocTypeDimension);
}).label(function(d) {
var name = d.key.split("-");
return name[0];
}).title(
function(d) {
return THIS.type == "netvalue" ? d.key + ': $'
+ numberFormat(d.value) : d.key + ': '
+ numberFormat(d.value);
});
THIS.pieChartSalesGroup.width(170).height(150).radius(60).dimension(
pieChartSalesGroupDimension).group(pieSalesGroup).label(
function(d) {
var purchaseGrp = d.key.split("-");
return purchaseGrp[0];
}).on('filtered', function(chart) {
THIS.refreshTable(pieChartSalesGroupDimension);
}).title(
function(d) {
return THIS.type == "netvalue" ? d.key + ': $'
+ numberFormat(d.value) : d.key + ': '
+ numberFormat(d.value);
});
THIS.pieChartMaterialType.width(170).height(150).radius(60)
.innerRadius(30).dimension(pieChartMaterialTypeDimension)
.group(pieMaterialType).on('filtered', function(chart) {
THIS.refreshTable(pieChartMaterialTypeDimension);
}).title(
function(d) {
return THIS.type == "netvalue" ? d.key + ': $'
+ numberFormat(d.value) : d.key + ': '
+ numberFormat(d.value);
});
THIS.pieChartOrderReason.width(170).height(150).radius(60)
.innerRadius(30).dimension(pieChartOrderReasonDimension).label(
function(d) {
var purchaseGrp = d.key.split("-");
return purchaseGrp[0];
})
.group(pieOrderReason).on('filtered', function(chart) {
THIS.refreshTable(pieChartOrderReasonDimension);
}).title(
function(d) {
return THIS.type == "netvalue" ? d.key + ': $'
+ numberFormat(d.value) : d.key + ': '
+ numberFormat(d.value);
});
THIS.pieChartOrderCategory.width(170).height(150).radius(60)
.innerRadius(30).dimension(pieChartOrderCategoryDimension).label(
function(d) {
var purchaseGrp = d.key.split("-");
return purchaseGrp[0];
})
.group(pieOrderCategory).on('filtered', function(chart) {
THIS.refreshTable(pieChartOrderCategoryDimension);
}).title(
function(d) {
return THIS.type == "netvalue" ? d.key + ': $'
+ numberFormat(d.value) : d.key + ': '
+ numberFormat(d.value);
});
// #### Row Chart
THIS.horzBarChart.width(180).height(700).margins({
top : 20,
left : 10,
right : 10,
bottom : 20
}).group(horzBarGrp).dimension(horzBarDimension).on('filtered',
function(chart) {
THIS.refreshTable(horzBarDimension);
})
// assign colors to each value in the x scale domain
.ordinalColors(
[ '#3182bd', '#6baed6', '#9e5ae1', '#c64bef', '#da8aab' ])
.label(function(d) {
return d.key;// .split(".")[1];
})
// title sets the row text
.title(
function(d) {
return THIS.type == "netvalue" ? d.key + ': $'
+ numberFormat(d.value) : d.key + ': '
+ numberFormat(d.value);
}).elasticX(true).xAxis().ticks(4);
THIS.timelineAreaChart.renderArea(true).width($('#content').width())
.height(150).transitionDuration(1000).margins({
top : 30,
right : 70,
bottom : 25,
left : 80
}).dimension(timelineDimension).mouseZoomable(true).rangeChart(
THIS.timelineChart).x(
d3.time.scale()
.domain(
[ new Date(2011, 0, 1),
new Date(2015, 11, 31) ]))
.round(d3.time.month.round).xUnits(d3.time.months).elasticY(
true).renderHorizontalGridLines(true).brushOn(false)
.group(timelineAreaGroup, "Vendor Count").valueAccessor(
function(d) {
return d.value.total;
}).on('filtered', function(chart) {
THIS.refreshTable(timelineDimension);
})
// .stack(timelineSecondGroup, "Material Count", function(d)
// {
// return d.value;
// })
// title can be called by any stack layer.
.title(function(d) {
var value = d.value.total;
if (isNaN(value))
value = 0;
return dateFormat(d.key) + "\n$" + numberFormat(value);
});
THIS.timelineChart.width($('#content').width()).height(80).margins({
top : 40,
right : 70,
bottom : 20,
left : 80
}).dimension(timelineDimension).group(timelineGroup).centerBar(true)
.gap(1).x(
d3.time.scale()
.domain(
[ new Date(2011, 0, 1),
new Date(2015, 11, 31) ]))
.round(d3.time.month.round).alwaysUseRounding(true).xUnits(
d3.time.months);
dc.dataCount(".dc-data-count").dimension(ndx).group(all);
var dataTableData = data.slice(0, 100);
THIS.dataTable = $(".dc-data-table")
.DataTable(
{
"sDom" : "<'dt-top-row'Tlf>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row'<'col-sm-6'i><'col-sm-6 text-right'p>>",
"bProcessing" : true,
"bLengthChange" : true,
"bSort" : true,
"bInfo" : true,
"bJQueryUI" : false,
"scrollX" : true,
"aaData" : dataTableData,
"oTableTools" : {
"aButtons" : [ {
"sExtends" : "collection",
"sButtonText" : 'Export <span class="caret" />',
"aButtons" : [ "csv", "pdf" ]
} ],
"sSwfPath" : "js/plugin/datatables/media/swf/copy_csv_xls_pdf.swf"
},
"bDestroy" : true,
"processing" : true,
"aoColumns" : [
{
"mDataProp" : null,
"sDefaultContent" : '<img src="./img/details_open.png">'
}, {
"mDataProp" : "a",
"sDefaultContent" : "0",
"sClass" : "numbercolumn"
}, {
"mDataProp" : "b",
"sDefaultContent" : "",
}, {
"mDataProp" : "h",
"sDefaultContent" : "",
}, {
"mDataProp" : "k",
"sDefaultContent" : "",
}, {
"mData" : "q",
"sDefaultContent" : ""
}, {
"mDataProp" : "j",
"sDefaultContent" : "",
}, {
"mDataProp" : "d",
"sDefaultContent" : "",
}, {
"mDataProp" : "f",
"sDefaultContent" : "",
}, {
"mDataProp" : "m",
"sDefaultContent" : "0",
"mRender" : function(data, type, full) {
if (isNaN(data))
data = 0;
return numberFormat(data);
},
"sClass" : "numbercolumn"
}, {
"mDataProp" : "r",
"sDefaultContent" : "",
}, {
"mDataProp" : "p",
"sClass" : "numbercolumn",
"sDefaultContent" : ""
}, ],
"fnRowCallback" : function(nRow, aData,
iDisplayIndex, iDisplayIndexFull) {
var request = {
"viewType" : "level2",
"source" : aData.n || "null",
"companyCode" : aData.b || "null",
"plant" : aData.k || "null",
"salesOrg" : aData.d || "null",
"salesType" : aData.j || "null",
"salesGroup" : aData.f || "null",
"soType" : aData.r || "null",
"materialType" : aData.q || "null",
"lastChangeDate" : aData.p || "null",
"division" : aData.h || "null",
"region" : "CAN",
"customerId" : "null"
};
* private String soCount; a private String
* companyCode; b private String companyName; c
* private String salesOrg; d private String
* salesOrgName; e private String salesGroup; f
* private String salesGroupName; g private
* String division; h private String
* divisionName; i private String salesDocType;
* j private String plantGroup; k private String
* plantName; l private String netValue; m
* private String source; n private String
* region; o private String lastChanged; p
* private String materialType; q private String
* soType; r
$(nRow).attr({
"id" : "row" + iDisplayIndex
}).unbind('click').bind('click', request,
soProfiling.callLevel2soProfile);
}
});
*/ dc.renderAll();
};
this.callLevel2soProfile = function(request) {
var tr = $(this).closest('tr');
THIS.childId = "child" + $(tr).attr("id");
if ($(tr).find('td:eq(0)').hasClass("expandRow")) {
$($(tr).find('td:eq(0)').find('img')).attr('src',
'./img/details_open.png');
$("#" + THIS.childId).hide(50);
} else {
$($(tr).find('td:eq(0)').find('img')).attr('src',
'./img/details_close.png');
if (!$(tr).next().hasClass("childRowtable")) {
$(tr).after($("<tr/>").addClass("childRowtable").attr({
"id" : THIS.childId
}).append($("<td/>")).append($("<td/>").attr({
"colspan" : "13",
"id" : THIS.childId + "td"
}).addClass("carousel")));
//enableLoading(THIS.childId + "td", "50%", "45%");
request = request.data;
callAjaxService("JiraProfile", function(response) {
callbackSucessLevel2SOProfile(response, request);
}, callBackFailure, request, "POST");
} else {
$("#" + THIS.childId).show(50);
}
}
$(tr).find('td:eq(0)').toggleClass("expandRow");
};
var callbackSucessLevel2SOProfile = function(response, request) {
//disableLoading(THIS.childId + "td");
if (response && response.isException){
showNotification("error",response.customMessage);
return;
}
var childTabledata = null;
if (response != null)
childTabledata = response["level2SalesOrderList"];
$("#" + THIS.childId + "td")
.show()
.html("")
.append(
$("<table/>")
.addClass("table table-hover dc-data-table")
.attr({
"id" : THIS.childId + "Table"
})
.append(
$("<thead/>")
.append(
$("<tr/>")
.append(
$(
"<th/>")
.html(
"Sales Order"))
.append(
$(
"<th/>")
.html(
"Material #"))
.append(
$(
"<th/>")
.html(
"Customer ID"))
.append(
$(
"<th/>")
.html(
"Customer Name"))
.append(
$(
"<th/>")
.html(
"Plant Name"))
.append(
$(
"<th/>")
.html(
"Line Item"))
.append(
$(
"<th/>")
.html(
"Net Value")))));
$("#" + THIS.childId + "Table")
.DataTable(
{
"sDom" : "<'dt-top-row'Tlf>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row'<'col-sm-6'i><'col-sm-6 text-right'p>>",
"bProcessing" : true,
"bLengthChange" : true,
// "bServerSide": true,
"bInfo" : true,
"bFilter" : false,
"bJQueryUI" : false,
"aaData" : childTabledata,
"scrollX" : true,
"oTableTools" : {
"aButtons" : [ {
"sExtends" : "collection",
"sButtonText" : 'Export <span class="caret" />',
"aButtons" : [ "csv", "pdf" ]
} ],
"sSwfPath" : "js/plugin/datatables/media/swf/copy_csv_xls_pdf.swf"
},
"aoColumns" : [ {
"mDataProp" : "salesDoc",
"sDefaultContent" : ""
}, {
"mDataProp" : "materialNumber",
"sDefaultContent" : ""
}, {
"mDataProp" : "customerId",
"sDefaultContent" : ""
}, {
"mDataProp" : "customerName",
"sDefaultContent" : ""
}, {
"mDataProp" : "plantName",
"sDefaultContent" : ""
}, {
"mDataProp" : "salesItem",
"sDefaultContent" : ""
}, {
"mDataProp" : "netValue",
"sDefaultContent" : "",
"mRender" : function(data, type, full) {
return numberFormat(data);
},
"sClass" : "numbercolumn"
} ],
"fnRowCallback" : function(nRow, aData,
iDisplayIndex, iDisplayIndexFull) {
$(nRow)
.attr(
{
'onClick' : "javascript:thirdLevelDrillDownSO('', '"
+ aData.salesDoc
+ "','100','"
+ request.source
+ "')",
'data-target' : '#myModalthredlevel',
'data-toggle' : 'modal'
});
}
});
};
this.refreshTable = function(dim) {
if (THIS.dataTable !== null && dim !== null) {
THIS.dataTable.fnClearTable();
THIS.dataTable.fnAddData(dim.top(100));
THIS.dataTable.fnDraw();
} else
console
.log('[While Refreshing Data Table] This should never happen..');
};
d3.selectAll("#version").text(dc.version);
/*
* var config = { endpoint : 'soprofile', dataKey:
* 'aggregatedSalesOrderList', dataType: 'json', dataPreProcess: function(d) {
* d.dd = dateFormat.parse(d.p); d.month = d3.time.month(d.dd); d.a = +d.a;
* d.m = +d.m; }, mappings : [{ chartType : 'pie', htmlElement:
* '#pie-chart-CompanyCode', field: 'companycode', resetHandler: "#resetCC"
* },{ chartType : 'pie', htmlElement: '#pie-chart-plant', field:
* 'accgroup', groupon: 'glamount', groupRound: true, resetHandler:
* "#resetPlant" },{ chartType : 'pie', htmlElement: '#pie-chart-Division',
* field: 'tradpartner', groupon: 'glamount', groupRound: true,
* resetHandler: "#resetDiv" },{ chartType : 'pie', htmlElement:
* '#pie-chart-MaterialType', field: 'userid', groupon: 'glamount',
* groupRound: true, resetHandler: "#resetMT" },{ chartType : 'pie',
* htmlElement: '#pie-chart-Sales-Doc-Type', field: 'tcode', groupon:
* 'glamount', groupRound: true, resetHandler: "#resetDT" },{ chartType :
* 'pie', htmlElement: '#pie-chart-SalesOrg', field: 'tcode', groupon:
* 'glamount', groupRound: true, resetHandler: "#resetSO" },{ chartType :
* 'pie', htmlElement: '#pie-chart-SalesGroup', field: 'tcode', groupon:
* 'glamount', groupRound: true, resetHandler: "#resetSG" },{ chartType :
* 'horbar', htmlElement: '#row-chart', field: 'doctype', resetHandler:''
* },{ chartType : 'timeline', htmlElement: '#timeline-area-chart',
* subHtmlElement: '#timeline-chart', field: 'month', group: 'glamount',
* resetHandler:'#resetTAC', mapFunction:function(p, v) { ++p.count; if
* (isNaN(v.m)) v.m = 0; p.total += v.m;// (v.open + v.close) / 2; return p; },
* reduceFunction : function(p, v) { --p.count; p.total -= v.netprice;//
* (v.open + v.close) / 2; return p; }, countFunction: function() { return {
* count : 0, total : 0 }; } },{ chartType : 'table', htmlElement:
* '.dc-data-table', field: 'date', groupon: 'companycode', coloums:
* 'date,a, b,h,k,q,j,d,f,m,r,p', sortby: 'companycode', summarydiv :
* '.dc-data-count', renderlet: 'dc-table-group', resetHandler:'#resetRC' }] };
*/
// var sop = new Profiling(config);
// sop.init(function(){
// $('#loading').hide();
// });
};
soProfileInstance(); | Durgesh1988/core | client/htmls/public/js/jiraprofiling/e2e_JiraProfiling.js | JavaScript | apache-2.0 | 32,814 | [
30522,
1005,
2224,
9384,
1005,
1025,
1013,
1013,
2139,
8569,
13327,
1025,
1013,
1013,
5530,
3388,
6279,
1006,
1007,
1025,
13075,
2061,
21572,
8873,
2989,
1025,
13075,
2061,
21572,
8873,
19856,
12693,
3401,
1027,
3853,
1006,
1007,
1063,
2061... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
tinyMCE.addI18n('sk.simple',{
bold_desc:"Tu\u010Dn\u00FD text (Ctrl+B)",
italic_desc:"\u0160ikm\u00FD text (kurz\u00EDva) (Ctrl+I)",
underline_desc:"Pod\u010Diarknut\u00FD text (Ctrl+U)",
striketrough_desc:"Pre\u0161krtnut\u00FD text",
bullist_desc:"Zoznam s odr\u00E1\u017Ekami",
numlist_desc:"\u010C\u00EDslovan\u00FD zoznam",
undo_desc:"Sp\u00E4\u0165 (Ctrl+Z)",
redo_desc:"Znovu (Ctrl+Y)",
cleanup_desc:"Vy\u010Disti\u0165 neupraven\u00FD k\u00F3d"
}); | skevy/django-tinymce | tinymce/media/tiny_mce/themes/simple/langs/sk.js | JavaScript | mit | 466 | [
30522,
4714,
12458,
2063,
1012,
5587,
2072,
15136,
2078,
1006,
1005,
15315,
1012,
3722,
1005,
1010,
1063,
7782,
1035,
4078,
2278,
1024,
1000,
10722,
1032,
1057,
24096,
2692,
2094,
2078,
1032,
1057,
8889,
2546,
2094,
3793,
1006,
14931,
12190... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#include <QMessageBox>
#include "charakterform.h"
#include "fertigkeitform.h"
#include "ui_charakterform.h"
#include "ui_fertigkeitform.h"
CharakterForm::CharakterForm(QDialog *parent, std::shared_ptr<CharakterManager> charakterManager) :
QDialog(parent),charakterManager(charakterManager),
ui(new Ui::charakterform){
ui->setupUi(this);
fertigkeitForm = Ptr<FertigkeitForm>(new FertigkeitForm(this,charakterManager));
fertigkeitForm->setModal(true);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
connect(ui->weiterButton,SIGNAL(clicked()),this,SLOT(startGenerierung()));
connect(ui->abbrechenButton,SIGNAL(clicked()),this,SLOT(abbrechenGenerierung()));
connect(fertigkeitForm->ui->abbrechenButton,SIGNAL(clicked()),this,SLOT(abbrechenGenerierung()));
connect(fertigkeitForm.get(),SIGNAL(abschliessen()),this,SLOT(abschliessenGenerierung()));
connect(fertigkeitForm.get(),SIGNAL(abbrechen()),this,SLOT(abbrechenGenerierung()));
}
CharakterForm::~CharakterForm(){
delete ui;
}
void CharakterForm::startGenerierung(){
QString name = ui->lineEditName->text();
QString beschreibung = ui->textEditBeschreibung->toPlainText();
if(name == NULL || name.trimmed().size() == 0){
QMessageBox::warning(this,tr("Pflichtfeld nicht gesetzt."),tr("Bitte geben sie einen Namen für ihren Chrakter an."),QMessageBox::Ok);
}else{
charakterManager->addCharakterBeschreibung(name,beschreibung);
this->close();
fertigkeitForm->reset();
fertigkeitForm->show();
}
}
void CharakterForm::abschliessenGenerierung(){
charakterManager->insert(*(charakterManager->getCurrentCharakter().get()));
charakterManager->saveCharakterToFile();
resetForm();
emit beenden();
}
void CharakterForm::abbrechenGenerierung(){
foreach(QLineEdit *widget, this->findChildren<QLineEdit*>()) {
widget->clear();
}
foreach(QTextEdit *widget, this->findChildren<QTextEdit*>()) {
widget->clear();
}
this->close();
}
void CharakterForm::resetForm(){
ui->lineEditName->clear();
ui->textEditBeschreibung->clear();
}
| FireballGfx/FUK | Fuk/charakterform.cpp | C++ | gpl-3.0 | 2,158 | [
30522,
1001,
2421,
1026,
1053,
7834,
3736,
3351,
8758,
1028,
1001,
2421,
1000,
25869,
4817,
3334,
14192,
1012,
1044,
1000,
1001,
2421,
1000,
10768,
28228,
2290,
29501,
24475,
2953,
2213,
1012,
1044,
1000,
1001,
2421,
1000,
21318,
1035,
2586... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using System;
namespace Benchy.Framework
{
/// <summary>
/// Represents a breakdown of TimeSpan values.
/// </summary>
public interface IDataBreakout
{
/// <summary>
/// The minimum value of the breakout.
/// </summary>
TimeSpan RangeMinValue { get; set; }
/// <summary>
/// The maximum value of the breakout.
/// </summary>
TimeSpan RangeMaxValue { get; set; }
/// <summary>
/// The number of items that fit between that breakout.
/// </summary>
int Occurences { get; set; }
/// <summary>
/// Represents a way to render it textually.
/// </summary>
/// <returns>A string representing the Breakout.</returns>
string GetText();
}
} | cmbrown1598/Benchy | Benchy/IDataBreakout.cs | C# | apache-2.0 | 818 | [
30522,
2478,
2291,
1025,
3415,
15327,
6847,
2100,
1012,
7705,
1063,
1013,
1013,
1013,
1026,
12654,
1028,
1013,
1013,
1013,
5836,
1037,
12554,
1997,
2335,
9739,
5300,
1012,
1013,
1013,
1013,
1026,
1013,
12654,
1028,
2270,
8278,
16096,
2696,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/usr/bin/env bash
python run.py --test &
sleep 1
py.test -v -s --driver PhantomJS tests/selenium
exit_code=$?
pkill -9 -f run.py && exit ${exit_code}
| mijdavis2/starter_weppy | tests/selenium/run.sh | Shell | mit | 156 | [
30522,
1001,
999,
1013,
2149,
2099,
1013,
8026,
1013,
4372,
2615,
24234,
18750,
2448,
1012,
1052,
2100,
1011,
1011,
3231,
1004,
3637,
1015,
1052,
2100,
1012,
3231,
1011,
1058,
1011,
1055,
1011,
1011,
4062,
11588,
22578,
5852,
1013,
7367,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#include <iostream>
#include <vector>
using namespace std;
typedef long long int64;
#define FOR(i, a, b) for (int _end_ = (b), i = (a); i <= _end_; ++i)
template <typename T> T gcd(T x, T y) {
for (T t; x; t = x, x = y % x, y = t);
return y;
}
int64 fpm(int64 b, int64 e, int64 m) {
int64 t = 1;
for (; e; e >>= 1, b = b * b % m) {
e & 1 ? t = t * b % m : 0;
}
return t;
}
const int M = 100000000;
const int64 N = 1e11;
bool b[M + 1];
vector<int> get_primes(int n) {
vector<int> P;
FOR (i, 2, n) {
if (!b[i]) P.push_back(i);
int k = n / i;
for (auto x : P) {
if (x > k) break;
b[x * i] = true;
if (i % x == 0) break;
}
}
return P;
}
auto primes = get_primes(M);
int find_root(int p) {
int x = p - 1;
vector<int> v;
for (auto &y : primes) {
if (x == 1) break;
if (y * y > x) break;
if (x % y == 0) {
v.push_back((p - 1) / y);
for (; x /= y, x % y == 0; );
}
}
if (x != 1) v.push_back((p - 1) / x);
x = p - 1;
FOR (i, 2, p) {
bool b = true;
for (auto y : v)
if (fpm(i, y, p) == 1) {
b = false;
break;
}
if (b) return i;
}
return -1;
}
int inv[15];
int main() {
int64 ans = 0;
int cnt = 0;
FOR (i, 1, 15) {
int g = gcd(i, 15);
int x = i / g;
int y = 15 / g;
int e = 1;
for (; y * e % x != 1 % x; ++e);
inv[i % 15] = e;
}
for (auto p : primes) {
int x = find_root(p);
if (++cnt % 100000 == 0) {
cerr << p << " " << x << endl;
}
int g = gcd(p - 1, 15);
int y = (p - 1) / g;
int64 b = fpm(x, (p - 1) / (2 * g) * inv[(p - 1) % 15] % y, p);
int64 m = fpm(x, y, p);
FOR (t, 1, g) {
ans += (N + p - b) / p * p;
b = b * m % p;
}
}
cout << ans << endl;
return 0;
}
| kkmonlee/Project-Euler-Solutions | CCPP/p421.cpp | C++ | gpl-3.0 | 1,689 | [
30522,
1001,
2421,
1026,
16380,
25379,
1028,
1001,
2421,
1026,
9207,
1028,
2478,
3415,
15327,
2358,
2094,
1025,
21189,
12879,
2146,
2146,
20014,
21084,
1025,
1001,
9375,
2005,
1006,
1045,
1010,
1037,
1010,
1038,
1007,
2005,
1006,
20014,
103... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
*/
/*
* splitarcs.c++
*
*/
//#include "glimports.h"
//#include "myassert.h"
//#include "mysetjmp.h"
//#include "mystdio.h"
#include "subdivider.h"
#include "arcsorter.h"
//#include "arc.h"
//#include "bin.h"
/* local preprocessor definitions */
#define MAXARCS 10
/*----------------------------------------------------------------------------
* Subdivider::split - split trim regions in source bin by line (param == value).
*----------------------------------------------------------------------------
*/
void
Subdivider::split( Bin& bin, Bin& left, Bin& right, int param, REAL value )
{
Bin intersections, unknown;
partition( bin, left, intersections, right, unknown, param, value );
int count = intersections.numarcs();
if( count % 2 ) {
#ifndef NDEBUG
left.show( "left" );
intersections.show( "intersections" );
right.show( "right" );
#endif
::mylongjmp( jumpbuffer, 29 );
}
Arc_ptr arclist[MAXARCS], *list;
if( count >= MAXARCS ) {
list = new Arc_ptr[count];
} else {
list = arclist;
}
Arc_ptr jarc, *last, *lptr;
for( last = list; (jarc=intersections.removearc()) != NULL; last++ )
*last = jarc;
if( param == 0 ) { /* sort into increasing t order */
ArcSdirSorter sorter(*this);
sorter.qsort( list, count );
//::qsort ((void *)list, count, sizeof(Arc_ptr), (cmpfunc)compare_s);
for( lptr=list; lptr<last; lptr+=2 )
check_s ( lptr[0], lptr[1] );
for( lptr=list; lptr<last; lptr+=2 )
join_s ( left, right, lptr[0], lptr[1] );
for( lptr=list; lptr != last; lptr++ ) {
if( ((*lptr)->head()[0] <= value) && ((*lptr)->tail()[0] <= value) )
left.addarc( *lptr );
else
right.addarc( *lptr );
}
} else { /* sort into decreasing s order */
ArcTdirSorter sorter(*this);
sorter.qsort( list, count );
//::qsort ((void *)list, count, sizeof(Arc_ptr), (cmpfunc)compare_t);
for( lptr=list; lptr<last; lptr+=2 )
check_t ( lptr[0], lptr[1] );
for( lptr=list; lptr<last; lptr+=2 )
join_t ( left, right, lptr[0], lptr[1] );
for( lptr=list; lptr != last; lptr++ ) {
if( ((*lptr)->head()[1] <= value) && ((*lptr)->tail()[1] <= value) )
left.addarc( *lptr );
else
right.addarc( *lptr );
}
}
if( list != arclist ) delete[] list;
unknown.adopt();
}
void
Subdivider::check_s( Arc_ptr jarc1, Arc_ptr jarc2 )
{
assert( jarc1->check( ) != 0 );
assert( jarc2->check( ) != 0 );
assert( jarc1->next->check( ) != 0 );
assert( jarc2->next->check( ) != 0 );
assert( jarc1 != jarc2 );
/* XXX - if these assertions fail, it is due to user error or
undersampling */
if( ! ( jarc1->tail()[0] < (jarc1)->head()[0] ) ) {
#ifndef NDEBUG
_glu_dprintf( "s difference %f\n", (jarc1)->tail()[0] - (jarc1)->head()[0] );
#endif
::mylongjmp( jumpbuffer, 28 );
}
if( ! ( jarc2->tail()[0] > (jarc2)->head()[0] ) ) {
#ifndef NDEBUG
_glu_dprintf( "s difference %f\n", (jarc2)->tail()[0] - (jarc2)->head()[0] );
#endif
::mylongjmp( jumpbuffer, 28 );
}
}
inline void
Subdivider::link( Arc_ptr jarc1, Arc_ptr jarc2, Arc_ptr up, Arc_ptr down )
{
up->nuid = down->nuid = 0; // XXX
up->next = jarc2;
down->next = jarc1;
up->prev = jarc1->prev;
down->prev = jarc2->prev;
down->next->prev = down;
up->next->prev = up;
down->prev->next = down;
up->prev->next = up;
}
inline void
Subdivider::simple_link( Arc_ptr jarc1, Arc_ptr jarc2 )
{
Arc_ptr tmp = jarc2->prev;
jarc2->prev = jarc1->prev;
jarc1->prev = tmp;
jarc2->prev->next = jarc2;
jarc1->prev->next = jarc1;
}
/*----------------------------------------------------------------------------
* join - add a pair of oppositely directed jordan arcs between two arcs
*----------------------------------------------------------------------------
*/
void
Subdivider::join_s( Bin& left, Bin& right, Arc_ptr jarc1, Arc_ptr jarc2 )
{
assert( jarc1->check( ) != 0);
assert( jarc2->check( ) != 0);
assert( jarc1 != jarc2 );
if( ! jarc1->getitail() )
jarc1 = jarc1->next;
if( ! jarc2->getitail() )
jarc2 = jarc2->next;
REAL s = jarc1->tail()[0];
REAL t1 = jarc1->tail()[1];
REAL t2 = jarc2->tail()[1];
if( t1 == t2 ) {
simple_link( jarc1, jarc2 );
} else {
Arc_ptr newright = new(arcpool) Arc( arc_right, 0 );
Arc_ptr newleft = new(arcpool) Arc( arc_left, 0 );
assert( t1 < t2 );
if( isBezierArcType() ) {
arctessellator.bezier( newright, s, s, t1, t2 );
arctessellator.bezier( newleft, s, s, t2, t1 );
} else {
arctessellator.pwl_right( newright, s, t1, t2, stepsizes[0] );
arctessellator.pwl_left( newleft, s, t2, t1, stepsizes[2] );
}
link( jarc1, jarc2, newright, newleft );
left.addarc( newright );
right.addarc( newleft );
}
assert( jarc1->check( ) != 0 );
assert( jarc2->check( ) != 0 );
assert( jarc1->next->check( ) != 0);
assert( jarc2->next->check( ) != 0);
}
void
Subdivider::check_t( Arc_ptr jarc1, Arc_ptr jarc2 )
{
assert( jarc1->check( ) != 0 );
assert( jarc2->check( ) != 0 );
assert( jarc1->next->check( ) != 0 );
assert( jarc2->next->check( ) != 0 );
assert( jarc1 != jarc2 );
/* XXX - if these assertions fail, it is due to user error or
undersampling */
if( ! ( jarc1->tail()[1] < (jarc1)->head()[1] ) ) {
#ifndef NDEBUG
_glu_dprintf( "t difference %f\n", jarc1->tail()[1] - (jarc1)->head()[1] );
#endif
::mylongjmp( jumpbuffer, 28 );
}
if( ! ( jarc2->tail()[1] > (jarc2)->head()[1] ) ) {
#ifndef NDEBUG
_glu_dprintf( "t difference %f\n", jarc2->tail()[1] - (jarc2)->head()[1] );
#endif
::mylongjmp( jumpbuffer, 28 );
}
}
/*----------------------------------------------------------------------------
* join_t - add a pair of oppositely directed jordan arcs between two arcs
*----------------------------------------------------------------------------
*/
void
Subdivider::join_t( Bin& bottom, Bin& top, Arc_ptr jarc1, Arc_ptr jarc2 )
{
assert( jarc1->check( ) != 0 );
assert( jarc2->check( ) != 0 );
assert( jarc1->next->check( ) != 0 );
assert( jarc2->next->check( ) != 0 );
assert( jarc1 != jarc2 );
if( ! jarc1->getitail() )
jarc1 = jarc1->next;
if( ! jarc2->getitail() )
jarc2 = jarc2->next;
REAL s1 = jarc1->tail()[0];
REAL s2 = jarc2->tail()[0];
REAL t = jarc1->tail()[1];
if( s1 == s2 ) {
simple_link( jarc1, jarc2 );
} else {
Arc_ptr newtop = new(arcpool) Arc( arc_top, 0 );
Arc_ptr newbot = new(arcpool) Arc( arc_bottom, 0 );
assert( s1 > s2 );
if( isBezierArcType() ) {
arctessellator.bezier( newtop, s1, s2, t, t );
arctessellator.bezier( newbot, s2, s1, t, t );
} else {
arctessellator.pwl_top( newtop, t, s1, s2, stepsizes[1] );
arctessellator.pwl_bottom( newbot, t, s2, s1, stepsizes[3] );
}
link( jarc1, jarc2, newtop, newbot );
bottom.addarc( newtop );
top.addarc( newbot );
}
assert( jarc1->check( ) != 0 );
assert( jarc2->check( ) != 0 );
assert( jarc1->next->check( ) != 0 );
assert( jarc2->next->check( ) != 0 );
}
| GreenteaOS/Kernel | third-party/reactos/dll/opengl/glu32/src/libnurbs/internals/splitarcs.cc | C++ | gpl-2.0 | 8,966 | [
30522,
1013,
1008,
1008,
1008,
6105,
10439,
19341,
8553,
1012,
3272,
30524,
7936,
1999,
1996,
22214,
2072,
2489,
1008,
1008,
4007,
6105,
1038,
1010,
2544,
1015,
1012,
1015,
1006,
1996,
1000,
6105,
1000,
1007,
1010,
1996,
8417,
1997,
2023,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<span data="filter">
<span class="label" ng-class="{ 'label-primary' : $ctrl.filter._isDefault, 'label-emphasize' : !$ctrl.filter._isDefault }">
<i class="fa fa-filter"></i>
<span translate>{{$ctrl.filter._label}}</span>
<span>{{$ctrl.filter.comparitorLabel}}</span>
<span>{{$ctrl.filter.displayValue}}</span>
<!-- optional close button, displayed if this is not a default filter -->
<a
href
ng-if="!$ctrl.filter._isDefault"
ng-click="$ctrl.onRemove({ filter: $ctrl.filter._key })"
class="filter-text-link">
<i class="fa fa-close"></i>
</a>
</span>
</span>
| IMA-WorldHealth/bhima-2.X | client/src/modules/templates/bhFilter.tmpl.html | HTML | gpl-2.0 | 626 | [
30522,
1026,
8487,
2951,
1027,
1000,
11307,
1000,
1028,
1026,
8487,
2465,
1027,
1000,
3830,
1000,
12835,
1011,
2465,
1027,
1000,
1063,
1005,
3830,
1011,
3078,
1005,
1024,
1002,
14931,
12190,
1012,
11307,
1012,
1035,
2003,
3207,
7011,
11314,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
require "fedex/version"
require "fedex/web_services"
| parndt/fedex-web-services | lib/fedex.rb | Ruby | mit | 53 | [
30522,
5478,
1000,
7349,
10288,
1013,
2544,
1000,
5478,
1000,
7349,
10288,
1013,
4773,
1035,
2578,
1000,
102,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/usr/bin/env ruby
require 'swineherd' ; include Swineherd
require 'swineherd/script/pig_script' ; include Swineherd::Script
require 'swineherd/script/wukong_script' ; include Swineherd::Script
Settings.define :flow_id, :required => true, :description => "Workflow needs a unique numeric id"
Settings.define :input_dir, :required => true, :description => "Path to necessary data"
Settings.define :n_users, :description => "Number of users who've used tokens, see warning"
Settings.define :reduce_tasks, :default => 96, :description => "Change to reduce task capacity on cluster"
Settings.define :script_path, :default => "/home/jacob/Programming/infochimps-data/social/network/twitter/base/corpus"
Settings.define :n_toks, :default => "100", :description => "Number of tokens to include in wordbag"
Settings.resolve!
#
# WARNING: You cannot run this workflow from end-to-end at the moment. You
# should run up to and including 'user_frequencies'. Then, fetch the number of
# users by looking at the 'combine input groups' on the jobtracker for
# document_frequencies.pig. Next, run the workflow the same, this time passing
# in the number of users as an option.
#
flow = Workflow.new(Settings.flow_id) do
tokenizer = WukongScript.new("#{Settings.script_path}/tokenize/extract_word_tokens.rb")
frequencies = PigScript.new("#{Settings.script_path}/wordbag/tfidf/document_frequencies.pig")
tfidf = PigScript.new("#{Settings.script_path}/wordbag/tfidf/tfidf.pig")
top_n_bag = PigScript.new("#{Settings.script_path}/wordbag/tfidf/top_n_bag.pig")
task :tokenize do
tokenizer.input << "#{Settings.input_dir}/tweet"
tokenizer.output << next_output(:tokenize)
tokenizer.run
end
task :user_frequencies => [:tokenize] do
frequencies.output << next_output(:user_frequencies)
frequencies.pig_options = "-Dmapred.reduce.tasks=#{Settings.reduce_tasks}"
frequencies.options = {
:usages => latest_output(:tokenize),
:usage_freqs => latest_output(:user_frequencies)
}
frequencies.run
end
task :tfidf_weights => [:user_frequencies] do
tfidf.output << next_output(:tfidf_weights)
tfidf.pig_options = "-Dmapred.reduce.tasks=#{Settings.reduce_tasks}"
tfidf.options = {
:usage_freqs => latest_output(:user_frequencies),
:n_users => "#{Settings.n_users}l",
:user_token_graph => latest_output(:tfidf_weights)
}
tfidf.run
end
task :top_n_bag => [:tfidf_weights] do
top_n_bag.output << next_output(:top_n_bag)
top_n_bag.pig_options = "-Dmapred.reduce.tasks=#{Settings.reduce_tasks}"
top_n_bag.options = {
:n => Settings.n_tokens,
:twuid => "#{Settings.input_dir}/twitter_user_id",
:bigrph => latest_output(:tfidf_weights),
:wordbag => latest_output(:top_n_bag)
}
top_n_bag.run
end
end
flow.workdir = "/tmp/wordbag"
flow.describe
flow.run(Settings.rest.first)
| mrflip/prep-wu-data | social/network/twitter/base/corpus/wordbag/tfidf/tfidf_workflow.rb | Ruby | gpl-3.0 | 3,005 | [
30522,
1001,
999,
1013,
2149,
2099,
1013,
8026,
1013,
4372,
2615,
10090,
5478,
1005,
25430,
3170,
5886,
2094,
1005,
1025,
2421,
25430,
3170,
5886,
2094,
5478,
1005,
25430,
3170,
5886,
2094,
1013,
5896,
1013,
10369,
1035,
5896,
1005,
1025,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.math.matrix;
import java.util.Arrays;
import org.apache.commons.lang.Validate;
/**
* A minimal implementation of a vector (in the mathematical sense) that contains doubles.
*/
public class DoubleMatrix1D implements Matrix<Double> {
private final double[] _data;
private final int _elements;
/** Empty vector. */
public static final DoubleMatrix1D EMPTY_MATRIX = new DoubleMatrix1D(new double[0]);
/**
* @param data
* The data, not null
*/
public DoubleMatrix1D(final Double[] data) {
Validate.notNull(data);
_elements = data.length;
_data = new double[_elements];
for (int i = 0; i < _elements; i++) {
_data[i] = data[i];
}
}
/**
* @param data
* The data, not null
*/
public DoubleMatrix1D(final double... data) {
Validate.notNull(data);
_elements = data.length;
_data = Arrays.copyOf(data, _elements);
}
/**
* Create an vector of length n with all entries equal to value.
*
* @param n
* number of elements
* @param value
* value of elements
*/
public DoubleMatrix1D(final int n, final double value) {
_elements = n;
_data = new double[_elements];
Arrays.fill(_data, value);
}
/**
* Returns the underlying vector data. If this is changed so is the vector.
*
* @see #toArray to get a copy of data
* @return An array containing the vector elements
*/
public double[] getData() {
return _data;
}
/**
* Convert the vector to a double array. As its elements are copied, the array is independent from the vector data.
*
* @return An array containing a copy of vector elements
*/
public double[] toArray() {
return Arrays.copyOf(_data, _elements);
}
/**
* {@inheritDoc}
*/
@Override
public int getNumberOfElements() {
return _elements;
}
/**
* {@inheritDoc} This method expects one index - any subsequent indices will be ignored.
*/
@Override
public Double getEntry(final int... index) {
return _data[index[0]];
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(_data);
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final DoubleMatrix1D other = (DoubleMatrix1D) obj;
if (!Arrays.equals(_data, other._data)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer();
final int n = _data.length;
sb.append(" (");
for (int i = 0; i < n - 1; i++) {
sb.append(_data[i] + ", ");
}
sb.append(_data[n - 1] + ") ");
return sb.toString();
}
}
| McLeodMoores/starling | projects/analytics/src/main/java/com/opengamma/analytics/math/matrix/DoubleMatrix1D.java | Java | apache-2.0 | 3,045 | [
30522,
1013,
1008,
1008,
1008,
9385,
1006,
1039,
1007,
2268,
1011,
2556,
2011,
2330,
22864,
2863,
4297,
1012,
1998,
1996,
2330,
22864,
2863,
2177,
1997,
3316,
1008,
1008,
3531,
2156,
4353,
2005,
6105,
1012,
1008,
1013,
7427,
4012,
1012,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#include "InitializationBlock.hpp"
namespace GA {
class RandomInitializator : public InitializationBlock
{
private:
GENOTYPE_TYPE init_center;
GENOTYPE_TYPE init_radius;
public:
RandomInitializator(GENOTYPE_TYPE init_center, GENOTYPE_TYPE init_diameter);
void init(Generation *generation);
};
}
| biserx/GeneticAlgorithmFramework | src/initializators/RandomInitializator.hpp | C++ | gpl-3.0 | 315 | [
30522,
1001,
2421,
1000,
3988,
3989,
23467,
1012,
6522,
2361,
1000,
3415,
15327,
11721,
1063,
2465,
6721,
5498,
20925,
21335,
4263,
1024,
2270,
3988,
3989,
23467,
1063,
2797,
1024,
8991,
26305,
1035,
2828,
1999,
4183,
1035,
2415,
1025,
8991... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* Copyright (C) 2012-2014 Carlos Pais
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "get_user_input.h"
#include <QTextCodec>
GetUserInput::GetUserInput(QObject *parent) :
Action(parent)
{
init();
}
GetUserInput::GetUserInput(const QVariantMap& data, QObject *parent):
Action(data, parent)
{
init();
loadInternal(data);
}
void GetUserInput::init()
{
setType(GameObjectMetaType::GetUserInput);
}
void GetUserInput::loadData(const QVariantMap & data, bool internal)
{
if (!internal)
Action::loadData(data, internal);
if (data.contains("message") && data.value("message").type() == QVariant::String)
setMessage(data.value("message").toString());
if (data.contains("variable") && data.value("variable").type() == QVariant::String)
setVariable(data.value("variable").toString());
if (data.contains("defaultValue") && data.value("defaultValue").type() == QVariant::String)
setDefaultValue(data.value("defaultValue").toString());
}
QString GetUserInput::variable()
{
return mVariable;
}
void GetUserInput::setVariable(const QString & var)
{
if (var != mVariable) {
mVariable = var;
notify("variable", mVariable);
}
}
QString GetUserInput::message()
{
return mMessage;
}
void GetUserInput::setMessage(const QString & msg)
{
if (msg != mMessage) {
mMessage = msg;
notify("message", mMessage);
}
}
QString GetUserInput::defaultValue()
{
return mDefaultValue;
}
void GetUserInput::setDefaultValue(const QString & value)
{
if (value != mDefaultValue) {
mDefaultValue = value;
notify("defaultValue", mDefaultValue);
}
}
QString GetUserInput::displayText() const
{
QString var("");
QString text(tr("Prompt") + " ");
text += QString("\"%1\"").arg(mMessage);
if (mVariable.size())
var = " " + tr("and store reply in") + " $" + mVariable;
text += var;
return text;
}
QVariantMap GetUserInput::toJsonObject(bool internal) const
{
QVariantMap object = Action::toJsonObject(internal);
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
if (! codec)
codec = QTextCodec::codecForLocale();
object.insert("message", mMessage);
object.insert("variable", mVariable);
object.insert("defaultValue", mDefaultValue);
return object;
}
| fr33mind/Belle | editor/actions/get_user_input.cpp | C++ | gpl-3.0 | 2,974 | [
30522,
1013,
1008,
9385,
1006,
1039,
1007,
2262,
1011,
2297,
5828,
6643,
2483,
1008,
1008,
2023,
2565,
2003,
2489,
4007,
1024,
2017,
2064,
2417,
2923,
3089,
8569,
2618,
2009,
1998,
1013,
2030,
19933,
1008,
2009,
2104,
1996,
3408,
1997,
19... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import dask.dataframe as dd
import pandas.util.testing as tm
import pandas as pd
from dask.dataframe.shuffle import shuffle
import partd
from dask.async import get_sync
dsk = {('x', 0): pd.DataFrame({'a': [1, 2, 3], 'b': [1, 4, 7]},
index=[0, 1, 3]),
('x', 1): pd.DataFrame({'a': [4, 5, 6], 'b': [2, 5, 8]},
index=[5, 6, 8]),
('x', 2): pd.DataFrame({'a': [7, 8, 9], 'b': [3, 6, 9]},
index=[9, 9, 9])}
d = dd.DataFrame(dsk, 'x', ['a', 'b'], [0, 4, 9, 9])
full = d.compute()
def test_shuffle():
s = shuffle(d, d.b, npartitions=2)
assert isinstance(s, dd.DataFrame)
assert s.npartitions == 2
x = get_sync(s.dask, (s._name, 0))
y = get_sync(s.dask, (s._name, 1))
assert not (set(x.b) & set(y.b)) # disjoint
assert shuffle(d, d.b, npartitions=2)._name == shuffle(d, d.b, npartitions=2)._name
def test_default_partitions():
assert shuffle(d, d.b).npartitions == d.npartitions
def test_index_with_non_series():
tm.assert_frame_equal(shuffle(d, d.b).compute(),
shuffle(d, 'b').compute())
def test_index_with_dataframe():
assert sorted(shuffle(d, d[['b']]).compute().values.tolist()) ==\
sorted(shuffle(d, ['b']).compute().values.tolist()) ==\
sorted(shuffle(d, 'b').compute().values.tolist())
def test_shuffle_from_one_partition_to_one_other():
df = pd.DataFrame({'x': [1, 2, 3]})
a = dd.from_pandas(df, 1)
for i in [1, 2]:
b = shuffle(a, 'x', i)
assert len(a.compute(get=get_sync)) == len(b.compute(get=get_sync))
| vikhyat/dask | dask/dataframe/tests/test_shuffle.py | Python | bsd-3-clause | 1,642 | [
30522,
12324,
8695,
2243,
1012,
2951,
15643,
2004,
20315,
12324,
25462,
2015,
1012,
21183,
4014,
1012,
5604,
2004,
1056,
2213,
12324,
25462,
2015,
2004,
22851,
2013,
8695,
2243,
1012,
2951,
15643,
1012,
23046,
12324,
23046,
12324,
2112,
2094,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* 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.
*/
/*
* ComparisonOperatorsJUnitTest.java JUnit based test
*
* Created on March 10, 2005, 3:14 PM
*/
package org.apache.geode.cache.query.functional;
import static org.junit.Assert.fail;
import java.util.Collection;
import java.util.Iterator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.query.CacheUtils;
import org.apache.geode.cache.query.Query;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.cache.query.data.Portfolio;
import org.apache.geode.test.junit.categories.OQLQueryTest;
@Category({OQLQueryTest.class})
public class ComparisonOperatorsJUnitTest {
public ComparisonOperatorsJUnitTest() {}
public String getName() {
return this.getClass().getSimpleName();
}
@Before
public void setUp() throws java.lang.Exception {
CacheUtils.startCache();
Region region = CacheUtils.createRegion("Portfolios", Portfolio.class);
region.put("0", new Portfolio(0));
region.put("1", new Portfolio(1));
region.put("2", new Portfolio(2));
region.put("3", new Portfolio(3));
}
@After
public void tearDown() throws java.lang.Exception {
CacheUtils.closeCache();
}
String operators[] = {"=", "<>", "!=", "<", "<=", ">", ">="};
@Test
public void testCompareWithInt() throws Exception {
String var = "ID";
int value = 2;
QueryService qs = CacheUtils.getQueryService();
for (int i = 0; i < operators.length; i++) {
Query query =
qs.newQuery("SELECT DISTINCT * FROM /Portfolios where " + var + operators[i] + value);
Object result = query.execute();
if (result instanceof Collection) {
Iterator iter = ((Collection) result).iterator();
while (iter.hasNext()) {
boolean isPassed = false;
Portfolio p = (Portfolio) iter.next();
switch (i) {
case 0:
isPassed = (p.getID() == value);
break;
case 1:
isPassed = (p.getID() != value);
break;
case 2:
isPassed = (p.getID() != value);
break;
case 3:
isPassed = (p.getID() < value);
break;
case 4:
isPassed = (p.getID() <= value);
break;
case 5:
isPassed = (p.getID() > value);
break;
case 6:
isPassed = (p.getID() >= value);
break;
}
if (!isPassed)
fail(this.getName() + " failed for operator " + operators[i]);
}
} else {
fail(this.getName() + " failed for operator " + operators[i]);
}
}
}
@Test
public void testCompareWithString() throws Exception {
String var = "P1.secId";
String value = "DELL";
QueryService qs = CacheUtils.getQueryService();
for (int i = 0; i < operators.length; i++) {
Query query = qs.newQuery(
"SELECT DISTINCT * FROM /Portfolios where " + var + operators[i] + "'" + value + "'");
Object result = query.execute();
if (result instanceof Collection) {
Iterator iter = ((Collection) result).iterator();
while (iter.hasNext()) {
boolean isPassed = false;
Portfolio p = (Portfolio) iter.next();
switch (i) {
case 0:
isPassed = (p.getP1().getSecId().compareTo(value) == 0);
break;
case 1:
isPassed = (p.getP1().getSecId().compareTo(value) != 0);
break;
case 2:
isPassed = (p.getP1().getSecId().compareTo(value) != 0);
break;
case 3:
isPassed = (p.getP1().getSecId().compareTo(value) < 0);
break;
case 4:
isPassed = (p.getP1().getSecId().compareTo(value) <= 0);
break;
case 5:
isPassed = (p.getP1().getSecId().compareTo(value) > 0);
break;
case 6:
isPassed = (p.getP1().getSecId().compareTo(value) >= 0);
break;
}
if (!isPassed)
fail(this.getName() + " failed for operator " + operators[i]);
}
} else {
fail(this.getName() + " failed for operator " + operators[i]);
}
}
}
@Test
public void testCompareWithNULL() throws Exception {
String var = "P2";
Object value = null;
QueryService qs = CacheUtils.getQueryService();
for (int i = 0; i < operators.length; i++) {
Query query =
qs.newQuery("SELECT DISTINCT * FROM /Portfolios where " + var + operators[i] + value);
Object result = query.execute();
if (result instanceof Collection) {
Iterator iter = ((Collection) result).iterator();
while (iter.hasNext()) {
boolean isPassed = false;
Portfolio p = (Portfolio) iter.next();
switch (i) {
case 0:
isPassed = (p.getP2() == value);
break;
default:
isPassed = (p.getP2() != value);
break;
}
if (!isPassed)
fail(this.getName() + " failed for operator " + operators[i]);
}
} else {
fail(this.getName() + " failed for operator " + operators[i]);
}
}
}
@Test
public void testCompareWithUNDEFINED() throws Exception {
String var = "P2.secId";
QueryService qs = CacheUtils.getQueryService();
for (int i = 0; i < operators.length; i++) {
// According to docs:
// To perform equality or inequality comparisons with UNDEFINED, use the
// IS_DEFINED and IS_UNDEFINED preset query functions instead of these
// comparison operators.
if (!operators[i].equals("=") && !operators[i].equals("!=") && !operators[i].equals("<>")) {
Query query = qs.newQuery(
"SELECT DISTINCT * FROM /Portfolios where " + var + operators[i] + " UNDEFINED");
Object result = query.execute();
if (result instanceof Collection) {
if (((Collection) result).size() != 0)
fail(this.getName() + " failed for operator " + operators[i]);
} else {
fail(this.getName() + " failed for operator " + operators[i]);
}
}
}
}
}
| pdxrunner/geode | geode-core/src/integrationTest/java/org/apache/geode/cache/query/functional/ComparisonOperatorsJUnitTest.java | Java | apache-2.0 | 7,209 | [
30522,
1013,
1008,
1008,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
2030,
2062,
12130,
6105,
1008,
10540,
1012,
2156,
1996,
5060,
5371,
5500,
2007,
2023,
2147,
2005,
3176,
2592,
4953,
1008,
9385,
6095,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudioTools.Project.Automation {
[ComVisible(true)]
public class OAProject : EnvDTE.Project, EnvDTE.ISupportVSProperties {
#region fields
private ProjectNode project;
EnvDTE.ConfigurationManager configurationManager;
#endregion
#region properties
public object Project {
get { return this.project; }
}
internal ProjectNode ProjectNode {
get { return this.project; }
}
#endregion
#region ctor
internal OAProject(ProjectNode project) {
this.project = project;
}
#endregion
#region EnvDTE.Project
/// <summary>
/// Gets or sets the name of the object.
/// </summary>
public virtual string Name {
get {
return project.Caption;
}
set {
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
ProjectNode.Site.GetUIThread().Invoke(() => {
project.SetEditLabel(value);
});
}
}
}
public void Dispose() {
configurationManager = null;
}
/// <summary>
/// Microsoft Internal Use Only. Gets the file name of the project.
/// </summary>
public virtual string FileName {
get {
return project.ProjectFile;
}
}
/// <summary>
/// Microsoft Internal Use Only. Specfies if the project is dirty.
/// </summary>
public virtual bool IsDirty {
get {
int dirty;
ErrorHandler.ThrowOnFailure(project.IsDirty(out dirty));
return dirty != 0;
}
set {
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
ProjectNode.Site.GetUIThread().Invoke(() => {
project.isDirty = value;
});
}
}
}
internal void CheckProjectIsValid() {
if (this.project == null || this.project.Site == null || this.project.IsClosed) {
throw new InvalidOperationException();
}
}
/// <summary>
/// Gets the Projects collection containing the Project object supporting this property.
/// </summary>
public virtual EnvDTE.Projects Collection {
get { return null; }
}
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public virtual EnvDTE.DTE DTE {
get {
return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE));
}
}
/// <summary>
/// Gets a GUID string indicating the kind or type of the object.
/// </summary>
public virtual string Kind {
get { return project.ProjectGuid.ToString("B"); }
}
/// <summary>
/// Gets a ProjectItems collection for the Project object.
/// </summary>
public virtual EnvDTE.ProjectItems ProjectItems {
get {
return new OAProjectItems(this, project);
}
}
/// <summary>
/// Gets a collection of all properties that pertain to the Project object.
/// </summary>
public virtual EnvDTE.Properties Properties {
get {
return new OAProperties(this.project.NodeProperties);
}
}
/// <summary>
/// Returns the name of project as a relative path from the directory containing the solution file to the project file
/// </summary>
/// <value>Unique name if project is in a valid state. Otherwise null</value>
public virtual string UniqueName {
get {
if (this.project == null || this.project.IsClosed) {
return null;
} else {
// Get Solution service
IVsSolution solution = this.project.GetService(typeof(IVsSolution)) as IVsSolution;
Utilities.CheckNotNull(solution);
// Ask solution for unique name of project
string uniqueName;
ErrorHandler.ThrowOnFailure(
solution.GetUniqueNameOfProject(
project.GetOuterInterface<IVsHierarchy>(),
out uniqueName
)
);
return uniqueName;
}
}
}
/// <summary>
/// Gets an interface or object that can be accessed by name at run time.
/// </summary>
public virtual object Object {
get { return this.project.Object; }
}
/// <summary>
/// Gets the requested Extender object if it is available for this object.
/// </summary>
/// <param name="name">The name of the extender object.</param>
/// <returns>An Extender object. </returns>
public virtual object get_Extender(string name) {
Utilities.ArgumentNotNull("name", name);
return DTE.ObjectExtenders.GetExtender(project.NodeProperties.ExtenderCATID.ToUpper(), name, project.NodeProperties);
}
/// <summary>
/// Gets a list of available Extenders for the object.
/// </summary>
public virtual object ExtenderNames {
get { return DTE.ObjectExtenders.GetExtenderNames(project.NodeProperties.ExtenderCATID.ToUpper(), project.NodeProperties); }
}
/// <summary>
/// Gets the Extender category ID (CATID) for the object.
/// </summary>
public virtual string ExtenderCATID {
get { return project.NodeProperties.ExtenderCATID; }
}
/// <summary>
/// Gets the full path and name of the Project object's file.
/// </summary>
public virtual string FullName {
get {
string filename;
uint format;
ErrorHandler.ThrowOnFailure(project.GetCurFile(out filename, out format));
return filename;
}
}
/// <summary>
/// Gets or sets a value indicatingwhether the object has not been modified since last being saved or opened.
/// </summary>
public virtual bool Saved {
get {
return !this.IsDirty;
}
set {
IsDirty = !value;
}
}
/// <summary>
/// Gets the ConfigurationManager object for this Project .
/// </summary>
public virtual EnvDTE.ConfigurationManager ConfigurationManager {
get {
return ProjectNode.Site.GetUIThread().Invoke(() => {
if (this.configurationManager == null) {
IVsExtensibility3 extensibility = this.project.Site.GetService(typeof(IVsExtensibility)) as IVsExtensibility3;
Utilities.CheckNotNull(extensibility);
object configurationManagerAsObject;
ErrorHandler.ThrowOnFailure(extensibility.GetConfigMgr(
this.project.GetOuterInterface<IVsHierarchy>(),
VSConstants.VSITEMID_ROOT,
out configurationManagerAsObject
));
Utilities.CheckNotNull(configurationManagerAsObject);
this.configurationManager = (ConfigurationManager)configurationManagerAsObject;
}
return this.configurationManager;
});
}
}
/// <summary>
/// Gets the Globals object containing add-in values that may be saved in the solution (.sln) file, the project file, or in the user's profile data.
/// </summary>
public virtual EnvDTE.Globals Globals {
get { return null; }
}
/// <summary>
/// Gets a ProjectItem object for the nested project in the host project.
/// </summary>
public virtual EnvDTE.ProjectItem ParentProjectItem {
get { return null; }
}
/// <summary>
/// Gets the CodeModel object for the project.
/// </summary>
public virtual EnvDTE.CodeModel CodeModel {
get { return null; }
}
/// <summary>
/// Saves the project.
/// </summary>
/// <param name="fileName">The file name with which to save the solution, project, or project item. If the file exists, it is overwritten</param>
/// <exception cref="InvalidOperationException">Is thrown if the save operation failes.</exception>
/// <exception cref="ArgumentNullException">Is thrown if fileName is null.</exception>
public virtual void SaveAs(string fileName) {
ProjectNode.Site.GetUIThread().Invoke(() => {
this.DoSave(true, fileName);
});
}
/// <summary>
/// Saves the project
/// </summary>
/// <param name="fileName">The file name of the project</param>
/// <exception cref="InvalidOperationException">Is thrown if the save operation failes.</exception>
/// <exception cref="ArgumentNullException">Is thrown if fileName is null.</exception>
public virtual void Save(string fileName) {
ProjectNode.Site.GetUIThread().Invoke(() => {
this.DoSave(false, fileName);
});
}
/// <summary>
/// Removes the project from the current solution.
/// </summary>
public virtual void Delete() {
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
ProjectNode.Site.GetUIThread().Invoke(() => {
this.project.Remove(false);
});
}
}
#endregion
#region ISupportVSProperties methods
/// <summary>
/// Microsoft Internal Use Only.
/// </summary>
public virtual void NotifyPropertiesDelete() {
}
#endregion
#region private methods
/// <summary>
/// Saves or Save Asthe project.
/// </summary>
/// <param name="isCalledFromSaveAs">Flag determining which Save method called , the SaveAs or the Save.</param>
/// <param name="fileName">The name of the project file.</param>
private void DoSave(bool isCalledFromSaveAs, string fileName) {
Utilities.ArgumentNotNull("fileName", fileName);
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
// If an empty file name is passed in for Save then make the file name the project name.
if (!isCalledFromSaveAs && string.IsNullOrEmpty(fileName)) {
// Use the solution service to save the project file. Note that we have to use the service
// so that all the shell's elements are aware that we are inside a save operation and
// all the file change listenters registered by the shell are suspended.
// Get the cookie of the project file from the RTD.
IVsRunningDocumentTable rdt = this.project.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
Utilities.CheckNotNull(rdt);
IVsHierarchy hier;
uint itemid;
IntPtr unkData;
uint cookie;
ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, this.project.Url, out hier,
out itemid, out unkData, out cookie));
if (IntPtr.Zero != unkData) {
Marshal.Release(unkData);
}
// Verify that we have a cookie.
if (0 == cookie) {
// This should never happen because if the project is open, then it must be in the RDT.
throw new InvalidOperationException();
}
// Get the IVsHierarchy for the project.
IVsHierarchy prjHierarchy = project.GetOuterInterface<IVsHierarchy>();
// Now get the soulution.
IVsSolution solution = this.project.Site.GetService(typeof(SVsSolution)) as IVsSolution;
// Verify that we have both solution and hierarchy.
Utilities.CheckNotNull(prjHierarchy);
Utilities.CheckNotNull(solution);
ErrorHandler.ThrowOnFailure(solution.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, prjHierarchy, cookie));
} else {
// We need to make some checks before we can call the save method on the project node.
// This is mainly because it is now us and not the caller like in case of SaveAs or Save that should validate the file name.
// The IPersistFileFormat.Save method only does a validation that is necessary to be performed. Example: in case of Save As the
// file name itself is not validated only the whole path. (thus a file name like file\file is accepted, since as a path is valid)
// 1. The file name has to be valid.
string fullPath = fileName;
try {
fullPath = CommonUtils.GetAbsoluteFilePath(((ProjectNode)Project).ProjectFolder, fileName);
}
// We want to be consistent in the error message and exception we throw. fileName could be for example #¤&%"¤&"% and that would trigger an ArgumentException on Path.IsRooted.
catch (ArgumentException ex) {
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, fileName), ex);
}
// It might be redundant but we validate the file and the full path of the file being valid. The SaveAs would also validate the path.
// If we decide that this is performance critical then this should be refactored.
Utilities.ValidateFileName(this.project.Site, fullPath);
if (!isCalledFromSaveAs) {
// 2. The file name has to be the same
if (!CommonUtils.IsSamePath(fullPath, this.project.Url)) {
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(this.project.Save(fullPath, 1, 0));
} else {
ErrorHandler.ThrowOnFailure(this.project.Save(fullPath, 0, 0));
}
}
}
}
#endregion
}
/// <summary>
/// Specifies an alternate name for a property which cannot be fully captured using
/// .NET attribute names.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
class PropertyNameAttribute : Attribute {
public readonly string Name;
public PropertyNameAttribute(string name) {
Name = name;
}
}
}
| munyirik/nodejstools | Common/Product/SharedProject/Automation/OAProject.cs | C# | apache-2.0 | 16,787 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
[//]: # ( )
[//]: # ( )
[//]: # ( ooooooooo. oooooooooooo .o. oooooooooo. )
[//]: # ( `888 `Y88. `888' `8 .888. `888' `Y8b )
[//]: # ( 888 .d88' 888 .8"888. 888 888 )
[//]: # ( 888ooo88P' 888oooo8 .8' `888. 888 888 )
[//]: # ( 888`88b. 888 " .88ooo8888. 888 888 )
[//]: # ( 888 `88b. 888 o .8' `888. 888 d88' )
[//]: # ( o888o o888o o888ooooood8 o88o o8888o o888bood8P' )
[//]: # ( )
[//]: # ( READ THIS BEFORE EDITING )
[//]: # ( )
[//]: # ( At every release, /README.md is overwritten with )
[//]: # ( templates/README.md! Any changes not reflected )
[//]: # ( there will be void at the next release! See )
[//]: # ( templates/README.md for details. )
[//]: # ( )
[//]: # ( If you, for whatever reason, need to generate the file )
[//]: # ( manually, use: [with the latest release version] )
[//]: # ( mvn -DreadmeVersion=x.x.x.x \ )
[//]: # ( resources:copy-resources@update-readme-version )
# intake-spigot
A Spigot bridge for [sk89q/Intake](https://github.com/sk89q/Intake).
Delivered as standalone plugin (`intake-spigot-4.2.35-plugin.jar`) or simple Maven dependency (if you prefer the shades (⌐■_■)).
The standalone plugin currently comes with a [custom fork of Intake](https://github.com/xxyy/Intake)
that has some fixes necessary for some features to work. However, there are pending
[pull](https://github.com/sk89q/Intake/pull/26) [requests](https://github.com/sk89q/Intake/pull/25)
to upstream.
Once upstream accepts the changes or introduces comparable features, the dependency will be
changed back.
Namely, upstream doesn't allow more than a single `@Classifier` annotation per parameter type and
their `TextProvider` is broken. Also they don't support default commands using empty aliases.
# Features
When I first wanted to try Intake, I found out the hard way that it needs quite a bit of boilerplate code when
used with Bukkit, especially compared to the old
[sk89q-command-framework](https://github.com/OvercastNetwork/sk89q-command-framework).
To save others (and my future self) from having to go through this pain, I created a more-or-less
abstract library for what I needed. This includes:
* basic registration of Intake commands **without messing with `plugin.yml`**
* automatic creation of **helpful help messages** from command metadata with **JSON tooltips** and `<command> help` subcommands
* extensible **error handling**
* custom unchecked message exceptions (`CommandExitMessage`)
* **automatic translation** of Intake error messages to other languages (German is included, feel free to PR more!)
* **parameter providers** for common things used in commands
(such as `@ItemInHand ItemStack`, `@Merged @Colored String`, `CommandSender`, `@Sender Player`,
`@OnlinePlayer Player`)
* a intuitive builder framework
* detached nested commands! (yay separation)
* all that without having to shade anything
[(⌐■_■)](https://www.youtube.com/watch?v=X2LTL8KgKv8)
# Installation
Installing this as a server owner is as easy as dropping the
[current plugin jar](https://ci.l1t.li/job/public~intake-spigot/lastRelease/)
into your server's plugins folder.
Note that there's two artifacts: `intake-spigot.jar`,
which includes only the API, and `intake-spigot-4.2.35-plugin.jar`, which
can be used as a standalone plugin that other plugins can depend on. Try not to confuse
these two, because doing so usually causes errors and stack traces, and nobody wants that
to happen. This artifact requires that [`XYC`](https://github.com/xxyy/xyc) is also
installed as a plugin. If none of your other plugins depend on XYC, you can also use the
special `intake-spigot-4.2.35-plugin-with-xyc.jar` which includes XYC.
Installing this as a developer is slightly more complicated, since this
project isn't being deployed into Maven Central.
The latest release is `4.2.35`. The latest
git commit included in that version is
[this one](https://github.com/xxyy/intake-spigot/releases/tag/intake-spigot-4.2.35).
## Maven
````xml
<repositories>
<repository>
<id>xxyy-repo</id>
<url>https://repo.l1t.li/xxyy-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>li.l1t.common</groupId>
<artifactId>intake-spigot</artifactId>
<version>4.2.35</version>
</dependency>
</dependencies>
````
## Gradle
````groovy
repositories {
maven { url "https://repo.l1t.li/xxyy-public/" }
}
dependencies {
compile group: 'li.l1t.common', name: 'intake-spigot', version: '4.2.35'
}
````
# Examples
Some plugins using this library are [the Expvp minigame](https://github.com/xxyy/expvp)
(full-blown Dependency Injection, service layer, custom everything) and
[my test plugin](https://github.com/xxyy/intake-spigot-test). If you have written a
Free Software and/or open-source plugin that you think could be listed here,
open an issue on GitHub.
Here's a simple command with some custom injections:
````java
public class MyCommand {
@Command(aliases = "setname", min = 2,
desc = "Changes the name",
usage = "[id] [name...]")
@Require("your.permission")
public void editName(YourService service, CommandSender sender,
YourThing thing,
@Merged @Colored String name)
throws IOException {
String previousName = thing.getName();
thing.setName(name);
sender.sendMessage("This is an awesome message");
}
}
````
Here's the code required to make XYC-Intake class and inject that:
````java
//best time to call this is on enable
private void registerCommands() {
commandsManager = new CommandsManager(plugin);
commandsManager.setLocale(sender -> /* your command sender to locale logic */);
commandsManager.setLocale(Locale.ENGLISH); // use the same locale for everyone
// if you don't set any locale, the system default is used
registerInjections();
commandsManager.registerCommand(new MyCommand(), "mc", "mcalias");
}
private void registerInjections() {
commandsManager.bind(YourService.class).toInstance(new YourService());
commandsManager.bind(YourThing.class).toProvider(new YourThingProvider(thingService));
}
````
The `registerCommand()` method automatically takes care of registering your command with Spigot.
Sadly, there is no public API for that, so it uses some internals for that, that may not be
compatible with certain nasty plugins which exchange the Spigot command map with their own version -
it should be fine for most applications though.
Note that you need to remove the command definitions from your `plugin.yml` before Intake-Spigot
can register them properly!
Providers work like in Vanilla Intake. Here's an example for sake of completeness:
````java
public class YourThingProvider implements Provider<YourThing> {
private final YourService service;
public SkillProvider(YourService service) {
this.service = service;
}
@Override
public boolean isProvided() {
return false;
}
@Nullable
@Override
public Skill get(CommandArgs arguments, List<? extends Annotation> modifiers) throws ArgumentException, ProvisionException {
String thingId = arguments.next();
return service.getThingOrFail(skillId);
}
@Override
public List<String> getSuggestions(String prefix) { //tab-complete
return service.getAllThings().stream()
.map(String::valueOf)
.collect(Collectors.toList());
}
}
````
If you want to see this plugin used in an actual project, take
a look at [Expvp](https://github.com/xxyy/Expvp). (Note however
that it makes heavy use of dependency injection and therefore
your own usage might differ, with some more repetitive code)
(Note that tab-complete for providers won't work until upstream pulls
[this PR](https://github.com/sk89q/Intake/pull/23).
# Screenshots
Here's some screenshots that demonstrate how generated messages look ingame.
The reason that it's all in German is obviously for demonstrating that it's multi-language and
not that I was too lazy to change the language.
Here's some help generated by the library, complete with a JSON tooltip:

Here's an Intake error message that was translated by the plugin:

Here's another translated message:

# Contributing
All contributions welcome, including further translations!
This project uses standard IntelliJ code style. Format your code with `Ctrl+Alt+L`.
I recommend that you read ['Clean Code' by the awesome Robert C. Martin](https://www.google.at/webhp?q=clean+code+pdf#newwindow=1&q=clean+code+pdf).
## Updating the Readme
When editing the readme, you need to change the template in `docs-templates/README.md` and then
update the actual `README.md` using:
````bash
mvn -DreadmeVersion=4.2.35 resources:copy-resources@update-readme-version
````
# License
This project is licensed under LGPL, mainly because it includes two lines from Intake that I had to copy
(y u make everything package-private).
See the included `LICENSE.txt` file for details.
| xxyy/intake-spigot | README.md | Markdown | lgpl-3.0 | 10,191 | [
30522,
1031,
1013,
1013,
1033,
1024,
1001,
1006,
1007,
1031,
1013,
1013,
1033,
1024,
1001,
1006,
1007,
1031,
1013,
1013,
1033,
1024,
1001,
1006,
1051,
9541,
9541,
9541,
9541,
1012,
1051,
9541,
9541,
9541,
9541,
9541,
2080,
1012,
1051,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.