repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
coscms/xorm | builder/builder_select.go | 1073 | // Copyright 2016 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package builder
import (
"errors"
"fmt"
)
func (b *Builder) selectWriteTo(w Writer) error {
if len(b.tableName) <= 0 {
return errors.New("no table indicated")
}
if _, err := fmt.Fprint(w, "SELECT "); err != nil {
return err
}
if len(b.selects) > 0 {
for i, s := range b.selects {
if _, err := fmt.Fprint(w, s); err != nil {
return err
}
if i != len(b.selects)-1 {
if _, err := fmt.Fprint(w, ","); err != nil {
return err
}
}
}
} else {
if _, err := fmt.Fprint(w, "*"); err != nil {
return err
}
}
if _, err := fmt.Fprintf(w, " FROM %s", w.Key(b.tableName)); err != nil {
return err
}
for _, v := range b.joins {
fmt.Fprintf(w, " %s JOIN %s ON ", v.joinType, w.Key(v.joinTable))
if err := v.joinCond.WriteTo(w); err != nil {
return err
}
}
if _, err := fmt.Fprint(w, " WHERE "); err != nil {
return err
}
return b.cond.WriteTo(w)
}
| bsd-3-clause |
ldthomas/apg-js2-examples | execute-rule/colors.js | 2921 | // Generated by JavaScript APG, Version [`apg-js2`](https://github.com/ldthomas/apg-js2)
module.exports = function(){
"use strict";
//```
// SUMMARY
// rules = 3
// udts = 4
// opcodes = 15
// --- ABNF original opcodes
// ALT = 1
// CAT = 3
// REP = 1
// RNM = 2
// TLS = 4
// TBS = 0
// TRG = 0
// --- SABNF superset opcodes
// UDT = 4
// AND = 0
// NOT = 0
// BKA = 0
// BKN = 0
// BKR = 0
// ABG = 0
// AEN = 0
// characters = [44 - 119] + user defined
//```
/* OBJECT IDENTIFIER (for internal parser use) */
this.grammarObject = 'grammarObject';
/* RULES */
this.rules = [];
this.rules[0] = {name: 'start', lower: 'start', index: 0, isBkr: false};
this.rules[1] = {name: 'color', lower: 'color', index: 1, isBkr: false};
this.rules[2] = {name: 'dummy', lower: 'dummy', index: 2, isBkr: false};
/* UDTS */
this.udts = [];
this.udts[0] = {name: 'u_red', lower: 'u_red', index: 0, empty: false, isBkr: false};
this.udts[1] = {name: 'u_white', lower: 'u_white', index: 1, empty: false, isBkr: false};
this.udts[2] = {name: 'u_blue', lower: 'u_blue', index: 2, empty: false, isBkr: false};
this.udts[3] = {name: 'u_yellow', lower: 'u_yellow', index: 3, empty: false, isBkr: false};
/* OPCODES */
/* start */
this.rules[0].opcodes = [];
this.rules[0].opcodes[0] = {type: 2, children: [1,2]};// CAT
this.rules[0].opcodes[1] = {type: 4, index: 1};// RNM(color)
this.rules[0].opcodes[2] = {type: 3, min: 0, max: Infinity};// REP
this.rules[0].opcodes[3] = {type: 2, children: [4,5]};// CAT
this.rules[0].opcodes[4] = {type: 7, string: [44]};// TLS
this.rules[0].opcodes[5] = {type: 4, index: 1};// RNM(color)
/* color */
this.rules[1].opcodes = [];
this.rules[1].opcodes[0] = {type: 1, children: [1,2,3]};// ALT
this.rules[1].opcodes[1] = {type: 7, string: [114,101,100]};// TLS
this.rules[1].opcodes[2] = {type: 7, string: [119,104,105,116,101]};// TLS
this.rules[1].opcodes[3] = {type: 7, string: [98,108,117,101]};// TLS
/* dummy */
this.rules[2].opcodes = [];
this.rules[2].opcodes[0] = {type: 2, children: [1,2,3,4]};// CAT
this.rules[2].opcodes[1] = {type: 11, empty: false, index: 0};// UDT(u_red)
this.rules[2].opcodes[2] = {type: 11, empty: false, index: 1};// UDT(u_white)
this.rules[2].opcodes[3] = {type: 11, empty: false, index: 2};// UDT(u_blue)
this.rules[2].opcodes[4] = {type: 11, empty: false, index: 3};// UDT(u_yellow)
// The `toString()` function will display the original grammar file(s) that produced these opcodes.
this.toString = function(){
var str = "";
str += "start = color *(\",\" color)\n";
str += "color = \"red\" / \"white\" / \"blue\"\n";
str += "dummy = u_red u_white u_blue u_yellow\n";
return str;
}
}
| bsd-3-clause |
MicroEJ/DemoJava-Showroom | com.is2t.widgets/src/java/com/is2t/mwt/widgets/tiny/Clock.java | 4305 | /**
* Java
* Copyright 2009-2012 IS2T. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be found at http://www.is2t.com/open-source-bsd-license/.
*/
package com.is2t.mwt.widgets.tiny;
import java.util.Calendar;
import java.util.Date;
import com.is2t.mwt.widgets.IClock;
import ej.mwt.Widget;
/**
* A clock is a widget that displays a date.
*/
public class Clock extends Widget implements IClock {
/**
* Creates a new clock with the current time. <br>
* Equivalent to {@link #Clock(Date)} passing <code>new Date(System.currentTimeMillis())</code>
* as argument.
*/
public Clock() {
this(new Date(System.currentTimeMillis()));
}
/**
* Creates a new clock specifying the date.<br>
* A clock is disabled by default.<br>
*
* @param date the date of the clock
*/
public Clock(Date date) {
setEnabled(false);
calendar = java.util.Calendar.getInstance();
calendar.setTime(date);
}
/**
* Sets a new date. The clock is not automatically repainted.
* @param date the date to set
*/
public void setDate(Date date) {
calendar.setTime(date);
}
/**
* Gets the date of the clock.
* @return the date of the clock
*/
public Date getDate() {
return calendar.getTime();
}
/**
* Adds an year to the current date.
*/
public void addYear() {
add(java.util.Calendar.YEAR, 1);
}
/**
* Subtracts an year to the current date.
*/
public void subYear() {
add(java.util.Calendar.YEAR, -1);
}
/**
* Gets the year of the current date.
*
* @return the year of the current date
*/
public int getYear() {
return calendar.get(java.util.Calendar.YEAR);
}
/**
* Adds an month to the current date.
*/
public void addMonth() {
add(java.util.Calendar.MONTH, 1);
}
/**
* Subtracts an month to the current date.
*/
public void subMonth() {
add(java.util.Calendar.MONTH, -1);
}
/**
* Gets the month of the current date.
*
* @return the month of the current date
*/
public int getMonth() {
return calendar.get(java.util.Calendar.MONTH);
}
/**
* Adds an day to the current date.
*/
public void addDay() {
add(java.util.Calendar.DAY_OF_MONTH, 1);
}
/**
* Subtracts an day to the current date.
*/
public void subDay() {
add(java.util.Calendar.DAY_OF_MONTH, -1);
}
/**
* Gets the day of month of the current date.
*
* @return the day of month of the current date
* @see Calendar
*/
public int getDayOfMonth() {
return calendar.get(java.util.Calendar.DAY_OF_MONTH);
}
/**
* Gets the day of week of the current date.
*
* @return the day of week of the current date
* @see Calendar
*/
public int getDayOfWeek() {
return calendar.get(java.util.Calendar.DAY_OF_WEEK);
}
/**
* Adds an hour to the current date.
*/
public void addHour() {
add(java.util.Calendar.HOUR_OF_DAY, 1);
}
/**
* Subtracts an hour to the current date.
*/
public void subHour() {
add(java.util.Calendar.HOUR_OF_DAY, -1);
}
/**
* Gets the hour of the current date.
*
* @return the hour of the current date
*/
public int getHour() {
return calendar.get(java.util.Calendar.HOUR_OF_DAY);
}
/**
* Adds a minute to the current date.
*/
public void addMinute() {
add(java.util.Calendar.MINUTE,1);
}
/**
* Subtracts a minute to the current date.
*/
public void subMinute() {
add(java.util.Calendar.MINUTE,-1);
}
/**
* Gets the minute of the current date.
* @return the minute of the current date
*/
public int getMinute() {
return calendar.get(java.util.Calendar.MINUTE);
}
/**
* Adds a second to the current date.
*/
public void addSecond() {
add(java.util.Calendar.SECOND,1);
}
/**
* Subtracts a second to the current date.
*/
public void subSecond() {
add(java.util.Calendar.SECOND,-1);
}
/**
* Gets the second of the current date.
* @return the second of the current date
*/
public int getSecond() {
return calendar.get(java.util.Calendar.SECOND);
}
/****************************************************************
* NOT IN API
****************************************************************/
protected java.util.Calendar calendar;
protected void add(int field, int increment) {
calendar.set(field, calendar.get(field)+increment);
repaint();
}
}
| bsd-3-clause |
AlchemyCMS/alchemy-usermanual | spec/libraries/template_helper_spec.rb | 92 | require 'spec_helper'
module Alchemy::UserManual
describe 'TemplateHelper' do
end
end
| bsd-3-clause |
Charleo85/SIS-Rebuild | batch_script.py | 2722 | from kafka import KafkaConsumer
from elasticsearch import Elasticsearch
import json, time
try:
# wait for 30 seconds for the initialization of Kafka
time.sleep(30)
# try to create instances of Kafka and Elasticsearch
es = Elasticsearch(['es'])
consumer = KafkaConsumer('new-listings-topic', group_id='listing-indexer', bootstrap_servers=['kafka:9092'])
finally:
# initialize the Elasticsearch instance
es = Elasticsearch(['es'])
# Load fixture into elastic search
data = {}
with open('./models/instructors.json') as data_file:
data = json.load(data_file)
with open('./models/students.json') as data_file:
data += json.load(data_file)
with open('./models/courses.json') as data_file:
data += json.load(data_file)
for element in data:
# General Index
if 'id' in element['fields']:
# password should not be included in search
if 'password' in element['fields']:
element['fields'].pop('password', None)
es.index(index='general_index', doc_type='listing', id=element['fields']['id'], body=element)
# Model Specific Indices
if element['model'] == 'api.Instructor':
es.index(index='instructor_index', doc_type='listing', id=element['fields']['id'], body=element)
elif element['model'] == 'api.Student':
es.index(index='student_index', doc_type='listing', id=element['fields']['id'], body=element)
elif element['model'] == 'api.Course':
es.index(index='course_index', doc_type='listing', id=element['fields']['id'], body=element)
# Start listening to Kafka Queue
consumer = KafkaConsumer('new-listings-topic', group_id='listing-indexer', bootstrap_servers=['kafka:9092'])
while True:
for message in consumer:
new_listing = (json.loads(message.value.decode('utf-8')))
# General Index
es.index(index='general_index', doc_type='listing', id=new_listing['fields']['id'], body=new_listing)
# Model Specific Indices
if new_listing['model'] == 'api.Instructor':
es.index(index='instructor_index', doc_type='listing', id=new_listing['fields']['id'], body=new_listing)
elif new_listing['model'] == 'api.Student':
es.index(index='student_index', doc_type='listing', id=new_listing['fields']['id'], body=new_listing)
elif new_listing['model'] == 'api.Course':
es.index(index='course_index', doc_type='listing', id=new_listing['fields']['id'], body=new_listing)
# refresh all incides to make changes effective
es.indices.refresh(index="listing_index")
| bsd-3-clause |
TechFit/myDay | models/dayresult.php | 1931 | <?php
namespace app\models;
use Yii;
use yii\data\Sort;
use yii\db\ActiveRecord;
class dayresult extends ActiveRecord{
public static function getAll($userId){
return self::find()->asArray()->where("user_id = '$userId'")->orderBy('date')->all();
}
public static function getAllPagination($userId){
return self::find()->asArray()->where("user_id = '$userId'")->orderBy('date');
}
public static function addRow($date, $result, $listResult, $userId){
$query = new dayresult();
$query->date = $date;
$query->result = $result;
$query->listResult = $listResult;
$query->user_id = $userId;
$query->save();
}
public static function delAll($id)
{
$delete = dayresult::findOne($id);
$delete->delete();
}
public static function getDataShedule($dayResult){
$sort = new Sort([
'attributes' => [
'date'
],
]);
$query = dayresult::getAllPagination(Yii::$app->getUser()->id);
$pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => 4]);
$models = $query->offset($pages->offset)
->limit($pages->limit)->orderBy($sort->orders)
->all();
foreach ($dayResult as $item)
{
$getDayResultDate[] = $item['date'];
$getDayResultCount[] = (int)($item['result'] * 100 / count($allNameEx));
$getDayResultList[] = $item['listResult'];
}
return [
'sort' => $sort,
'pages' => $pages,
'models' => $models,
'getDayResultDate' => $getDayResultDate,
'getDayResultCount' => $getDayResultCount,
'getDayResultList' => $getDayResultList
];
}
}
| bsd-3-clause |
ymohl-cl/game-builder | scene/loader/build_loader.go | 1639 | package loader
import (
"os"
"runtime"
"github.com/ymohl-cl/game-builder/objects"
"github.com/ymohl-cl/game-builder/objects/block"
"github.com/ymohl-cl/game-builder/objects/text"
)
func (L *DefaultLoader) addBlockLoading() error {
var b *block.Block
var err error
if b, err = block.New(block.Filled); err != nil {
return err
}
b.SetVariantStyle(colorRed, colorGreen, colorBlue, colorOpacity, objects.SFix)
b.UpdateSize(L.widthBlock, L.heightBlock)
b.UpdatePosition(originX+L.widthBlock, originY+(L.heightScreen-L.heightScreen/4))
if err = b.Init(L.renderer); err != nil {
return err
}
L.layers[layerLoadingBar] = append(L.layers[layerLoadingBar], b)
L.loadBlock = b
return nil
}
func (L *DefaultLoader) addTxt() error {
var t *text.Text
var err error
var x, y int32
var fontPath string
x = L.widthScreen / 2
y = L.heightScreen / 4
// get good path to open font
fontPath = os.Getenv("GOPATH") + "/pkg/" + runtime.GOOS + "_" + runtime.GOARCH + font
// add title
if t, err = text.New(mainTxt, sizeMainTxt, fontPath, x, y); err != nil {
return err
}
t.SetVariantStyle(colorRed, colorGreen, colorBlue, colorOpacity, objects.SFix)
if err = t.Init(L.renderer); err != nil {
return err
}
L.layers[layerText] = append(L.layers[layerText], t)
// add signature
y = L.heightScreen / 2
if t, err = text.New(txtBottomToLoad, sizeTxtBottomToLoad, fontPath, x, y); err != nil {
return err
}
t.SetVariantStyle(colorRed, colorGreen, colorBlue, colorOpacity, objects.SFix)
if err = t.Init(L.renderer); err != nil {
return err
}
L.layers[layerText] = append(L.layers[layerText], t)
return nil
}
| bsd-3-clause |
tmaiaroto/minerva | config/bootstrap.php | 3024 | <?php
use lithium\core\Libraries;
// Add a minerva_models type
Libraries::paths(array('minerva_models' => array(
'{:library}\minerva\models\{:name}'
)
));
// Set the date so we don't get any warnings (should be in your php.ini)
$tz = ini_get('date.timezone');
if (!$tz) {
$tz = 'UTC';
}
date_default_timezone_set($tz);
// Get minerva's configuration for various reasons
$minerva_config = Libraries::get('minerva');
$base_url = isset($config['url']) ? $config['url'] : '/minerva';
$admin_prefix = isset($config['admin_prefix']) ? $config['admin_prefix'] : 'admin';
define('MINERVA_BASE_URL', $base_url);
define('MINERVA_ADMIN_PREFIX', $admin_prefix);
/**
* The error configuration allows you to use the filter system along with the advanced matching
* rules of the `ErrorHandler` class to provide a high level of control over managing exceptions in
* your application, with no impact on framework or application code.
*/
require __DIR__ . '/bootstrap/errors.php';
require __DIR__ . '/bootstrap/media.php';
require __DIR__ . '/bootstrap/connections.php';
require __DIR__ . '/bootstrap/session.php';
require __DIR__ . '/bootstrap/auth.php';
/**
* This sets up minerva's access system.
* It is optional, if 'minerva_access' is set to false in the minerva library configuration
* then the default access system will not be used. The system will then rely completely
* upon 3rd party access control. At that point, in order to protect core actions, filters
* would be the logical step to take.
*
* @todo: rewrite minervas config access System!
* something like: MinervaConfig::assertIdentical('use_minerva_access')
*
* NOTE: Minerva's core access system is basic, but can be extended by additional access rules.
* In the very least, it could be used for a "super administrator" role only and an additional
* access system for every other type of user and need could be put into place.
* Please take care when disabling even the most basic of security measures.
*/
if (!isset($minerva_config['use_minerva_access']) || $minerva_config['use_minerva_access'] === true) {
require __DIR__ . '/bootstrap/access.php';
}
/**
* The templates.php file applies a filter on the dispatcher so that a more robust
* template system is put into place. This is critical to Minerva.
*/
require __DIR__ . '/bootstrap/templates.php';
/**
* Minerva integrates with Facebook, optionally, but by design.
* If Minerva's config has a 'facebook' key with 'appId' and 'secret' then it will use the
* li3_facebook library and it will become a dependency.
*/
require __DIR__ . '/bootstrap/facebook.php';
/**
* The dependencies.php file applies a filter on the dispatcher so that anytime Minerva
* is called, it will check for the proper dependencies. Minvera requires several other
* Lithium libraries in order to function properly. However, once you have these dependencies,
* you could safely comment out this line and save the system a few function calls.
*/
require __DIR__ . '/bootstrap/dependencies.php';
?> | bsd-3-clause |
alameluchidambaram/CONNECT | Product/Production/Services/DocumentQueryCore/src/main/java/gov/hhs/fha/nhinc/gateway/aggregator/model/DocQueryMessageKey.java | 9761 | /*
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government 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 UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.gateway.aggregator.model;
import gov.hhs.fha.nhinc.gateway.aggregator.AggregatorException;
/**
* This represents the fields that make up the message key that identifies a single document query record in the
* aggregator message results table.
*
* @author Les Westberg
*/
public class DocQueryMessageKey {
private static final String DOC_QUERY_TAG = "DocQuery";
private static final String DOC_QUERY_TAG_START = "<" + DOC_QUERY_TAG + ">";
private static final String DOC_QUERY_TAG_END = "</" + DOC_QUERY_TAG + ">";
private static final String HOME_COMMUNITY_ID_TAG = "HomeCommunityId";
private static final String HOME_COMMUNITY_ID_TAG_START = "<" + HOME_COMMUNITY_ID_TAG + ">";
private static final String HOME_COMMUNITY_ID_TAG_END = "</" + HOME_COMMUNITY_ID_TAG + ">";
private static final String ASSIGNING_AUTHORITY_TAG = "AssigningAuthority";
private static final String ASSIGNING_AUTHORITY_TAG_START = "<" + ASSIGNING_AUTHORITY_TAG + ">";
private static final String ASSIGNING_AUTHORITY_TAG_END = "</" + ASSIGNING_AUTHORITY_TAG + ">";
private static final String PATIENT_ID_TAG = "PatientId";
private static final String PATIENT_ID_TAG_START = "<" + PATIENT_ID_TAG + ">";
private static final String PATIENT_ID_TAG_END = "</" + PATIENT_ID_TAG + ">";
// Private member variables
// -------------------------
private String homeCommunityId;
private String assigningAuthority;
private String patientId;
/**
* Default constructor.
*/
public DocQueryMessageKey() {
clear();
}
/**
* This method takes the information in a formatted message key and creates an object with that information. This
* key should be one that was created by this class. (or at least exactly formatted that way).
*
* @param sMessageKey The message key as formatted by calling the creatingXMLMessageKey.
* @throws AggregatorException This is thrown if the format of the XML message is not correct.
*/
public DocQueryMessageKey(String sMessageKey) throws AggregatorException {
// Since this is a simple XML that is in a controlled format -
// It is easiest to just pull out the fields by hand-parsing...
// -------------------------------------------------------------
parseXMLMessageKey(sMessageKey);
}
/**
* Clear the ocntents of this object
*/
public void clear() {
homeCommunityId = "";
assigningAuthority = "";
patientId = "";
}
/**
* Return the assigning authority.
*
* @return The assigning authority.
*/
public String getAssigningAuthority() {
return assigningAuthority;
}
/**
* Sets the assigning authority.
*
* @param assigningAuthority The assigning authority.
*/
public void setAssigningAuthority(String assigningAuthority) {
this.assigningAuthority = assigningAuthority;
}
/**
* Return the home community ID. Note if this has not been set, then a look up will be done to retrieve it based on
* assigning authority.
*
* @return The home community ID.
*/
public String getHomeCommunityId() {
return homeCommunityId;
}
/**
* Sets the home community ID. Note if this has not been set, then a look up will be done to retrieve it based on
* assigning authority.
*
* @param homeCommunityId The home community ID.
*/
public void setHomeCommunityId(String homeCommunityId) {
this.homeCommunityId = homeCommunityId;
}
/**
* Returns the patient Id.
*
* @return The patient Id.
*/
public String getPatientId() {
return patientId;
}
/**
* Sets the patient Id.
*
* @param patientId The patient Id.
*/
public void setPatientId(String patientId) {
this.patientId = patientId;
}
/**
* This method creates the XML Message Key that will be stored in the MessageKey field of the
* AGGREGATOR.AGG_MESSAGE_RESULTS table.
*
* @return The XML key that is created based on the fields in this object.
*/
public String createXMLMessageKey() {
String sAssigningAuthority = "";
String sHomeCommunityId = "";
String sPatientId = "";
if (assigningAuthority != null) {
sAssigningAuthority = assigningAuthority.trim();
}
if (homeCommunityId != null) {
// Right now the assigning authority and home community are the same.
// When this work gets done, we will need to
// -------------------------------------------------------------------
if (homeCommunityId.trim().length() <= 0) {
sHomeCommunityId = sAssigningAuthority;
} else {
sHomeCommunityId = homeCommunityId.trim();
}
}
if (patientId != null) {
sPatientId = patientId.trim();
}
String sKey = DOC_QUERY_TAG_START + HOME_COMMUNITY_ID_TAG_START + sHomeCommunityId + HOME_COMMUNITY_ID_TAG_END
+ ASSIGNING_AUTHORITY_TAG_START + sAssigningAuthority + ASSIGNING_AUTHORITY_TAG_END
+ PATIENT_ID_TAG_START + sPatientId + PATIENT_ID_TAG_END + DOC_QUERY_TAG_END;
return sKey;
}
/**
* Since this is a simple XML that is in a controlled format - It is easiest to just pull out the fields by
* hand-parsing...
*
* @param sMessageKey The XML string key containing the data.
* @throws AggregatorException This is thrown if the format of the XML message is not correct.
*/
public void parseXMLMessageKey(String sMessageKey) throws AggregatorException {
int iStartIdx = 0;
int iEndIdx = 0;
// Get the Home community
// ------------------------
iStartIdx = sMessageKey.indexOf(HOME_COMMUNITY_ID_TAG_START);
if (iStartIdx >= 0) {
iStartIdx += HOME_COMMUNITY_ID_TAG_START.length();
} else {
throw new AggregatorException("Format of DocQueryMessageKey was invalid. MessageKey = '" + sMessageKey
+ "'");
}
iEndIdx = sMessageKey.indexOf(HOME_COMMUNITY_ID_TAG_END);
if (iEndIdx > 0) {
homeCommunityId = sMessageKey.substring(iStartIdx, iEndIdx);
} else {
throw new AggregatorException("Format of DocQueryMessageKey was invalid. MessageKey = '" + sMessageKey
+ "'");
}
// Get the Assigning Authority
// -----------------------------
iStartIdx = sMessageKey.indexOf(ASSIGNING_AUTHORITY_TAG_START);
if (iStartIdx >= 0) {
iStartIdx += ASSIGNING_AUTHORITY_TAG_START.length();
} else {
throw new AggregatorException("Format of DocQueryMessageKey was invalid. MessageKey = '" + sMessageKey
+ "'");
}
iEndIdx = sMessageKey.indexOf(ASSIGNING_AUTHORITY_TAG_END);
if (iEndIdx > 0) {
assigningAuthority = sMessageKey.substring(iStartIdx, iEndIdx);
} else {
throw new AggregatorException("Format of DocQueryMessageKey was invalid. MessageKey = '" + sMessageKey
+ "'");
}
// Get the Patient Id
// -------------------
iStartIdx = sMessageKey.indexOf(PATIENT_ID_TAG_START);
if (iStartIdx >= 0) {
iStartIdx += PATIENT_ID_TAG_START.length();
} else {
throw new AggregatorException("Format of DocQueryMessageKey was invalid. MessageKey = '" + sMessageKey
+ "'");
}
iEndIdx = sMessageKey.indexOf(PATIENT_ID_TAG_END);
if (iEndIdx > 0) {
patientId = sMessageKey.substring(iStartIdx, iEndIdx);
} else {
throw new AggregatorException("Format of DocQueryMessageKey was invalid. MessageKey = '" + sMessageKey
+ "'");
}
}
}
| bsd-3-clause |
meishichao/yii2test | vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php | 1715 | <?php
/**
* Definition cache decorator class that cleans up the cache
* whenever there is a cache miss.
*/
class HTMLPurifier_DefinitionCache_Decorator_Cleanup extends HTMLPurifier_DefinitionCache_Decorator
{
/**
* @type string
*/
public $name = 'Cleanup';
/**
* @return HTMLPurifier_DefinitionCache_Decorator_Cleanup
*/
public function copy()
{
return new HTMLPurifier_DefinitionCache_Decorator_Cleanup();
}
/**
* @param HTMLPurifier_Definition $def
* @param HTMLPurifier_Config $config
* @return mixed
*/
public function add($def, $config)
{
$status = parent::add($def, $config);
if (!$status) {
parent::cleanup($config);
}
return $status;
}
/**
* @param HTMLPurifier_Definition $def
* @param HTMLPurifier_Config $config
* @return mixed
*/
public function set($def, $config)
{
$status = parent::set($def, $config);
if (!$status) {
parent::cleanup($config);
}
return $status;
}
/**
* @param HTMLPurifier_Definition $def
* @param HTMLPurifier_Config $config
* @return mixed
*/
public function replace($def, $config)
{
$status = parent::replace($def, $config);
if (!$status) {
parent::cleanup($config);
}
return $status;
}
/**
* @param HTMLPurifier_Config $config
* @return mixed
*/
public function get($config)
{
$ret = parent::get($config);
if (!$ret) {
parent::cleanup($config);
}
return $ret;
}
}
// vim: et sw=4 sts=4
| bsd-3-clause |
codeliner/codelinerjs | src/Codelinerjs/Javascript/library/Backbone/BlockingView.js | 751 | var ClBackbone = $CL.namespace("Cl.Backbone");
$CL.require("Cl.Backbone.View");
ClBackbone.BlockingView = function() {};
ClBackbone.BlockingView = $CL.extendClass(ClBackbone.BlockingView, Cl.Backbone.View, {
renderingIsBlocked : false,
renderingQueued : false,
blockRendering : function() {
this.renderingIsBlocked = true;
},
stopBlocking : function() {
this.renderingIsBlocked = false;
if (this.renderingQueued) {
this.render();
this.renderingQueued = false;
}
},
render : function() {
if (!this.renderingIsBlocked) {
Cl.Backbone.View.prototype.render.apply(this);
} else {
this.renderingQueued = true;
}
}
}); | bsd-3-clause |
nickus83/Funny-Critters | prj.scripts/viewer.py | 11918 | # -*- coding: utf-8 -*-
import os
import os.path as osp
import math
import numpy as np
import pygame
import random
import sys
from pygame.locals import *
def getImage(filename):
"""Get image for dissolving."""
sys.path.append("../prj.core")
try:
from utils import load_png
except Exception, e:
print(e)
finally:
del sys.path[-1]
try:
image = load_png(filename)
except pygame.error, message:
print "Cannot load image:", filename
raise SystemExit, message
else:
return image
def getPixelArray(image, rect=None):
"""Get pixel array of given rect."""
if not rect:
width, height = image.get_size()
dimension = min([width, height])
rect = pygame.Rect(0, 0, dimension, dimension)
part = image.subsurface(rect)
assert(part.get_size()[0] == part.get_size()[1]) # only square images
return pygame.surfarray.pixels3d(part)
class ColorCell(object):
"""Cell with the color of corresonding pixel in the field area."""
def __init__(self, x, y, size, color, padding=1):
super(ColorCell, self).__init__()
self.rect = pygame.Rect((x * size, y * size), (size, size))
self.color = color
self.padding = padding
def draw_cell(self, surface, background_color=None):
"""Draws cell with padding."""
if background_color:
surface.fill(background_color, self.rect)
else:
surface.fill(pygame.Color("gray"), self.rect)
surface.fill(
self.color, self.rect.inflate(-self.padding, -self.padding))
def highligh_cell(self, surface):
"""Draw cell with highlighted padding."""
surface.fill(pygame.Color("red"), self.rect)
surface.fill(
self.color, self.rect.inflate(-self.padding, -self.padding))
class Button(object):
"""Button for tools"""
def __init__(self, rect, text, padding=1):
super(Button, self).__init__()
self.rect = rect
self.color = pygame.Color(random.randrange(0, 255),
random.randrange(0, 255),
random.randrange(0, 255))
self.padding = padding
self.text = text
def draw_button(self, surface, background_color=None):
"""Draw button with padding"""
surface.fill(
self.color, self.rect.inflate(-self.padding, -self.padding))
font = pygame.font.Font(None, 15)
surface.blit(font.render(self.text, True, pygame.Color("black")),
(self.rect.x, self.rect.y))
class FieldGrid(object):
"""FieldGrid describing loading image"""
def __init__(self, pxarray):
super(FieldGrid, self).__init__()
self.data = []
self.field = pygame.Surface((800, 800))
self.pxarray = pxarray
self.update_data()
def update_data(self):
self.step = 800 / len(self.pxarray[0])
width, height = self.field.get_size()
self.data = []
for x in xrange(len(self.pxarray[0])):
self.data.append([])
for y in xrange(len(self.pxarray[0])):
self.data[x].append(None)
def image_to_grid(self):
palette = []
temp_set = set()
HEIGHT = WIDTH = len(self.pxarray[0])
for row in xrange(HEIGHT):
for column in xrange(WIDTH):
color = pygame.Color(int(self.pxarray[row][column][0]),
int(self.pxarray[row][column][1]),
int(self.pxarray[row][column][2]))
temp_set.add((int(self.pxarray[row][column][0]),
int(self.pxarray[row][column][1]),
int(self.pxarray[row][column][2])))
cell = ColorCell(row, column, self.step, color)
self.data[row][column] = cell
temp_list = list(temp_set)
for r, g, b in temp_list:
palette.append(pygame.Color(r, g, b))
return self.pxarray, palette
def change_pixel(self, row, column, selected_color):
self.pxarray[row][column][0] = selected_color.r
self.pxarray[row][column][1] = selected_color.g
self.pxarray[row][column][2] = selected_color.b
self.image_to_grid()
def draw_field(self, padding=1):
width, height = self.field.get_size()
for x, row in enumerate(self.data):
for y, column in enumerate(row):
try:
column.padding = padding
column.draw_cell(self.field)
except Exception as e:
print(e)
def get_idx(self, pos):
"""Return cell of field grid for given position."""
row, column = (int(math.ceil(pos[0] / self.step)),
int(math.ceil(pos[1] / self.step)))
return row, column
def redraw_pixel(self, row, column, color):
target_cell = self.data[row][column]
target_cell.color = color
target_cell.draw_cell(self.field)
class ToolsGrid(object):
"""Grid for tools area."""
def __init__(self, step=20):
super(ToolsGrid, self).__init__()
self.data = []
self.buttons = []
self.tools = pygame.Surface((475, 600))
self.tools.fill(pygame.Color("grey"))
self.step = step
self.width, self.height = self.tools.get_size()
for x in xrange(29): # max 667 colors
self.data.append([])
for y in xrange(23):
self.data[x].append(0)
for x in xrange(11): # 11 buttons
self.buttons.append(0)
self.step = step
def insert_palette(self, palette):
"""Save given palatte."""
for x, row in enumerate(self.data):
for y, column in enumerate(row):
if len(palette) > 0:
self.data[x][y] = ColorCell(y, x, self.step, palette.pop())
else:
self.data[x][y] = 0
for x, column in enumerate(self.buttons): # insert buttons
self.buttons[x] = Button(
(pygame.Rect(0 + (20 * x * 2), 580, 40, 20)), "Resize")
def draw_tools(self, padding=1):
"""Draw palette."""
width, height = self.tools.get_size()
for x, row in enumerate(self.data):
for y, column in enumerate(row):
if column != 0:
column.padding = padding
column.draw_cell(self.tools)
for x, column in enumerate(self.buttons):
if column != 0:
column.draw_button(self.tools)
def get_cell(self, pos):
"""Return cell of tools grid for given position."""
row, column = (int(math.ceil((pos[0] - 805) / self.step)),
int(math.ceil(pos[1] / self.step)))
if self.data[column][row] != 0:
return self.data[column][row]
def get_button(self, (x, y)):
"""Return button on given coordinates"""
for button in self.buttons:
if button.rect.collidepoint(x - 805, y):
return button
def main(image_name, target_rect):
size = width, height = 1280, 800
FPS = 10
screen = pygame.display.set_mode(size, 0)
clock = pygame.time.Clock()
pygame.font.init()
image = getImage(image_name)
pxarray = getPixelArray(image, target_rect)
# main area with image
grid = FieldGrid(pxarray)
tools = ToolsGrid()
tumbnails = pygame.Surface((480, 195)) # thumbnails
tumbnails.fill(pygame.Color("grey"))
image_pixel, image_palette = grid.image_to_grid()
tools.insert_palette(image_palette)
te = pygame.surfarray.make_surface(image_pixel)
tumbnails.blit(te, (10, 10))
tools.draw_tools()
grid.draw_field()
done = False
selected_color = None
while not done: # main loop
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
done = True
elif event.key == K_UP:
try:
target_rect = target_rect.move(0, -1)
except Exception as e:
print(e)
elif event.key == K_DOWN:
target_rect = target_rect.move(0, 1)
elif event.key == K_LEFT:
target_rect = target_rect.move(-1, 0)
elif event.key == K_RIGHT:
target_rect = target_rect.move(1, 0)
elif event.type == MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
if event.button == 1: # left mouse button
if 0 <= x <= 800 and 0 <= y <= 800: # in the field area
row, column = grid.get_idx((x, y))
if selected_color:
grid.change_pixel(row, column, selected_color)
selected_color = None # Empty selected color
grid.draw_field()
elif 805 <= x <= 1280 and 0 <= y < 580: # in the tools area
tools_cell = tools.get_cell((x, y))
if tools_cell:
selected_color = tools_cell.color
tools_cell.draw_cell(
tools.tools, pygame.Color("red"))
elif 805 <= x <= 1280 and 580 <= y <= 600: # in the buttons area
button_pressed = tools.get_button((x, y))
if button_pressed:
print(button_pressed.color)
elif event.button == 4 or event.button == 5:
if pygame.key.get_pressed() == K_LCTRL:
rm = 5
else:
rm = 1 # resize multiplier
if event.button == 4: # scroll up
target_rect = target_rect.inflate(-rm, -rm)
elif event.button == 5: # scroll down
target_rect = target_rect.inflate(rm, rm)
elif event.button == 3:
print(x, y)
elif event.type == pygame.QUIT:
done = True
grid.pxarray = getPixelArray(image, target_rect)
screen.fill(pygame.Color("black"))
grid.update_data()
new_image_pixel, _ = grid.image_to_grid()
grid.draw_field()
new_te = pygame.surfarray.make_surface(new_image_pixel)
tumbnails.blit(new_te, (10, 10))
screen.blit(grid.field, (0, 0))
screen.blit(tools.tools, (805, 0))
screen.blit(tumbnails, (805, 605))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
if __name__ == '__main__':
from argparse import ArgumentParser
p = ArgumentParser(description='image viewer')
p.add_argument('-i', '--image', required=True,
help="name of image in data/images dir (only .png)")
p.add_argument('-l', '--left', default=0, type=int,
required=False, help="left corner of the rect taken out of the picture")
p.add_argument('-t', '--top', default=0, type=int,
required=False, help="top corner of the rect taken out of the picture")
p.add_argument('-w', '--width', default=32, type=int,
required=True, help="width of the rect taken out of the picture")
p.add_argument('-he', '--height', default=32, type=int,
required=True, help="height of the rect taken out of the picture")
args = p.parse_args()
target_rect = pygame.Rect(args.left, args.top, args.width, args.height)
main(args.image, target_rect)
| bsd-3-clause |
prolop/Prolop-cms | backend/views/comment/update.php | 866 | <?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\Comment */
$this->title = 'Обновить комментарий: ';
$this->params['breadcrumbs'][] = ['label' => 'Comments', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="comment-update">
<h1>
<?= Html::encode($this->title) ?>
<?= Html::a('Удалить', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Вы уверенны, что хотите удалить эту запись?',
'method' => 'post',
],
]) ?>
</h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| bsd-3-clause |
simodalla/newage | newage/migrations/0001_initial.py | 350 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
}
complete_apps = ['newage'] | bsd-3-clause |
diginmanager/digin | frontend/views/skills-testimonials/_search.php | 987 | <?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\SkillsTestimonialsSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="skills-testimonials-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'testid') ?>
<?= $form->field($model, 'userid') ?>
<?= $form->field($model, 'quotes') ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'image') ?>
<?php // echo $form->field($model, 'crtdt') ?>
<?php // echo $form->field($model, 'crtby') ?>
<?php // echo $form->field($model, 'upddt') ?>
<?php // echo $form->field($model, 'updby') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| bsd-3-clause |
mdcconcepts/opinion_desk_CAP | protected/modules/user/views/admin/view.php | 1889 | <?php
$this->breadcrumbs = array(
UserModule::t('Users') => array('admin'),
$model->username,
);
$this->menu = array(
// array('label' => UserModule::t('Create User'), 'url' => array('create')),
array('label' => UserModule::t('Update User'), 'url' => array('update', 'id' => $model->id)),
array('label' => UserModule::t('Delete User'), 'url' => '#', 'linkOptions' => array('submit' => array('delete', 'id' => $model->id), 'confirm' => UserModule::t('Are you sure to delete this item?'))),
array('label' => UserModule::t('Manage Users'), 'url' => array('admin')),
array('label' => UserModule::t('Manage Profile Field'), 'url' => array('profileField/admin')),
array('label' => UserModule::t('List User'), 'url' => array('/user')),
);
?>
<h1><?php echo UserModule::t('View User') . ' "' . $model->username . '"'; ?></h1>
<?php
$attributes = array(
'id',
'username',
);
$profileFields = ProfileField::model()->forOwner()->sort()->findAll();
if ($profileFields) {
foreach ($profileFields as $field) {
array_push($attributes, array(
'label' => UserModule::t($field->title),
'name' => $field->varname,
'type' => 'raw',
'value' => (($field->widgetView($model->profile)) ? $field->widgetView($model->profile) : (($field->range) ? Profile::range($field->range, $model->profile->getAttribute($field->varname)) : $model->profile->getAttribute($field->varname))),
));
}
}
array_push($attributes, 'password', 'email', 'activkey', 'create_at', 'lastvisit_at', array(
'name' => 'superuser',
'value' => User::itemAlias("AdminStatus", $model->superuser),
), array(
'name' => 'status',
'value' => User::itemAlias("UserStatus", $model->status),
)
);
$this->widget('zii.widgets.CDetailView', array(
'data' => $model,
'attributes' => $attributes,
));
?>
| bsd-3-clause |
mvjohn100/spree_bank_transfer | spec/models/spree/bank_account_spec.rb | 115 | require 'spec_helper'
describe Spree::BankAccount do
pending "add some examples to (or delete) #{__FILE__}"
end
| bsd-3-clause |
ryneches/SuchTree | SuchTree/tests/test_SuchLinkedTrees.py | 11688 | from __future__ import print_function
from functools import reduce
import pytest
from SuchTree import SuchTree, SuchLinkedTrees
from dendropy import Tree
from itertools import combinations
import numpy
import pandas as pd
import tempfile
try :
import igraph
has_igraph = True
except ImportError :
has_igraph = False
test_tree = 'SuchTree/tests/test.tree'
dpt = Tree.get( file=open(test_tree), schema='newick' )
dpt.resolve_polytomies()
N = 0
for n,node in enumerate( dpt.inorder_node_iter() ) :
node.label = n
if node.taxon :
N += 1
# gopher/louse dataset
gopher_tree = 'SuchTree/tests/gopher.tree'
lice_tree = 'SuchTree/tests/lice.tree'
gl_links = 'SuchTree/tests/links.csv'
def test_init_link_by_name() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
assert type(SLT) == SuchLinkedTrees
def test_init_link_by_id() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
assert type(SLT) == SuchLinkedTrees
def test_init_one_tree_by_file() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( test_tree, T, links )
assert type(SLT) == SuchLinkedTrees
def test_init_both_trees_by_file() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( test_tree, test_tree, links )
assert type(SLT) == SuchLinkedTrees
# test properties
def test_col_names() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
assert SLT.col_names == list(T.leafs.keys())
def test_row_names() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
assert SLT.row_names == list(T.leafs.keys())
def test_col_ids() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
col_ids = SLT.col_ids
leaf_ids = T.leafs.values()
assert len(col_ids) == len(leaf_ids)
for i,j in zip( col_ids, leaf_ids ) :
assert i == j
def test_row_ids() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
row_ids = SLT.row_ids
leaf_ids = T.leafs.values()
assert len(row_ids) == len(leaf_ids)
for i,j in zip( row_ids, leaf_ids ) :
assert i == j
def test_n_cols() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
assert SLT.n_cols == T.n_leafs
def test_n_rows() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
assert SLT.n_rows == T.n_leafs
def test_get_column_leafs() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
for n,colname in enumerate( links.columns ) :
s = links.applymap(bool)[ colname ]
leafs1 = set( map( lambda x : T.leafs[x], s[ s > 0 ].index ) )
leafs2 = set( SLT.get_column_leafs(n) )
assert leafs1 == leafs2
def test_get_column_leafs_by_name() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
for colname in links.columns :
s = links.applymap(bool)[ colname ]
leafs1 = set( map( lambda x : T.leafs[x], s[ s > 0 ].index ) )
#print( colname )
leafs2 = set( SLT.get_column_leafs( colname ) )
assert leafs1 == leafs2
def test_get_column_leafs_as_row_ids() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
for n,colname in enumerate( links.columns ) :
s = links.applymap(bool)[ colname ]
leafs1 = set( map( list(SLT.col_ids).index, map( lambda x : T.leafs[x], s[ s > 0 ].index ) ) )
leafs2 = set( SLT.get_column_leafs(n, as_row_ids=True) )
assert leafs1 == leafs2
def test_get_column_leafs_by_name_as_row_ids() :
T = SuchTree( test_tree )
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=list(T.leafs.keys()) )
SLT = SuchLinkedTrees( T, T, links )
for colname in links.columns :
s = links.applymap(bool)[ colname ]
leafs1 = set( map( list(SLT.col_ids).index, map( lambda x : T.leafs[x], s[ s > 0 ].index ) ) )
leafs2 = set( SLT.get_column_leafs( colname, as_row_ids=True ) )
assert leafs1 == leafs2
def test_get_column_links() :
T = SuchTree( test_tree )
row_names = list(T.leafs.keys())
numpy.random.shuffle(row_names)
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=row_names )
SLT = SuchLinkedTrees( T, T, links )
for n,colname in enumerate( links.columns ) :
s = links.applymap(bool)[ colname ]
c = SLT.get_column_links(n)
for m,rowname in enumerate( SLT.row_names ) :
assert s[rowname] == c[m]
def test_linkmatrix_property() :
T = SuchTree( test_tree )
row_names = list(T.leafs.keys())
numpy.random.shuffle(row_names)
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=row_names )
SLT = SuchLinkedTrees( T, T, links )
for col in SLT.col_names :
for row in SLT.row_names :
col_id = SLT.col_names.index(col)
row_id = SLT.row_names.index(row)
assert bool(links.T[row][col]) == SLT.linkmatrix[row_id][col_id]
def test_linklist_property() :
T = SuchTree( test_tree )
row_names = list(T.leafs.keys())
numpy.random.shuffle(row_names)
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=row_names )
SLT = SuchLinkedTrees( T, T, links )
l = links.unstack()
A = set(map( lambda x : (SLT.TreeB.leafs[x[0]], SLT.TreeA.leafs[x[1]]),
list( l[l>0].index ) ))
B = set(map( lambda x : (x[0], x[1]), SLT.linklist ) )
assert A == B
def test_link_identities() :
with tempfile.NamedTemporaryFile() as f1 :
f1.file.write( b'(A:1,(B:1,(C:1,D:1)E:1)F:1)G:1;' )
f1.file.close()
T1 = SuchTree( f1.name )
with tempfile.NamedTemporaryFile() as f2 :
f2.file.write( b'((a:1,b:1)e:1,(c:1,d:1)f:1)g:1;' )
f2.file.close()
T2 = SuchTree( f2.name )
ll = ( ('A','a'), ('B','c'), ('B','d'), ('C','d'), ('D','d') )
links = pd.DataFrame( numpy.zeros( (4,4), dtype=int ),
index=list(T1.leafs.keys()),
columns=list(T2.leafs.keys()) )
for i,j in ll :
links.at[i,j] = 1
SLT = SuchLinkedTrees( T1, T2, links )
t1_sfeal = dict( zip( T1.leafs.values(), T1.leafs.keys() ) )
t2_sfeal = dict( zip( T2.leafs.values(), T2.leafs.keys() ) )
lll = set( (t1_sfeal[j], t2_sfeal[i] ) for i,j in SLT.linklist.tolist() )
assert set(ll) == lll
# test subsetting
def test_subset_a() :
T = SuchTree( test_tree )
row_names = list(T.leafs.keys())
numpy.random.shuffle(row_names)
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=row_names )
SLT = SuchLinkedTrees( T, T, links )
sfeal = dict( zip( SLT.TreeA.leafs.values(), SLT.TreeA.leafs.keys() ) )
subset_links = links.loc[ list(map( lambda x: sfeal[x], SLT.TreeA.get_leafs(1) )) ]
l = subset_links.unstack()
SLT.subset_a(1)
A = set(map( lambda x : (SLT.TreeB.leafs[x[0]], SLT.TreeA.leafs[x[1]]),
list( l[l>0].index ) ))
B = set(map( lambda x : (x[0], x[1]), SLT.linklist ) )
assert A == B
def test_subset_b() :
T = SuchTree( test_tree )
row_names = list(T.leafs.keys())
numpy.random.shuffle(row_names)
links = pd.DataFrame( numpy.random.random_integers( 0, 3, size=(N,N)),
columns=list(T.leafs.keys()),
index=row_names )
SLT = SuchLinkedTrees( T, T, links )
sfeal = dict( zip( SLT.TreeB.leafs.values(), SLT.TreeB.leafs.keys() ) )
subset_links = links[ list(map( lambda x: sfeal[x], SLT.TreeB.get_leafs(1) )) ]
l = subset_links.unstack()
SLT.subset_b(1)
A = set(map( lambda x : (SLT.TreeB.leafs[x[0]], SLT.TreeA.leafs[x[1]]),
list( l[l>0].index ) ))
B = set(map( lambda x : (x[0], x[1]), SLT.linklist ) )
assert A == B
# test igraph output
@pytest.mark.skipif(not has_igraph, reason="igraph not installed")
def test_to_igraph() :
#Make sure the igraph output has correct same structure
T1 = SuchTree( gopher_tree )
T2 = SuchTree( lice_tree )
links = pd.read_csv( gl_links, index_col=0 )
SLT = SuchLinkedTrees( T1, T2, links )
g = SLT.to_igraph()
# igraph returns an unweighted adjacency matrix,
# so we'll convert SuchLinkedTrees weighted
# adjacency matrix to an unweighted form.
saj = numpy.ceil( SLT.adjacency() )
# For some reason, igraph invented its own Matrix
# class that doesn't implement a standard numpy
# interface. :-/
iaj = numpy.array( list( map( list, g.get_adjacency() ) ) )
# matrixes must be the same shape
assert saj.shape == iaj.shape
# all matrix elements must be equal
assert reduce( lambda a,b:a and b, (saj == iaj).flatten() )
| bsd-3-clause |
Garethp/php-ews | src/API/Enumeration/IdFormatType.php | 533 | <?php
/**
* Contains \garethp\ews\API\Enumeration\IdFormatType.
*/
namespace garethp\ews\API\Enumeration;
use garethp\ews\API\Enumeration;
/**
* Class representing IdFormatType
*
* Surfaces the various id types that are supported for conversion
* XSD Type: IdFormatType
*/
class IdFormatType extends Enumeration
{
const ENTRY_ID = 'EntryId';
const EWS_ID = 'EwsId';
const EWS_LEGACY_ID = 'EwsLegacyId';
const HEX_ENTRY_ID = 'HexEntryId';
const OWA_ID = 'OwaId';
const STORE_ID = 'StoreId';
}
| bsd-3-clause |
yreynhout/Projac | src/Projac.SqlClient.Tests/Legacy/TSqlTests.NonQueryProcedure.cs | 20549 | using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using NUnit.Framework;
using Projac.Sql.Tests.SqlClient;
using Projac.SqlClient.Legacy;
namespace Projac.Sql.Tests.Legacy
{
public partial class TSqlTests
{
[TestCaseSource("NonQueryProcedureCases")]
public void NonQueryProcedureReturnsExpectedInstance(SqlNonQueryCommand actual, SqlNonQueryCommand expected)
{
Assert.That(actual.Text, Is.EqualTo(expected.Text));
Assert.That(actual.Parameters, Is.EquivalentTo(expected.Parameters).Using(new SqlParameterEqualityComparer()));
}
private static IEnumerable<TestCaseData> NonQueryProcedureCases()
{
yield return new TestCaseData(
TSql.NonQueryProcedure("text"),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
TSql.NonQueryProcedure("text", parameters: null),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
TSql.NonQueryProcedure("text", new { }),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
TSql.NonQueryProcedure("text", new { Parameter = new SqlParameterValueStub() }),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
TSql.NonQueryProcedure("text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.StoredProcedure));
}
[TestCaseSource("NonQueryProcedureIfCases")]
public void NonQueryProcedureIfReturnsExpectedInstance(IEnumerable<SqlNonQueryCommand> actual, SqlNonQueryCommand[] expected)
{
var actualArray = actual.ToArray();
Assert.That(actualArray.Length, Is.EqualTo(expected.Length));
for (var index = 0; index < actualArray.Length; index++)
{
Assert.That(actualArray[index].Text, Is.EqualTo(expected[index].Text));
Assert.That(actualArray[index].Parameters, Is.EquivalentTo(expected[index].Parameters).Using(new SqlParameterEqualityComparer()));
}
}
private static IEnumerable<TestCaseData> NonQueryProcedureIfCases()
{
yield return new TestCaseData(
TSql.NonQueryProcedureIf(true, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureIf(true, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureIf(true, "text", new { }),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureIf(true, "text", new { Parameter = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureIf(true, "text",
new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureIf(false, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureIf(false, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureIf(false, "text", new { }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureIf(false, "text", new { Parameter = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureIf(false, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
}
[TestCaseSource("NonQueryProcedureUnlessCases")]
public void NonQueryProcedureUnlessReturnsExpectedInstance(IEnumerable<SqlNonQueryCommand> actual, SqlNonQueryCommand[] expected)
{
var actualArray = actual.ToArray();
Assert.That(actualArray.Length, Is.EqualTo(expected.Length));
for (var index = 0; index < actualArray.Length; index++)
{
Assert.That(actualArray[index].Text, Is.EqualTo(expected[index].Text));
Assert.That(actualArray[index].Parameters, Is.EquivalentTo(expected[index].Parameters).Using(new SqlParameterEqualityComparer()));
}
}
private static IEnumerable<TestCaseData> NonQueryProcedureUnlessCases()
{
yield return new TestCaseData(
TSql.NonQueryProcedureUnless(false, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureUnless(false, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureUnless(false, "text", new { }),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureUnless(false, "text", new { Parameter = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureUnless(false, "text",
new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@Parameter1"),
new SqlParameterValueStub().ToDbParameter("@Parameter2")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureUnless(true, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureUnless(true, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureUnless(true, "text", new { }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureUnless(true, "text", new { Parameter = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureUnless(true, "text", new { Parameter1 = new SqlParameterValueStub(), Parameter2 = new SqlParameterValueStub() }),
new SqlNonQueryCommand[0]);
}
[TestCaseSource("NonQueryProcedureFormatCases")]
public void NonQueryProcedureFormatReturnsExpectedInstance(SqlNonQueryCommand actual, SqlNonQueryCommand expected)
{
Assert.That(actual.Text, Is.EqualTo(expected.Text));
Assert.That(actual.Parameters, Is.EquivalentTo(expected.Parameters).Using(new SqlParameterEqualityComparer()));
}
private static IEnumerable<TestCaseData> NonQueryProcedureFormatCases()
{
yield return new TestCaseData(
TSql.NonQueryProcedureFormat("text"),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
TSql.NonQueryProcedureFormat("text", parameters: null),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
TSql.NonQueryProcedureFormat("text", new IDbParameterValue[0]),
new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure));
yield return new TestCaseData(
TSql.NonQueryProcedureFormat("text", new SqlParameterValueStub()),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
TSql.NonQueryProcedureFormat("text {0}", new SqlParameterValueStub()),
new SqlNonQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
TSql.NonQueryProcedureFormat("text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure));
yield return new TestCaseData(
TSql.NonQueryProcedureFormat("text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure));
}
[TestCaseSource("NonQueryProcedureFormatIfCases")]
public void NonQueryProcedureFormatIfReturnsExpectedInstance(IEnumerable<SqlNonQueryCommand> actual, SqlNonQueryCommand[] expected)
{
var actualArray = actual.ToArray();
Assert.That(actualArray.Length, Is.EqualTo(expected.Length));
for (var index = 0; index < actualArray.Length; index++)
{
Assert.That(actualArray[index].Text, Is.EqualTo(expected[index].Text));
Assert.That(actualArray[index].Parameters, Is.EquivalentTo(expected[index].Parameters).Using(new SqlParameterEqualityComparer()));
}
}
private static IEnumerable<TestCaseData> NonQueryProcedureFormatIfCases()
{
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(true, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(true, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(true, "text", new IDbParameterValue[0]),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(true, "text", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(true, "text {0}", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(false, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(false, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(false, "text", new IDbParameterValue[0]),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(false, "text", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(false, "text {0}", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatIf(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
}
[TestCaseSource("NonQueryProcedureFormatUnlessCases")]
public void NonQueryProcedureFormatUnlessReturnsExpectedInstance(IEnumerable<SqlNonQueryCommand> actual, SqlNonQueryCommand[] expected)
{
var actualArray = actual.ToArray();
Assert.That(actualArray.Length, Is.EqualTo(expected.Length));
for (var index = 0; index < actualArray.Length; index++)
{
Assert.That(actualArray[index].Text, Is.EqualTo(expected[index].Text));
Assert.That(actualArray[index].Parameters, Is.EquivalentTo(expected[index].Parameters).Using(new SqlParameterEqualityComparer()));
}
}
private static IEnumerable<TestCaseData> NonQueryProcedureFormatUnlessCases()
{
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(false, "text"),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(false, "text", parameters: null),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(false, "text", new IDbParameterValue[0]),
new[] { new SqlNonQueryCommand("text", new DbParameter[0], CommandType.StoredProcedure) });
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(false, "text", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(false, "text {0}", new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(false, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(false, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new[]
{
new SqlNonQueryCommand("text @P0 @P1", new[]
{
new SqlParameterValueStub().ToDbParameter("@P0"),
new SqlParameterValueStub().ToDbParameter("@P1")
}, CommandType.StoredProcedure)
});
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(true, "text"),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(true, "text", parameters: null),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(true, "text", new IDbParameterValue[0]),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(true, "text", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(true, "text {0}", new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(true, "text", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
yield return new TestCaseData(
TSql.NonQueryProcedureFormatUnless(true, "text {0} {1}", new SqlParameterValueStub(), new SqlParameterValueStub()),
new SqlNonQueryCommand[0]);
}
}
}
| bsd-3-clause |
bigdawg-istc/bigdawg | src/main/java/istc/bigdawg/migration/datatypes/package-info.java | 168 | /**
* Mapping between data types in different databases.
*/
/**
* @author Adam Dziedzic
*
* Feb 24, 2016 12:23:10 PM
*/
package istc.bigdawg.migration.datatypes; | bsd-3-clause |
DestinyVaultHelper/dvh | app/src/main/java/org/swistowski/vaulthelper/Application.java | 1039 | package org.swistowski.vaulthelper;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import org.swistowski.vaulthelper.storage.Data;
import org.swistowski.vaulthelper.util.ImageStorage;
import org.swistowski.vaulthelper.views.ClientWebView;
public class Application extends android.app.Application {
private Tracker mTracker;
private ClientWebView mWebView;
@Override
public void onCreate()
{
mWebView = new ClientWebView(getApplicationContext());
ImageStorage.getInstance().setContext(getApplicationContext());
Data.getInstance().setContext(getApplicationContext());
super.onCreate();
}
public ClientWebView getWebView() {
return mWebView;
}
public synchronized Tracker getTracker() {
if(mTracker==null){
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
mTracker = analytics.newTracker(R.xml.global_tracker);
}
return mTracker;
}
}
| bsd-3-clause |
rapidpro/tracpro | tracpro/contacts/urls.py | 373 | from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from tracpro.utils import is_production
from .views import ContactCRUDL, force_contacts_sync
urlpatterns = ContactCRUDL().as_urlpatterns()
if not is_production():
urlpatterns += [
url(r'^force_contacts_sync/$', force_contacts_sync, name='force_contacts_sync'),
]
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s06/CWE122_Heap_Based_Buffer_Overflow__CWE131_memmove_81a.cpp | 2488 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__CWE131_memmove_81a.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__CWE131.label.xml
Template File: sources-sink-81a.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate memory without using sizeof(int)
* GoodSource: Allocate memory using sizeof(int)
* Sinks: memmove
* BadSink : Copy array to data using memmove()
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__CWE131_memmove_81.h"
namespace CWE122_Heap_Based_Buffer_Overflow__CWE131_memmove_81
{
#ifndef OMITBAD
void bad()
{
int * data;
data = NULL;
/* FLAW: Allocate memory without using sizeof(int) */
data = (int *)malloc(10);
if (data == NULL) {exit(-1);}
const CWE122_Heap_Based_Buffer_Overflow__CWE131_memmove_81_base& baseObject = CWE122_Heap_Based_Buffer_Overflow__CWE131_memmove_81_bad();
baseObject.action(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
int * data;
data = NULL;
/* FIX: Allocate memory using sizeof(int) */
data = (int *)malloc(10*sizeof(int));
if (data == NULL) {exit(-1);}
const CWE122_Heap_Based_Buffer_Overflow__CWE131_memmove_81_base& baseObject = CWE122_Heap_Based_Buffer_Overflow__CWE131_memmove_81_goodG2B();
baseObject.action(data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__CWE131_memmove_81; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
ItsmeJulian/dotnect_stack | dotnect_platform/src/tracking_class.cpp | 4333 | // file: tracking_class.cpp, style: README.md
//
// License http://opensource.org/licenses/BSD-3-Clause
// Copyright (c) 2016, ItsmeJulian (github.com/ItsmeJulian)
// All rights reserved.
//
// Get input matrix, filter it_ and do minimum entry search (MES)
// Then project found MES-pixel via intrinsics to 3D point and publish
// Also paint found MES-pixel into image and publish it
//
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
// ros
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <sensor_msgs/image_encodings.h>
// boost
#include <boost/thread/mutex.hpp>
// opencv
#include <opencv2/core/mat.hpp>
// local
#include "data_container.h"
#include "tracking_class.h"
#include "custom_defines.h"
// Subscribe to video topic, advertise 3D point/marker, set kinect intrinsics
TrackingClass::TrackingClass(DataContainer *container) : container_(container), it_(nh_)
{
verbose_ = false;
point_f1_.resize(6);
point_f1_[1] = 15;
// kinect1 intrinsics, adjust fx_,fy_,cx_,cy_ to your camera
fx_ = 5.9421480358642339e+02;
fy_ = 5.9104092248505947e+02;
cx_ = 3.3930546187516956e+02;
cy_ = 2.4273843891390746e+02;
// publish image with point position
pub_img_transport_ = it_.advertise("/dotnect_platform/paint_img", 1);
}
TrackingClass::~TrackingClass()
{
}
// change topic
void TrackingClass::subscribeImgSrc(std::string topic_name)
{
sub_img_transport_ = it_.subscribe(topic_name, 1, &TrackingClass::callbImg, this);
}
// flag to printf pixel position and depth_ value
bool TrackingClass::setVerbose(bool &verbose)
{
this->verbose_ = verbose;
}
// image callback: convert, prepare then MES
void TrackingClass::callbImg(const sensor_msgs::ImageConstPtr &img_ptr)
{
boost::mutex::scoped_lock lock(mtx_);
cv_bridge::CvImagePtr cv_ptr;
try
{
// mutable matrix is needed, so copy
cv_ptr = cv_bridge::toCvCopy(img_ptr, sensor_msgs::image_encodings::TYPE_16UC1);
}
catch (cv_bridge::Exception &e)
{
printf(ACRED NNAME ": %s" ACRESETN, e.what());
return;
}
// get pointer directly to cv::Mat member
cv::Mat *mat_ptr = &(cv_ptr->image);
// push 0-entries into background having 4000mm along z_-axis (camera depth maximum)
// layout for img_ptr, cv_ptr, mat_ptr and mat_CV8UC1_;
// mat_CV8UC1_flip_ inverts the horizontal direction
// ________ j,u
// |
// | x__.
// i,v | |
// | y
ushort *p_row;
// speed: first row, then column
for (int i = 0; i < mat_ptr->rows; ++i)
{
p_row = mat_ptr->ptr<ushort>(i);
for (int j = 0; j < mat_ptr->cols; ++j)
{
if (p_row[j] == 0)
p_row[j] = 4000;
}
}
// precaution blur
blur(*mat_ptr, *mat_ptr, cv::Size(3, 3));
// find minimum = closest point, MES
depth_ = mat_ptr->at<ushort>(0, 0);
for (int i = 0; i < mat_ptr->rows; ++i)
{
p_row = mat_ptr->ptr<ushort>(i);
for (int j = 0; j < mat_ptr->cols; ++j)
{
if (p_row[j] < depth_)
{
u_ = j;
v_ = i;
depth_ = p_row[j];
}
}
}
// pinhole model to project into camera-kosy [mm] (plumb_bob)
// http://wiki.ros.org/image_pipeline/CameraInfo
x_ = (u_ - cx_) / fx_ * depth_;
y_ = (v_ - cy_) / fy_ * depth_;
z_ = double(depth_);
// send to container
point_f1_[0] = ros::Time::now().toNSec();
point_f1_[2] = cv_ptr->header.seq;
point_f1_[3] = x_;
point_f1_[4] = y_;
point_f1_[5] = z_;
container_->setVec(point_f1_);
// option to output pixel position
if (verbose_)
{
printf(NNAME ": x:%f y:%f z:%f; px u:%d v:%d d:%d\n", x_, y_, z_, u_, v_, depth_);
}
// convert to greyscale cv::Mat with 8-Bit depth_, (max - min)
(*mat_ptr).convertTo(mat_CV8UC1_, CV_8UC1, 255. / (2500 - 0), 0);
cv::flip(mat_CV8UC1_, mat_CV8UC1_flip_, 1);
// paint black and white point into image
cv::circle(mat_CV8UC1_flip_, cv::Point(mat_CV8UC1_flip_.cols - 1 - u_, v_), 9, cv::Scalar(0, 0, 0), CV_FILLED, 8, 0);
cv::circle(mat_CV8UC1_flip_, cv::Point(mat_CV8UC1_flip_.cols - 1 - u_, v_), 5, cv::Scalar(255, 255, 255), 3, 8, 0);
// output modified video stream
pub_img_transport_.publish(
cv_bridge::CvImage((*cv_ptr).header, sensor_msgs::image_encodings::TYPE_8UC1, mat_CV8UC1_flip_).toImageMsg());
}
// EOF
| bsd-3-clause |
MwanzanFelipe/rockletonfortune | zillions/migrations/0001_initial.py | 6981 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-07 21:44
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='BckGrnd_Clcs',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('last_week_updated', models.IntegerField()),
('date_updated', models.DateField(verbose_name='Date of ReUp')),
],
),
migrations.CreateModel(
name='Budget',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.DecimalField(decimal_places=2, max_digits=7)),
('ed_perc', models.DecimalField(decimal_places=2, max_digits=5)),
('time_period', models.CharField(choices=[('WE', 'Weekly'), ('MO', 'Monthly')], default='WE', max_length=2)),
],
),
migrations.CreateModel(
name='Primary_Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30, verbose_name='Category Name')),
],
),
migrations.CreateModel(
name='Primary_Category_Bucket',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=15, verbose_name='Category Name')),
],
),
migrations.CreateModel(
name='Rockleton',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_of_birth', models.DateField()),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Secondary_Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30, verbose_name='Category Name')),
('primary_category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zillions.Primary_Category')),
],
),
migrations.CreateModel(
name='Source',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=20, verbose_name='Source Name')),
],
),
migrations.CreateModel(
name='Source_Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=15, verbose_name='Category Name')),
],
),
migrations.CreateModel(
name='Transaction',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('transaction_date', models.DateField(verbose_name='Transaction Date')),
('description', models.CharField(max_length=60, verbose_name='Description')),
('original_description', models.CharField(blank=True, max_length=170, null=True, verbose_name='Original Description')),
('amount', models.DecimalField(decimal_places=4, max_digits=9)),
('transaction_type', models.IntegerField(choices=[(-1, 'debit'), (1, 'credit')])),
('ed_perc', models.DecimalField(decimal_places=2, max_digits=5)),
('notes', models.TextField(blank=True, verbose_name='Notes')),
('alias', models.CharField(blank=True, max_length=60, verbose_name='Alias')),
('mint_import', models.BooleanField(default=True)),
('internal_transfer', models.BooleanField(default=False)),
('flagged', models.BooleanField(default=False)),
('secondary_category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zillions.Secondary_Category')),
('source', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zillions.Source')),
],
options={
'ordering': ('-transaction_date',),
},
),
migrations.CreateModel(
name='Transaction_Import',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('transaction_date', models.DateField(verbose_name='Transaction Date')),
('description', models.CharField(max_length=60, verbose_name='Description')),
('original_description', models.CharField(blank=True, max_length=170, null=True, verbose_name='Original Description')),
('amount', models.DecimalField(decimal_places=4, max_digits=9)),
('transaction_type', models.IntegerField(choices=[(-1, 'debit'), (1, 'credit')])),
('secondary_category', models.CharField(max_length=60, verbose_name='Secondary Category')),
('source', models.CharField(max_length=60, verbose_name='Source')),
],
options={
'ordering': ('-transaction_date',),
},
),
migrations.AddField(
model_name='source',
name='category',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zillions.Source_Category'),
),
migrations.AddField(
model_name='primary_category',
name='category',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zillions.Primary_Category_Bucket'),
),
migrations.AddField(
model_name='budget',
name='secondary_category',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zillions.Secondary_Category'),
),
migrations.AddField(
model_name='budget',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zillions.Rockleton'),
),
migrations.AlterUniqueTogether(
name='budget',
unique_together=set([('user', 'secondary_category')]),
),
]
| bsd-3-clause |
shenningting/sixGroup | views/account/show.php | 3287 | <?php
use yii\widgets\LinkPager;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/common.css">
<link rel="stylesheet" href="css/main.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/colResizable-1.3.min.js"></script>
<script type="text/javascript" src="js/common.js"></script>
<style>
tr{
margin-top:100px;
}
</style>
<script type="text/javascript">
/*$(function () {
$(".list_table").colResizable({
liveDrag: true,
gripInnerHtml: "<div class='grip'></div>",
draggingClass: "dragging",
minWidth: 30
});
});*/
</script>
</head>
<body>
<div id="table" class="mt10" style="margin-top: 30px">
<div class="box span10 oh">
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="list_table">
<tr>
<th width="200">昵称</th>
<th width="500">Api地址</th>
<th width="300">Token</th>
<th width="200">操作</th>
</tr>
<?php foreach($account_data as $k=>$v){?>
<tr class="tr">
<td align="center"><?php echo $v['aname']?></td>
<td>
<input type="text" id="content2_<?php echo $k?>" value="<?php echo $v['aurl']?>"/>
<button class="btn btn82 btn_nochecked" onclick="copy2(<?php echo $k?>)">复制</button>
</td>
<td>
<input type="text" id="content1_<?php echo $k?>" value="<?php echo $v['atoken']?>"/>
<span style="margin-left: 0" ><input type="button" name="button" onclick="copy1(<?php echo $k?>)" class="btn btn82 btn_nochecked" value="复制"></span>
</td>
<td>
<a href="index.php?r=account/del&aid=<?php echo $v['aid']?>"><input type="button" name="button" class="btn btn82 btn_del" value="删除"></a>
<a href="index.php?r=account/edit&aid=<?php echo $v['aid']?>"><input type="button" name="button" class="btn btn82 btn_add" value="修改"></a>
</td>
</tr>
<?php }?>
</table>
<div class="page mt10">
<div class="pagination">
<ul>
<?= LinkPager::widget(['pagination' => $pagination]) ?>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
<script src="js/jq.js"></script>
<script>
function copy1(k)
{
var Url=document.getElementById("content1_"+k);
//alert(Url);
Url.select(); // 选择对象
document.execCommand("Copy"); // 执行浏览器复制命令
alert("已复制好,可贴粘。");
}
function copy2(k)
{
var Url=document.getElementById("content2_"+k);
Url.select(); // 选择对象
document.execCommand("Copy"); // 执行浏览器复制命令
alert("已复制好,可贴粘。");
}
</script> | bsd-3-clause |
wajatmaka/Web-Kepegawaian | operator/daftar.php | 38901 | <?php
require_once('../lib/auth.php');
require_once('../lib/conn.php');
require_once('../lib/liboperator.php');
auth('operator');
$inpt=($_SESSION['priv']=='input')?true:false;
$nip=false;
$daftarpegawai=array();
if(!empty($_GET['nip'])){
$nip=$_GET['nip'];
$dp=getDataPegawai($nip);
if($dp){
$daftarseksi=getDaftarSeksiByUnitKerja($dp['id_unit_kerja']);
$daftarjabatan=getDaftarJabatanBySUK($dp['id_unit_kerja'],$dp['seksi']);
$daftarhobi=getDaftarHobiPeg($dp['id_pegawai']);
$daftarpendidikan=getDaftarPendidikanPeg($dp['id_pegawai']);
$daftarpelatihan=getDaftarPelatihanPeg($dp['id_pegawai']);
$daftardiklatpeg=getDaftarDiklatPeg($dp['id_pegawai']);
$daftarkepangkatan=getDaftarKepangkatanPeg($dp['id_pegawai']);
$daftarpengalaman=getDaftarPengalamanPeg($dp['id_pegawai']);
$daftarpenghargaan=getDaftarPenghargaanPeg($dp['id_pegawai']);
$daftarkunjungan=getDaftarKunjunganPeg($dp['id_pegawai']);
$daftarseminar=getDaftarSeminarPeg($dp['id_pegawai']);
$daftarpasangan=getDaftarPasanganPeg($dp['id_pegawai']);
$daftaranak=getDaftarAnakPeg($dp['id_pegawai']);
$daftarortu=getDaftarOrtuPeg($dp['id_pegawai']);
$daftarmertua=getDaftarMertuaPeg($dp['id_pegawai']);
$daftarsaudara=getDaftarSaudaraPeg($dp['id_pegawai']);
$daftaripar=getDaftarIparPeg($dp['id_pegawai']);
$daftarorgsma=getDaftarOrgSMAPeg($dp['id_pegawai']);
$daftarorgpt=getDaftarOrgPTPeg($dp['id_pegawai']);
$daftarorgkerja=getDaftarOrgKerjaPeg($dp['id_pegawai']);
$tmt=getTglMulaiTerhitung($dp['id_pegawai']);
$tglcpns=getTglCPNS($dp['id_pegawai']);
$tglpns=getTglPNS($dp['id_pegawai']);
$masakerjagolongan=getMasaKerjaGolongan($dp['id_pegawai']);
$masakerjatotal=getTotalMasaKerja($dp['id_pegawai']);
$pnd_terakhir=getPendidikanTerakhir($dp['id_pegawai']);
}
}else{
$daftarunitkerja=getListKat('c.nama');
$baris=10;
if(!empty($_GET['page'])){
$page=$_GET['page'];
}else{
$page=1;
}
if(!empty($_GET['filter'])){
$filter=$_GET['filter'];
}else{
$filter='';
}
$tmp=getDaftarPegawai($baris,$page,$filter);
$daftarpegawai=$tmp['hasil'];
$jml=$tmp['jml'];
$jmlhlm=ceil($jml/$baris);
}
function cetakPage($halaman,$jml){
?>
<ul>
<li><span>Halaman</span></li>
<?
for($i=1;$i<=$jml;$i++):
if($i==$halaman){
echo "<li><span>$i</span></li>";
}else{
if(!empty($_GET['filter'])){
echo "<li><a href=\"?page=$i&filter=".urlencode($_GET['filter'])."\">$i</a></li>";
}else{
echo "<li><a href=\"?page=$i\">$i</a></li>";
}
}
endfor;
?>
</ul>
<?php
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Data Kepegawaian BBPPK - Lembang Jawa Barat</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<link type="text/css" href="../css/gaya.css" rel="stylesheet" media="screen"/>
<link type="text/css" href="../css/cetak.css" rel="stylesheet" media="print"/>
<style type="text/css">
#infohasil{
background:#f8fafb;
padding:7px;
color:#081e25;
-moz-border-radius-topleft: 10px;
-moz-border-radius-topright: 10px;
-moz-border-radius-bottomright: 0px;
-moz-border-radius-bottomleft: 0px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 10px;
-webkit-border-bottom-left-radius: 0px;
-webkit-border-bottom-right-radius: 0px;
margin-bottom:0;
text-shadow: 2px 2px 5px #bae9ff;
}
#infohasil a{
text-decoration:underline;
word-spacing:0.1em;
}
#infohasil a:hover{
color:#081e25;
font-weight:800;
}
form label{
color:#555;
font-size:1em;
display:block;
margin:10px 0 0;
}
.read{
position:relative;
display:inline;
color:#222;
font-size:1.2em;
font-weight:800;
}
#page{
margin:15px 0 0;
}
#page ul{
list-style:none;
margin:0;
padding:0;
}
#page ul li{
display:inline;
}
#page ul li a{
background:#b6d7e7;
padding:3px 6px;
margin:2px 3px;
border:1px solid #69a4c0;
color:#1a5672;
}
#page ul li a:hover{
font-weight:800;
background:#6ca9c6;
}
#page ul li a:visited{
color:#1a5672;
}
#page ul li span{
padding:3px 6px;
background:#f1f7f9;
font-weight:800;
margin:2px 3px;
border:1px solid #f8f8f8;
}
hr{
border:none;
width:100%;
border-top:2px solid #f8f8f8;
margin:30px 0 0;
}
</style>
</head>
<body>
<div id="pnlpesan"><p id="isipesan">ini pesan dari aplikasi ini</p> <p><a href="#" class="close">tutup</a></p></div>
<div id="wrapper">
<div id="header">
<img src="../img/logo2.png" width="30%" height="*"/>
<p>Data Kepegawaian BBPPK - Lembang Jawa Barat</p>
<p class="desc">Operator<sub>(<?php echo $_SESSION['priv']; ?>)</sub></p>
</div>
<div id="content">
<div id="menu">
<ul>
<li><a href="index.php">Home</a></li>
<?php if($_SESSION['priv']=='input'):?>
<li><a href="input.php">Input</a></li>
<li><a href="edit.php">Edit</a></li>
<li><a href="upload.php">Upload Foto</a></li>
<?php endif;?>
<li><div>Daftar</div></li>
<li><a href="cari.php">Cari</a></li>
<li><a href="laporan.php">Laporan</a></li>
<li><a href="statistik.php">Statistik</a><li>
<li><a id="logout" href="../login.php?a=logout">Logout</a></li>
</ul>
</div>
<div id="isi">
<?if(!$nip):?>
<h2>Daftar Pegawai</h2>
<?if(empty($_GET['filter'])):?>
<form id="formfilter" action="daftar.php" method="GET">
<fieldset>
<legend>Kategori</legend>
<input type="hidden" name="filter" id="filter"/>
<div class="cond">
<select name="kat" class="kat">
<option value="c.nama">Unit Kerja</option>
<option value="d.golongan">Golongan</option>
<option value="b.eselon">Eselon</option>
<option value="b.seksi">Seksi</option>
<option value="a.tempat_lahir">Tempat Lahir</option>
<option value="a.jk">Jenis Kelamin</option>
<option value="a.status">Status</option>
<option value="a.status_kawin">Status Perkawinan</option>
<option value="a.agama">Agama</option>
</select>
<select name="op" class="op">
<option value="=">Samadengan</option>
<option value="!=">Tidak samadengan</option>
</select>
<select name="nilai" class="nilai">
<?php foreach($daftarunitkerja as $brs):?>
<option value="'<?php echo $brs['nama'];?>'"><?php echo $brs['nama'];?></option>
<?php endforeach;?>
</select>
</div>
<input type="button" id="tambah" class="tombol" value="Tambah" />
<hr/>
<input type="submit" id="kirim" value="Filter" class="tombol"/>
</fieldset>
</form>
<?endif?>
<p id="infohasil">
<?=$jml?> data pegawai
<?if(!empty($filter)):?>
[<?=explainQuery($_GET['filter'])?>]
<a href="daftar.php">«reset filter</a>
<?if($jml&&$_SESSION['priv']=='input'):?>
<a href="export.php?filter=<?=$_GET['filter']?>">export ke excel</a>
<?endif;?>
<?elseif($jml&&$_SESSION['priv']=='input'):?>
<a href="export.php">export ke excel</a>
<?endif?>
</p>
<table id="daftarpegawai">
<thead>
<tr><th>NIP</th><th>Nama</th><th>Jabatan</th><th>Seksi</th><th>Unit Kerja</th><th>Status</th><th>Keterangan</th></tr>
</thead>
<tbody>
<?foreach($daftarpegawai as $brs):?>
<tr>
<td><a href="?nip=<?=$brs['nip']?>"><?=$brs['nip']?></a> <?if($inpt):?><br/><a href="edit.php?snip=<?=$brs['nip']?>">Edit</a><?endif;?></td>
<td><?=$brs['nama']?></td>
<td><?=$brs['jabatan']?></td><td><?=$brs['seksi']?></td>
<td><?=$brs['nama_unit_kerja']?></td><td><?=$brs['status']?></td>
<td><?=$brs['keterangan']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
<div id="page">
<?cetakPage($page,$jmlhlm);?>
</div>
<br><br>
<?else:?>
<h2>Detail Pegawai <?=$nip?> <a href="daftar.php" class="tombol">«Kembali</a>
<a href="#" id="cetak" class="tombol">Cetak</a>
<?if($_SESSION['priv']=='input'):?>
<a href="report/drh.php?nip=<?=$nip?>" class="tombol">Export</a>
<?endif;?>
</h2>
<form>
<fieldset>
<img id="foto" src="../lib/gambar.php?nip=<?=$nip?>" width="200" height="300" />
<label for="nip">NIP</label><div id="nip" class="read"><?=$nip?></div>
<label for="nmlengkap">Nama Lengkap</label><div id="nmlengkap" class="read"><?=$dp['nama']?></div>
<label for="golongan">Golongan</label><div id="golongan" class="read"><?php echo $dp['golongan']." ".$dp['ket'];?></div>
<label for="tmt_jabatan">TMT</label><div id="tmt_jabatan" class="read"><?=$tmt?></div>
<label for="mk_golongan">Masa Kerja Golongan</label><div id="mk_golongan" class="read"><?=$masakerjagolongan?></div>
<label for="total_mk">Total Masa Kerja</label><div id="total_mk" class="read"><?=$masakerjatotal?></div>
<label for="ttl">Tempat Tanggal Lahir</label><div id="ttl" class="read"><?=$dp['tempat_lahir']?>, <?=$dp['tgl_lahir']?></div>
<label for="agama">Agama</label><div id="agama" class="read"><?=$dp['agama']?></div>
<label for="jk">Jenis Kelamin</label><div id="jk" class="read"><? echo ($dp['jk']=='P')?'Pria':'Wanita';?></div>
<br>
<label for="cpns">CPNS</label><div id="cpns" class="read"><?=$tglcpns?></div>
<label for="pns">PNS</label><div id="pns" class="read"><?=$tglpns?></div>
<label for="unitkerja">Unit Kerja</label><div id="unitkerja" class="read"><?=$dp['nama_unit_kerja']?></div>
<label for="seksi">Seksi</label><div id="seksi" class="read"><?=$dp['seksi']?></div>
<label for="jabatan">Jabatan</label><div id="jabatan" class="read"><?=$dp['jabatan']?></div>
<label for="pnd_terakhir">Pendidikan terakhir</label><div id="pnd_terakhir" class="read"><?if(!empty($pnd_terakhir)):?><?=$pnd_terakhir['tingkat']?> <?=$pnd_terakhir['jurusan']?> <?=$pnd_terakhir['nama']?> <?=$pnd_terakhir['tahun']?> <?=$pnd_terakhir['tempat']?><?endif;?></div>
<br>
<label for="alamat">Alamat</label><div id="alamat" class="read"><?=$dp['jalan']?> <?=$dp['kelurahan']?> <?=$dp['kecamatan']?></div>
<label for="kab">Kabupaten</label><div id="kab" class="read"><?=$dp['kabupaten']?></div>
<label for="propinsi">Propinsi</label><div id="propinsi" class="read"><?=$dp['propinsi']?></div>
<label for="kodepos">Kode Pos</label><div id="kodepos" class="read"><?=$dp['kode_pos']?></div>
<br>
<label for="status">Status</label><div id="status" class="read"><?=$dp['status']?></div>
<label for="statuskawin">Status Pernikahan</label><div id="statuskawin" class="read"><?=$dp['status_kawin']?></div>
<label for="keterangan">Keterangan</label><div id="keterangan" class="read"><?=$dp['keterangan']?></div>
<label for="notelp">Nomor Telp.</label><div id="notelp" class="read"><?=$dp['notelp']?></div>
<br>
<label for="daftarpendidikan">Pendidikan Formal</label>
<table id="daftarpendidikan">
<thead>
<tr><th>Tingkat</th><th>Nama</th><th>Jurusan</th><th>No Ijazah</th><th>Tahun</th><th>Tempat</th><th>KepSek/Dekan</th></tr>
</thead>
<tbody>
<?foreach($daftarpendidikan as $brs):?>
<tr>
<td><input type="hidden" name="atingkat_pndd[]" value="<?=$brs['tingkat']?>" ><?=$brs['tingkat']?></td>
<td><input type="hidden" name="anm_pndd[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="ajurusan_pndd[]" value="<?=$brs['jurusan']?>" ><?=$brs['jurusan']?></td>
<td><input type="hidden" name="anoijazah_pndd[]" value="<?=$brs['no_ijazah']?>" ><?=$brs['no_ijazah']?></td>
<td><input type="hidden" name="athn_pndd[]" value="<?=$brs['tahun']?>" ><?=$brs['tahun']?></td>
<td><input type="hidden" name="atmp_pndd[]" value="<?=$brs['tempat']?>" ><?=$brs['tempat']?></td>
<td><input type="hidden" name="akepsek_pndd[]" value="<?=$brs['kepsek']?>" ><?=$brs['kepsek']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
<br>
<label for="nonformal">Pendidikan Non Formal</label>
<label for="pelatihan">Daftar Pelatihan</label>
<table id="daftarpelatihan">
<thead>
<tr><th>Nama Pelatihan</th><th>Tanggal<br/>Mulai</th><th>Tanggal<br/>Selesai</th><th>No Tanda Lulus</th><th>Tempat</th><th>Ket</th></tr>
</thead>
<tbody>
<?foreach($daftarpelatihan as $brs):?>
<tr>
<td><input type="hidden" name="anm_plthn[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="atglawal_plthn[]" value="<?=$brs['tgl_awal']?>" ><?=$brs['tgl_awal']?></td>
<td><input type="hidden" name="atglakhir_plthn[]" value="<?=$brs['tgl_akhir']?>" ><?=$brs['tgl_akhir']?></td>
<td><input type="hidden" name="anobukti_plthn[]" value="<?=$brs['no_tanda_lulus']?>" ><?=$brs['no_tanda_lulus']?></td>
<td><input type="hidden" name="atmp_plthn[]" value="<?=$brs['tempat']?>" ><?=$brs['tempat']?></td>
<td><input type="hidden" name="aket_plthn[]" value="<?=$brs['ket']?>" ><?=$brs['ket']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
<br>
<label for="diklat">Daftar Diklat</label>
<table id="daftardiklat">
<thead>
<tr><th>Jenis<br/>Diklat</th><th>Nama Diklat</th><th>Tanggal<br/>Mulai</th><th>Tanggal<br/>Selesai</th><th>No Tanda Lulus</th><th>Tempat</th><th>Lama (jam)</th><th>Ket</th></tr>
</thead>
<tbody>
<?foreach($daftardiklatpeg as $brs):?>
<tr>
<td><input type="hidden" name="ajns_diklat[]" value="<?=$brs['jenis']?>" ><?=$brs['jenis']?></td>
<td><input type="hidden" name="anm_diklat[]" value="<?=$brs['id_jenis_diklat']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="atglawal_diklat[]" value="<?=$brs['tgl_awal']?>" ><?=$brs['tgl_awal']?></td>
<td><input type="hidden" name="atglakhir_diklat[]" value="<?=$brs['tgl_akhir']?>" ><?=$brs['tgl_akhir']?></td>
<td><input type="hidden" name="anobukti_diklat[]" value="<?=$brs['no_tanda_lulus']?>" ><?=$brs['no_tanda_lulus']?></td>
<td><input type="hidden" name="atmp_diklat[]" value="<?=$brs['tempat']?>" ><?=$brs['tempat']?></td>
<td><input type="hidden" name="alama_diklat[]" value="<?=$brs['lama']?>" ><?=$brs['lama']?></td>
<td><input type="hidden" name="aket_diklat[]" value="<?=$brs['ket']?>" ><?=$brs['ket']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
<br>
<label for="penghargaan">Penghargaan</label>
<table id="daftarpenghargaan">
<thead>
<tr><th>Nama Penghargaan</th><th>Tahun Perolehan</th><th>Pihak Pemberi</th></tr>
</thead>
<tbody>
<?foreach($daftarpenghargaan as $brs):?>
<tr>
<td><input type="hidden" name="anm_penghargaan[]" value="<?=$brs['nama_penghargaan']?>" ><?=$brs['nama_penghargaan']?></td>
<td><input type="hidden" name="athn_penghargaan[]" value="<?=$brs['tahun']?>" ><?=$brs['tahun']?></td>
<td><input type="hidden" name="apemberi_penghargaan[]" value="<?=$brs['pihak_pemberi']?>" ><?=$brs['pihak_pemberi']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<fieldset>
<legend>Riwayat Kepangkatan</legend>
<table id="daftarkepangkatan">
<thead>
<tr><th rowspan=2>Pangkat</th><th rowspan=2>Golongan</th><th rowspan=2>T.M.T</th><th colspan=3 align=center>Surat Keputusan</th><th rowspan=2>Dasar Peraturan</th></tr>
<tr><th>Pejabat</th><th>Nomor</th><th>Tanggal</th></tr>
</thead>
<tbody>
<?foreach($daftarkepangkatan as $brs):?>
<tr>
<td><input type="hidden" name="anm_pangkat[]" value="<?=$brs['pangkat']?>" ><?=$brs['pangkat']?></td>
<td><input type="hidden" name="agolongan_pangkat[]" value="<?=$brs['id_golongan']?>" ><?=$brs['golongan']?> <?=$brs['ket']?></td>
<td><input type="hidden" name="atmt_pangkat[]" value="<?=$brs['tanggal_berlaku']?>" ><?=$brs['tanggal_berlaku']?></td>
<td><input type="hidden" name="ask_pejabat_pangkat[]" value="<?=$brs['sk_pejabat']?>" ><?=$brs['sk_pejabat']?></td>
<td><input type="hidden" name="ask_nomor_pangkat[]" value="<?=$brs['sk_nomor']?>" ><?=$brs['sk_nomor']?></td>
<td><input type="hidden" name="ask_tgl_pangkat[]" value="<?=$brs['sk_tanggal']?>" ><?=$brs['sk_tanggal']?></td>
<td><input type="hidden" name="adasar_pangkat[]" value="<?=$brs['dasar_peraturan']?>" ><?=$brs['dasar_peraturan']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<br>
<?if($inpt):?>
<br>
<fieldset>
<legend>Keterangan Badan dan Kegemaran</legend>
<label for="hobi">Kegemaran (Hobi)</label><div id="hobi" class="read"><? foreach($daftarhobi as $brs):?><?=$brs['hobi']?>, <? endforeach;?></div>
<label for="tinggi">Tinggi Badan</label><div id="tinggi" class="read"><?=$dp['tinggi']?> cm</div>
<label for="berat">Berat Badan</label><div id="berat" class="read"><?=$dp['berat']?> kg</div>
<label for="rambut">Rambut</label><div id="rambut" class="read"><?=$dp['warna_rambut']?></div>
<label for="bentukmuka">Bentuk Muka</label><div id="bentukmuka" class="read"><?=$dp['bentuk_muka']?></div>
<label for="warnakulit">Warna Kulit</label><div id="warnakulit" class="read"><?=$dp['warna_kulit']?></div>
<label for="cirikhas">Ciri-ciri Khas</label><div id="cirikhas" class="read"><?=$dp['ciri_khas']?></div>
<label for="cacat">Cacat Tubuh</label><div id="cacat" class="read"><?=$dp['cacat_tubuh']?></div>
</fieldset>
<br>
<fieldset>
<legend>Riwayat Jabatan / Pekerjaan</legend>
<table id="daftarpengalaman">
<thead>
<tr><th rowspan=2>Pengalaman Bekerja</th><th rowspan=2>Tanggal<br/>Mulai</th><th rowspan=2>Tanggal<br/>Selesai</th><th rowspan=2>Golongan</th><th colspan=3 align=center>Surat Keputusan</th></tr>
<tr><th>Pejabat</th><th>Nomor</th><th>Tanggal</th></tr>
</thead>
<tbody>
<?foreach($daftarpengalaman as $brs):?>
<tr>
<td><input type="hidden" name="anm_pengalaman[]" value="<?=$brs['pengalaman']?>" ><?=$brs['pengalaman']?></td>
<td><input type="hidden" name="atglmulai_pengalaman[]" value="<?=$brs['tgl_mulai']?>" ><?=$brs['tgl_mulai']?></td>
<td><input type="hidden" name="atglselesai_pengalaman[]" value="<?=$brs['tgl_selesai']?>" ><?=$brs['tgl_selesai']?></td>
<td><input type="hidden" name="agol_pengalaman[]" value="<?=$brs['id_golongan']?>" ><?=$brs['golongan']?> <?=$brs['ket']?></td>
<td><input type="hidden" name="ask_pejabat_pengalaman[]" value="<?=$brs['sk_pejabat']?>" ><?=$brs['sk_pejabat']?></td>
<td><input type="hidden" name="ask_nomor_pengalaman[]" value="<?=$brs['sk_nomor']?>" ><?=$brs['sk_nomor']?></td>
<td><input type="hidden" name="ask_tgl_pengalaman[]" value="<?=$brs['sk_tanggal']?>" ><?=$brs['sk_tanggal']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Kunjungan Luar Negeri</legend>
<table id="daftarkunjungan">
<thead>
<tr><th>Negara</th><th>Tujuan Kunjungan</th><th>Tanggal<br/>Mulai</th><th>Tanggal<br/>Selesai</th><th>Pembiaya</th></tr>
</thead>
<tbody>
<?foreach($daftarkunjungan as $brs):?>
<tr>
<td><input type="hidden" name="anegara_kunjungan[]" value="<?=$brs['negara']?>" ><?=$brs['negara']?></td>
<td><input type="hidden" name="atujuan_kunjungan[]" value="<?=$brs['tujuan']?>" ><?=$brs['tujuan']?></td>
<td><input type="hidden" name="atglmulai_kunjungan[]" value="<?=$brs['tgl_awal']?>" ><?=$brs['tgl_awal']?></td>
<td><input type="hidden" name="atglselesai_kunjungan[]" value="<?=$brs['tgl_akhir']?>" ><?=$brs['tgl_akhir']?></td>
<td><input type="hidden" name="apembiaya_kunjungan[]" value="<?=$brs['pembiaya']?>" ><?=$brs['pembiaya']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Seminar / Panitia</legend>
<table id="daftarseminar">
<thead>
<tr><th>Nama</th><th>Peranan</th><th>Tanggal<br/>Penyelenggaraan</th><th>Instansi Penyelenggara</th><th>Tempat</th></tr>
</thead>
<tbody>
<?foreach($daftarseminar as $brs):?>
<tr>
<td><input type="hidden" name="anm_seminar[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="aperanan_seminar[]" value="<?=$brs['peranan']?>" ><?=$brs['peranan']?></td>
<td><input type="hidden" name="atgl_seminar[]" value="<?=$brs['tgl_penyelenggaraan']?>" ><?=$brs['tgl_penyelenggaraan']?></td>
<td><input type="hidden" name="apenyelenggara_seminar[]" value="<?=$brs['penyelenggara']?>" ><?=$brs['penyelenggara']?></td>
<td><input type="hidden" name="atmp_seminar[]" value="<?=$brs['tempat']?>" ><?=$brs['tempat']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Keterangan Keluarga</legend>
<fieldset>
<legend>Pasangan Hidup</legend>
<table id="daftarpasangan">
<thead>
<tr><th>Nama</th><th>Tempat Lahir</th><th>Tanggal Lahir</th><th>Tanggal Menikah</th><th>Pekerjaan</th><th>Keterangan</th></tr>
</thead>
<tbody>
<?foreach($daftarpasangan as $brs):?>
<tr>
<td><input type="hidden" name="anm_pasangan[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="atmplhr_pasangan[]" value="<?=$brs['tempat_lahir']?>" ><?=$brs['tempat_lahir']?></td>
<td><input type="hidden" name="atgllhr_pasangan[]" value="<?=$brs['tgl_lahir']?>" ><?=$brs['tgl_lahir']?></td>
<td><input type="hidden" name="atglmenikah_pasangan[]" value="<?=$brs['tgl_menikah']?>" ><?=$brs['tgl_menikah']?></td>
<td><input type="hidden" name="akerja_pasangan[]" value="<?=$brs['pekerjaan']?>" ><?=$brs['pekerjaan']?></td>
<td><input type="hidden" name="aket_pasangan[]" value="<?=$brs['keterangan']?>" ><?=$brs['keterangan']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Anak</legend>
<table id="daftaranak">
<thead>
<tr><th>Nama</th><th>Jenis Kelamin</th><th>Tempat Lahir</th><th>Tanggal Lahir</th><th>Pekerjaan</th><th>Keterangan</th></tr>
</thead>
<tbody>
<?foreach($daftaranak as $brs):?>
<tr>
<td><input type="hidden" name="anm_anak[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="ajk_anak[]" value="<?=$brs['jk']?>" ><? echo ($brs['jk']=='P')?'Pria':'Wanita';?></td>
<td><input type="hidden" name="atmplhr_anak[]" value="<?=$brs['tempat_lahir']?>" ><?=$brs['tempat_lahir']?></td>
<td><input type="hidden" name="atgllhr_anak[]" value="<?=$brs['tgl_lahir']?>" ><?=$brs['tgl_lahir']?></td>
<td><input type="hidden" name="akerja_anak[]" value="<?=$brs['pekerjaan']?>" ><?=$brs['pekerjaan']?></td>
<td><input type="hidden" name="aket_anak[]" value="<?=$brs['keterangan']?>" ><?=$brs['keterangan']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Bapak dan Ibu Kandung</legend>
<table id="daftarortu">
<thead>
<tr><th>Nama</th><th>Jenis Kelamin</th><th>Tanggal Lahir</th><th>Pekerjaan</th><th>Keterangan</th></tr>
</thead>
<tbody>
<?foreach($daftarortu as $brs):?>
<tr>
<td><input type="hidden" name="anm_ortu[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="ajk_ortu[]" value="<?=$brs['jk']?>" ><? echo ($brs['jk']=='P')?'Pria':'Wanita';?></td>
<td><input type="hidden" name="atgllhr_ortu[]" value="<?=$brs['tgl_lahir']?>" ><?=$brs['tgl_lahir']?></td>
<td><input type="hidden" name="akerja_ortu[]" value="<?=$brs['pekerjaan']?>" ><?=$brs['pekerjaan']?></td>
<td><input type="hidden" name="aket_ortu[]" value="<?=$brs['keterangan']?>" ><?=$brs['keterangan']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Bapak dan Ibu Mertua</legend>
<table id="daftarmertua">
<thead>
<tr><th>Nama</th><th>Jenis Kelamin</th><th>Tanggal Lahir</th><th>Pekerjaan</th><th>Keterangan</th></tr>
</thead>
<tbody>
<?foreach($daftarmertua as $brs):?>
<tr>
<td><input type="hidden" name="anm_mertua[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="ajk_mertua[]" value="<?=$brs['jk']?>" ><? echo ($brs['jk']=='P')?'Pria':'Wanita';?></td>
<td><input type="hidden" name="atgllhr_mertua[]" value="<?=$brs['tgl_lahir']?>" ><?=$brs['tgl_lahir']?></td>
<td><input type="hidden" name="akerja_mertua[]" value="<?=$brs['pekerjaan']?>" ><?=$brs['pekerjaan']?></td>
<td><input type="hidden" name="aket_mertua[]" value="<?=$brs['keterangan']?>" ><?=$brs['keterangan']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Saudara Kandung</legend>
<table id="daftarsaudara">
<thead>
<tr><th>Nama</th><th>Jenis Kelamin</th><th>Tanggal Lahir</th><th>Pekerjaan</th><th>Keterangan</th></tr>
</thead>
<tbody>
<?foreach($daftarsaudara as $brs):?>
<tr>
<td><input type="hidden" name="anm_saudara[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="ajk_saudara[]" value="<?=$brs['jk']?>" ><? echo ($brs['jk']=='P')?'Pria':'Wanita';?></td>
<td><input type="hidden" name="atgllhr_saudara[]" value="<?=$brs['tgl_lahir']?>" ><?=$brs['tgl_lahir']?></td>
<td><input type="hidden" name="akerja_saudara[]" value="<?=$brs['pekerjaan']?>" ><?=$brs['pekerjaan']?></td>
<td><input type="hidden" name="aket_saudara[]" value="<?=$brs['keterangan']?>" ><?=$brs['keterangan']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Saudara Kandung Pasangan Hidup</legend>
<table id="daftaripar">
<thead>
<tr><th>Nama</th><th>Jenis Kelamin</th><th>Tanggal Lahir</th><th>Pekerjaan</th><th>Keterangan</th></tr>
</thead>
<tbody>
<?foreach($daftaripar as $brs):?>
<tr>
<td><input type="hidden" name="anm_ipar[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="ajk_ipar[]" value="<?=$brs['jk']?>" ><? echo ($brs['jk']=='P')?'Pria':'Wanita';?></td>
<td><input type="hidden" name="atgllhr_ipar[]" value="<?=$brs['tgl_lahir']?>" ><?=$brs['tgl_lahir']?></td>
<td><input type="hidden" name="akerja_ipar[]" value="<?=$brs['pekerjaan']?>" ><?=$brs['pekerjaan']?></td>
<td><input type="hidden" name="aket_ipar[]" value="<?=$brs['keterangan']?>" ><?=$brs['keterangan']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
</fieldset>
<br>
<fieldset>
<legend>Keterangan Organisasi</legend>
<fieldset>
<legend>Organisasi saat SMA atau sebelumnya</legend>
<table id="daftarorg_sma">
<thead>
<tr><th>Nama Organisasi</th><th>Kedudukan</th><th>Tahun<br/>Mulai</th><th>Tahun<br/>Selesai</th><th>Tempat</th><th>Pimpinan Organisasi</th></tr>
</thead>
<tbody>
<?foreach($daftarorgsma as $brs):?>
<tr>
<td><input type="hidden" name="anm_orgsma[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="akedudukan_orgsma[]" value="<?=$brs['kedudukan']?>" ><?=$brs['kedudukan']?></td>
<td><input type="hidden" name="athnmulai_orgsma[]" value="<?=$brs['tahun_awal']?>" ><?=$brs['tahun_awal']?></td>
<td><input type="hidden" name="athnselesai_orgsma[]" value="<?=$brs['tahun_akhir']?>" ><?=$brs['tahun_akhir']?></td>
<td><input type="hidden" name="atmp_orgsma[]" value="<?=$brs['tempat']?>" ><?=$brs['tempat']?></td>
<td><input type="hidden" name="apimpinan_orgsma[]" value="<?=$brs['nama_pemimpin']?>" ><?=$brs['nama_pemimpin']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Organisasi saat Perguruan Tinggi</legend>
<table id="daftarorg_pt">
<thead>
<tr><th>Nama Organisasi</th><th>Kedudukan</th><th>Tahun<br/>Mulai</th><th>Tahun<br/>Selesai</th><th>Tempat</th><th>Pimpinan Organisasi</th></tr>
</thead>
<tbody>
<?foreach($daftarorgpt as $brs):?>
<tr>
<td><input type="hidden" name="anm_orgpt[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="akedudukan_orgpt[]" value="<?=$brs['kedudukan']?>" ><?=$brs['kedudukan']?></td>
<td><input type="hidden" name="athnmulai_orgpt[]" value="<?=$brs['tahun_awal']?>" ><?=$brs['tahun_awal']?></td>
<td><input type="hidden" name="athnselesai_orgpt[]" value="<?=$brs['tahun_akhir']?>" ><?=$brs['tahun_akhir']?></td>
<td><input type="hidden" name="atmp_orgpt[]" value="<?=$brs['tempat']?>" ><?=$brs['tempat']?></td>
<td><input type="hidden" name="apimpinan_orgpt[]" value="<?=$brs['nama_pemimpin']?>" ><?=$brs['nama_pemimpin']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
<br>
<fieldset>
<legend>Organisasi Selesai Pendidikan</legend>
<table id="daftarorg_kerja">
<thead>
<tr><th>Nama Organisasi</th><th>Kedudukan</th><th>Tahun<br/>Mulai</th><th>Tahun<br/>Selesai</th><th>Tempat</th><th>Pimpinan Organisasi</th></tr>
</thead>
<tbody>
<?foreach($daftarorgkerja as $brs):?>
<tr>
<td><input type="hidden" name="anm_orgkerja[]" value="<?=$brs['nama']?>" ><?=$brs['nama']?></td>
<td><input type="hidden" name="akedudukan_orgkerja[]" value="<?=$brs['kedudukan']?>" ><?=$brs['kedudukan']?></td>
<td><input type="hidden" name="athnmulai_orgkerja[]" value="<?=$brs['tahun_awal']?>" ><?=$brs['tahun_awal']?></td>
<td><input type="hidden" name="athnselesai_orgkerja[]" value="<?=$brs['tahun_akhir']?>" ><?=$brs['tahun_akhir']?></td>
<td><input type="hidden" name="atmp_orgkerja[]" value="<?=$brs['tempat']?>" ><?=$brs['tempat']?></td>
<td><input type="hidden" name="apimpinan_orgkerja[]" value="<?=$brs['nama_pemimpin']?>" ><?=$brs['nama_pemimpin']?></td>
</tr>
<?endforeach;?>
</tbody>
</table>
</fieldset>
</fieldset>
<br>
<fieldset>
<legend>Keterangan</legend>
<fieldset>
<legend>Keterangan Berkelakuan Baik</legend>
<label for="skkb_pejabat">Pejabat</label><div id="skkb_pejabat" class="read"><?=$dp['pejabat_skkb']?></div>
<label for="skkb_nomor">Nomor</label><div id="skkb_nomor" class="read"><?=$dp['no_skkb']?></div>
<label for="skkb_tgl">Tanggal</label><div id="skkb_tgl" class="read"><?=$dp['tgl_skkb']?></div>
</fieldset>
<br>
<fieldset>
<legend>Keterangan Berbadan Sehat</legend>
<label for="sk_sehat_pejabat">Pejabat</label><div id="sk_sehat_pejabat" class="read"><?=$dp['pejabat_ketsehat']?></div>
<label for="sk_sehat_nomor">Nomor</label><div id="sk_sehat_nomor" class="read"><?=$dp['no_ketsehat']?></div>
<label for="sk_sehat_tgl">Tanggal</label><div id="sk_sehat_tgl" class="read"><?=$dp['tgl_ketsehat']?></div>
</fieldset>
<br>
</fieldset>
<?endif;?>
<br>
</form>
<?endif?>
</div>
</div>
<div id="dummy"></div>
<div id="dummy2"></div>
<div id="footer"> 2012 © BBPPK - Lembang Jawa Barat</div>
</div>
</body>
<script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function() {
var pnlPesan=$('#pnlpesan'),ttpPesan=$('#pnlpesan a.close'),isiPesan=$('#isipesan'),cond=$('.cond').clone(),filter=$('#filter');
cond.prepend('<select class="conj">'+
'<option value=" and ">Dan</option>'+
'<option value=" or ">Atau</option>'+
'</select>'
);
$('#cetak').click(function(){
window.print();
return false;
});
$('#tambah').click(function(){
$('.cond').last().after(cond.clone());
});
ttpPesan.click(function(){
pnlPesan.fadeOut('fast');
return false;
});
$('.kat').live('change',function(){
var ini=$(this);
var nilai=ini.next().next();
var nama=ini.val();
nilai.children().remove();
console.log(ini.val());
nama=nama.substr(nama.indexOf('.')+1);
$.ajax({
url:'../lib/ajax.php?op=listkat&kat='+ini.val(),
type:'GET',
timeout:10000,
dataType: 'json',
success:function(data){
for(var i=0;i<data.length;i++){
nilai.append('<option value="\''+data[i][nama]+'\'">'+data[i][nama]+'</option>');
}
},
error:function(e){
updatePesan('Terjadi kesalahan koneksi');
}
});
});
$('#kirim').click(function(){
var query='';
$('.cond').each(function(){
$(this).children().each(function(){
query+=$(this).val();
});
});
filter.val(query);
});
function updatePesan(pesan){
isiPesan.html(pesan).addClass('cahaya');
setTimeout(function() {
isiPesan.removeClass('cahaya', 1500);
}, 500);
pnlPesan.fadeIn('slow').animate({opacity:0.8});
}
$('table').each(function(){
$(this).find('tbody').children().filter(':odd').css('background-color','#b6d7e7');
});
});
</script>
</html>
| bsd-3-clause |
bkielbasa/coyote2 | module/forum/template/forumView.php | 3827 | <script type="text/javascript">
<!--
var hash = '<?= $hash; ?>';
var preventAjax = false;
var currMode = '<?= $viewMode; ?>';
var defaultMode = '<?= $viewMode; ?>';
var hashChange = function()
{
if (jQuery.inArray(window.location.hash, ['#all', '#unanswered', '#votes', '#unread']) > -1)
{
if (('#' + currMode) != window.location.hash)
{
$('#body .f-menu-top a[href$=' + window.location.hash + ']').trigger('click');
}
}
else if (window.location.hash == '')
{
if (currMode != defaultMode)
{
//$('a[href$=#' + defaultMode + ']').trigger('click');
}
}
};
$(document).ready(function()
{
$.posting.init({currentUrl: '<?= url($page->getLocation()); ?>', forumId: '<?= $page->getForumId(); ?>'});
$(window).hashchange(hashChange);
$(window).hashchange();
$('#body').delegate('select[name=forum]', 'change', function()
{
window.location.href = $(this).val();
});
$('select[name=page]').change(function()
{
window.location.href = '<?= url($page->getLocation()); ?>?page=' + $(this).val();
});
$('#search-top input[name=q][autocomplete=off]').autocomplete({url: '<?= url(Path::connector('forumSearch')); ?>'});
$('#search-top').mouseenter(function()
{
$(this).addClass('search-holder');
});
});
//-->
</script>
<a style="display: none;" title="Strona główna forum" href="<?= url('@forum'); ?>" data-shortcut="g+i">Strona główna forum</a>
<a style="display: none;" title="Strona glówna kategorii forum" href="<?= url($page->getLocation()); ?>" data-shortcut="g+f">Kategoria forum</a>
<div id="page">
<?= $page->getContent(); ?>
</div>
<?php if ($forum) : ?>
<?php include('_partialCategory.php'); ?>
<?php endif; ?>
<div id="body">
<ul class="f-menu-top">
<?= Topic::buildForumMenu($viewMode); ?>
<?php if ($isWriteable) : ?>
<li id="submit-top" title="Napisz nowy temat w tym dziale (skrót: n)"><a href="<?= url($page->getLocation()) . '?mode=submit'; ?>" data-shortcut="n"><span>Nowy temat</span></a></li>
<?php endif; ?>
<li id="search-top">
<?= Form::open(Path::connector('forumSearch')); ?>
<fieldset>
<?= Form::text('q', '', array('autocomplete' => 'off', 'placeholder' => 'Szukaj na forum...')); ?><a title="Szukaj na forum" href="<?= url(Path::connector('forumSearch')); ?>" class="search-submit-button"></a>
</fieldset>
<?= Form::close(); ?>
</li>
</ul>
<div style="clear: both;"></div>
<?php include('_partialTopicList.php'); ?>
<?php if (($topic) && (count($topic) > 10)) : ?>
<ul class="f-menu-bottom">
<li id="submit-bottom" title="Napisz nowy temat w tym dziale (skrót: n)"><a href="<?= url($page->getLocation()) . '?mode=submit'; ?>"><span>Nowy temat</span></a></li>
</ul>
<?php endif; ?>
</div>
<div style="overflow: hidden; margin-top: 10px">
<a id="feed-button" href="<?= url($page->getLocation()); ?>?export=atom" title="Eksportuj do: Atom">atom</a>
<p style="float: right;">Ilość tematów na strone <?= Form::select('page', Form::option($pageList, $perPage)); ?></p>
</div>
<div id="user-tags">
<strong title="Wpisz intersujące Cię tagi, aby odznaczyć tematy na liście">Tagi: <span title="Kliknij, aby edytować tagi"></span></strong>
<?php foreach ($userTags as $tag) : ?>
<?= Form::hidden('userTags[]', $tag); ?>
<?php endforeach; ?>
<div>
<?php if ($tags) : ?>
<?php foreach ($tags as $tag => $weight) : ?>
<?= Html::a(url($page->getLocation()) . '?tag=' . urlencode($tag), $tag); ?> × <?= $weight; ?>
<?php endforeach; ?>
<?php else : ?>
<cite>(Brak tagów. Kliknij, aby dodać)</cite>
<?php endif; ?>
</div>
</div>
<div id="users-online">
<div><?= count($usersOnline) + $anonymousUsersOnline; ?> użytkownik(ów) przegląda to forum (<?= $anonymousUsersOnline; ?> gości)</div>
<p><?= implode(', ', $usersOnline); ?></p>
</div> | bsd-3-clause |
mogoweb/chromium-crosswalk | content/browser/renderer_host/media/audio_input_device_manager_unittest.cc | 9282 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "content/browser/browser_thread_impl.h"
#include "content/browser/renderer_host/media/audio_input_device_manager.h"
#include "content/public/common/media_stream_request.h"
#include "media/audio/audio_manager_base.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::InSequence;
using testing::SaveArg;
using testing::Return;
namespace content {
class MockAudioInputDeviceManagerListener
: public MediaStreamProviderListener {
public:
MockAudioInputDeviceManagerListener() {}
virtual ~MockAudioInputDeviceManagerListener() {}
MOCK_METHOD2(Opened, void(MediaStreamType, const int));
MOCK_METHOD2(Closed, void(MediaStreamType, const int));
MOCK_METHOD2(DevicesEnumerated, void(MediaStreamType,
const StreamDeviceInfoArray&));
MOCK_METHOD3(Error, void(MediaStreamType, int, MediaStreamProviderError));
StreamDeviceInfoArray devices_;
private:
DISALLOW_COPY_AND_ASSIGN(MockAudioInputDeviceManagerListener);
};
class AudioInputDeviceManagerTest : public testing::Test {
public:
AudioInputDeviceManagerTest() {}
// Returns true iff machine has an audio input device.
bool CanRunAudioInputDeviceTests() {
return audio_manager_->HasAudioInputDevices();
}
protected:
virtual void SetUp() OVERRIDE {
// The test must run on Browser::IO.
message_loop_.reset(new base::MessageLoop(base::MessageLoop::TYPE_IO));
io_thread_.reset(new BrowserThreadImpl(BrowserThread::IO,
message_loop_.get()));
audio_manager_.reset(media::AudioManager::Create());
manager_ = new AudioInputDeviceManager(audio_manager_.get());
audio_input_listener_.reset(new MockAudioInputDeviceManagerListener());
manager_->Register(audio_input_listener_.get(),
message_loop_->message_loop_proxy().get());
// Gets the enumerated device list from the AudioInputDeviceManager.
manager_->EnumerateDevices(MEDIA_DEVICE_AUDIO_CAPTURE);
EXPECT_CALL(*audio_input_listener_,
DevicesEnumerated(MEDIA_DEVICE_AUDIO_CAPTURE, _))
.Times(1)
.WillOnce(SaveArg<1>(&devices_));
// Wait until we get the list.
message_loop_->RunUntilIdle();
}
virtual void TearDown() OVERRIDE {
manager_->Unregister();
io_thread_.reset();
}
scoped_ptr<base::MessageLoop> message_loop_;
scoped_ptr<BrowserThreadImpl> io_thread_;
scoped_refptr<AudioInputDeviceManager> manager_;
scoped_ptr<MockAudioInputDeviceManagerListener> audio_input_listener_;
scoped_ptr<media::AudioManager> audio_manager_;
StreamDeviceInfoArray devices_;
private:
DISALLOW_COPY_AND_ASSIGN(AudioInputDeviceManagerTest);
};
// Opens and closes the devices.
TEST_F(AudioInputDeviceManagerTest, OpenAndCloseDevice) {
if (!CanRunAudioInputDeviceTests())
return;
ASSERT_FALSE(devices_.empty());
InSequence s;
for (StreamDeviceInfoArray::const_iterator iter = devices_.begin();
iter != devices_.end(); ++iter) {
// Opens/closes the devices.
int session_id = manager_->Open(*iter);
// Expected mock call with expected return value.
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, session_id))
.Times(1);
// Waits for the callback.
message_loop_->RunUntilIdle();
manager_->Close(session_id);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, session_id))
.Times(1);
// Waits for the callback.
message_loop_->RunUntilIdle();
}
}
// Opens multiple devices at one time and closes them later.
TEST_F(AudioInputDeviceManagerTest, OpenMultipleDevices) {
if (!CanRunAudioInputDeviceTests())
return;
ASSERT_FALSE(devices_.empty());
InSequence s;
int index = 0;
scoped_ptr<int[]> session_id(new int[devices_.size()]);
// Opens the devices in a loop.
for (StreamDeviceInfoArray::const_iterator iter = devices_.begin();
iter != devices_.end(); ++iter, ++index) {
// Opens the devices.
session_id[index] = manager_->Open(*iter);
// Expected mock call with expected returned value.
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, session_id[index]))
.Times(1);
// Waits for the callback.
message_loop_->RunUntilIdle();
}
// Checks if the session_ids are unique.
for (size_t i = 0; i < devices_.size() - 1; ++i) {
for (size_t k = i + 1; k < devices_.size(); ++k) {
EXPECT_TRUE(session_id[i] != session_id[k]);
}
}
for (size_t i = 0; i < devices_.size(); ++i) {
// Closes the devices.
manager_->Close(session_id[i]);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, session_id[i]))
.Times(1);
// Waits for the callback.
message_loop_->RunUntilIdle();
}
}
// Opens a non-existing device.
TEST_F(AudioInputDeviceManagerTest, OpenNotExistingDevice) {
if (!CanRunAudioInputDeviceTests())
return;
InSequence s;
MediaStreamType stream_type = MEDIA_DEVICE_AUDIO_CAPTURE;
std::string device_name("device_doesnt_exist");
std::string device_id("id_doesnt_exist");
int sample_rate(0);
int channel_config(0);
StreamDeviceInfo dummy_device(
stream_type, device_name, device_id, sample_rate, channel_config, 2048,
false);
int session_id = manager_->Open(dummy_device);
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, session_id))
.Times(1);
// Waits for the callback.
message_loop_->RunUntilIdle();
}
// Opens default device twice.
TEST_F(AudioInputDeviceManagerTest, OpenDeviceTwice) {
if (!CanRunAudioInputDeviceTests())
return;
ASSERT_FALSE(devices_.empty());
InSequence s;
// Opens and closes the default device twice.
int first_session_id = manager_->Open(devices_.front());
int second_session_id = manager_->Open(devices_.front());
// Expected mock calls with expected returned values.
EXPECT_NE(first_session_id, second_session_id);
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, first_session_id))
.Times(1);
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, second_session_id))
.Times(1);
// Waits for the callback.
message_loop_->RunUntilIdle();
manager_->Close(first_session_id);
manager_->Close(second_session_id);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, first_session_id))
.Times(1);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, second_session_id))
.Times(1);
// Waits for the callback.
message_loop_->RunUntilIdle();
}
// Accesses then closes the sessions after opening the devices.
TEST_F(AudioInputDeviceManagerTest, AccessAndCloseSession) {
if (!CanRunAudioInputDeviceTests())
return;
ASSERT_FALSE(devices_.empty());
InSequence s;
int index = 0;
scoped_ptr<int[]> session_id(new int[devices_.size()]);
// Loops through the devices and calls Open()/Close()/GetOpenedDeviceInfoById
// for each device.
for (StreamDeviceInfoArray::const_iterator iter = devices_.begin();
iter != devices_.end(); ++iter, ++index) {
// Note that no DeviceStopped() notification for Event Handler as we have
// stopped the device before calling close.
session_id[index] = manager_->Open(*iter);
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, session_id[index]))
.Times(1);
message_loop_->RunUntilIdle();
const StreamDeviceInfo* info = manager_->GetOpenedDeviceInfoById(
session_id[index]);
DCHECK(info);
EXPECT_EQ(iter->device.id, info->device.id);
manager_->Close(session_id[index]);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, session_id[index]))
.Times(1);
message_loop_->RunUntilIdle();
}
}
// Access an invalid session.
TEST_F(AudioInputDeviceManagerTest, AccessInvalidSession) {
if (!CanRunAudioInputDeviceTests())
return;
InSequence s;
// Opens the first device.
StreamDeviceInfoArray::const_iterator iter = devices_.begin();
int session_id = manager_->Open(*iter);
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, session_id))
.Times(1);
message_loop_->RunUntilIdle();
// Access a non-opened device.
// This should fail and return an empty StreamDeviceInfo.
int invalid_session_id = session_id + 1;
const StreamDeviceInfo* info =
manager_->GetOpenedDeviceInfoById(invalid_session_id);
DCHECK(!info);
manager_->Close(session_id);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, session_id))
.Times(1);
message_loop_->RunUntilIdle();
}
} // namespace content
| bsd-3-clause |
patrickm/chromium.src | chrome/browser/sync/test/integration/enable_disable_test.cc | 6261 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/test/integration/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "sync/internal_api/public/base/model_type.h"
#include "sync/internal_api/public/read_node.h"
#include "sync/internal_api/public/read_transaction.h"
// This file contains tests that exercise enabling and disabling data
// types.
namespace {
class EnableDisableSingleClientTest : public SyncTest {
public:
// TODO(pvalenzuela): Switch to SINGLE_CLIENT once FakeServer
// supports this scenario.
EnableDisableSingleClientTest() : SyncTest(SINGLE_CLIENT_LEGACY) {}
virtual ~EnableDisableSingleClientTest() {}
private:
DISALLOW_COPY_AND_ASSIGN(EnableDisableSingleClientTest);
};
bool DoesTopLevelNodeExist(syncer::UserShare* user_share,
syncer::ModelType type) {
syncer::ReadTransaction trans(FROM_HERE, user_share);
syncer::ReadNode node(&trans);
return node.InitByTagLookup(syncer::ModelTypeToRootTag(type)) ==
syncer::BaseNode::INIT_OK;
}
IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest, EnableOneAtATime) {
ASSERT_TRUE(SetupClients());
// Setup sync with no enabled types.
ASSERT_TRUE(GetClient(0)->SetupSync(syncer::ModelTypeSet()));
// TODO(rlarocque, 97780): It should be possible to disable notifications
// before calling SetupSync(). We should move this line back to the top
// of this function when this is supported.
DisableNotifications();
const syncer::ModelTypeSet registered_types =
GetClient(0)->service()->GetRegisteredDataTypes();
syncer::UserShare* user_share = GetClient(0)->service()->GetUserShare();
for (syncer::ModelTypeSet::Iterator it = registered_types.First();
it.Good(); it.Inc()) {
ASSERT_TRUE(GetClient(0)->EnableSyncForDatatype(it.Get()));
// AUTOFILL_PROFILE is lumped together with AUTOFILL.
// SESSIONS is lumped together with PROXY_TABS and
// HISTORY_DELETE_DIRECTIVES.
// Favicons are lumped together with PROXY_TABS and
// HISTORY_DELETE_DIRECTIVES.
if (it.Get() == syncer::AUTOFILL_PROFILE || it.Get() == syncer::SESSIONS) {
continue;
}
if (!syncer::ProxyTypes().Has(it.Get())) {
ASSERT_TRUE(DoesTopLevelNodeExist(user_share, it.Get()))
<< syncer::ModelTypeToString(it.Get());
}
// AUTOFILL_PROFILE is lumped together with AUTOFILL.
if (it.Get() == syncer::AUTOFILL) {
ASSERT_TRUE(DoesTopLevelNodeExist(user_share,
syncer::AUTOFILL_PROFILE));
} else if (it.Get() == syncer::HISTORY_DELETE_DIRECTIVES ||
it.Get() == syncer::PROXY_TABS) {
ASSERT_TRUE(DoesTopLevelNodeExist(user_share,
syncer::SESSIONS));
}
}
EnableNotifications();
}
IN_PROC_BROWSER_TEST_F(EnableDisableSingleClientTest, DisableOneAtATime) {
ASSERT_TRUE(SetupClients());
// Setup sync with no disabled types.
ASSERT_TRUE(GetClient(0)->SetupSync());
// TODO(rlarocque, 97780): It should be possible to disable notifications
// before calling SetupSync(). We should move this line back to the top
// of this function when this is supported.
DisableNotifications();
const syncer::ModelTypeSet registered_types =
GetClient(0)->service()->GetRegisteredDataTypes();
syncer::UserShare* user_share = GetClient(0)->service()->GetUserShare();
// Make sure all top-level nodes exist first.
for (syncer::ModelTypeSet::Iterator it = registered_types.First();
it.Good(); it.Inc()) {
if (!syncer::ProxyTypes().Has(it.Get())) {
ASSERT_TRUE(DoesTopLevelNodeExist(user_share, it.Get()));
}
}
for (syncer::ModelTypeSet::Iterator it = registered_types.First();
it.Good(); it.Inc()) {
// MANAGED_USERS and MANAGED_USER_SETTINGS are always synced.
if (it.Get() == syncer::MANAGED_USERS ||
it.Get() == syncer::MANAGED_USER_SHARED_SETTINGS ||
it.Get() == syncer::SYNCED_NOTIFICATIONS ||
it.Get() == syncer::SYNCED_NOTIFICATION_APP_INFO)
continue;
ASSERT_TRUE(GetClient(0)->DisableSyncForDatatype(it.Get()));
// AUTOFILL_PROFILE is lumped together with AUTOFILL.
// SESSIONS is lumped together with PROXY_TABS and TYPED_URLS.
// HISTORY_DELETE_DIRECTIVES is lumped together with TYPED_URLS.
// PRIORITY_PREFERENCES is lumped together with PREFERENCES.
// Favicons are lumped together with PROXY_TABS and
// HISTORY_DELETE_DIRECTIVES.
if (it.Get() == syncer::AUTOFILL_PROFILE ||
it.Get() == syncer::SESSIONS ||
it.Get() == syncer::HISTORY_DELETE_DIRECTIVES ||
it.Get() == syncer::PRIORITY_PREFERENCES ||
it.Get() == syncer::FAVICON_IMAGES ||
it.Get() == syncer::FAVICON_TRACKING) {
continue;
}
syncer::UserShare* user_share =
GetClient(0)->service()->GetUserShare();
ASSERT_FALSE(DoesTopLevelNodeExist(user_share, it.Get()))
<< syncer::ModelTypeToString(it.Get());
if (it.Get() == syncer::AUTOFILL) {
// AUTOFILL_PROFILE is lumped together with AUTOFILL.
ASSERT_FALSE(DoesTopLevelNodeExist(user_share, syncer::AUTOFILL_PROFILE));
} else if (it.Get() == syncer::TYPED_URLS) {
ASSERT_FALSE(DoesTopLevelNodeExist(user_share,
syncer::HISTORY_DELETE_DIRECTIVES));
// SESSIONS should be enabled only if PROXY_TABS is.
ASSERT_EQ(GetClient(0)->IsTypePreferred(syncer::PROXY_TABS),
DoesTopLevelNodeExist(user_share, syncer::SESSIONS));
} else if (it.Get() == syncer::PROXY_TABS) {
// SESSIONS should be enabled only if TYPED_URLS is.
ASSERT_EQ(GetClient(0)->IsTypePreferred(syncer::TYPED_URLS),
DoesTopLevelNodeExist(user_share, syncer::SESSIONS));
} else if (it.Get() == syncer::PREFERENCES) {
ASSERT_FALSE(DoesTopLevelNodeExist(user_share,
syncer::PRIORITY_PREFERENCES));
}
}
EnableNotifications();
}
} // namespace
| bsd-3-clause |
pederpansen/dune-ax1 | dune/ax1/acme2_cyl/configurations/no_analytical_solution.hh | 1258 | /*
* no_analytical_solution.hh
*
* Created on: Jan 17, 2012
* Author: jpods
*/
#ifndef DUNE_AX1_NO_ANALYTICAL_SOLUTION_HH
#define DUNE_AX1_NO_ANALYTICAL_SOLUTION_HH
#include <dune/pdelab/common/function.hh>
#include <dune/ax1/acme2_cyl/common/acme2_cyl_parametertree.hh>
template<typename GV, typename RField, int dim>
class NoAnalyticalSolution :
public Dune::PDELab::AnalyticGridFunctionBase<
Dune::PDELab::AnalyticGridFunctionTraits<GV,RField,dim>,
NoAnalyticalSolution<GV,RField,dim> >
{
public:
typedef Dune::PDELab::AnalyticGridFunctionTraits<GV,RField,dim> Traits;
typedef Dune::PDELab::AnalyticGridFunctionBase<Traits, NoAnalyticalSolution<GV,RField,dim> > BaseT;
typedef typename Traits::DomainType DomainType;
typedef typename Traits::RangeType RangeType;
typedef RField RF;
typedef RangeType RT;
NoAnalyticalSolution(const GV & gv, const Acme2CylParameters& params_)
: BaseT(gv)
{}
inline void evaluateGlobal(const DomainType & x, RangeType & y) const
{
y[0] = 0.;
}
/*
inline const GV& getGridView () const
{
}
*/
// set time for subsequent evaluation
void setTime (double t)
{}
};
#endif /* DUNE_AX1_NO_ANALYTICAL_SOLUTION_HH */
| bsd-3-clause |
hcmaza/nortia | src/main/java/ar/edu/undec/nortia/model/PresupuestoRubro.java | 5664 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ar.edu.undec.nortia.model;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Min;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Hugo
*/
@Entity
@Table(name = "presupuesto_rubro", schema = "ap")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "PresupuestoRubro.findAll", query = "SELECT p FROM PresupuestoRubro p"),
@NamedQuery(name = "PresupuestoRubro.findByPresupuestoid", query = "SELECT p FROM PresupuestoRubro p WHERE p.presupuestoRubroPK.presupuestoid = :presupuestoid"),
@NamedQuery(name = "PresupuestoRubro.findByRubroid", query = "SELECT p FROM PresupuestoRubro p WHERE p.presupuestoRubroPK.rubroid = :rubroid"),
@NamedQuery(name = "PresupuestoRubro.findByGastocomitente", query = "SELECT p FROM PresupuestoRubro p WHERE p.gastocomitente = :gastocomitente"),
@NamedQuery(name = "PresupuestoRubro.findByGastouniversidad", query = "SELECT p FROM PresupuestoRubro p WHERE p.gastouniversidad = :gastouniversidad"),
@NamedQuery(name = "PresupuestoRubro.findByEstado", query = "SELECT p FROM PresupuestoRubro p WHERE p.estado = :estado")})
public class PresupuestoRubro implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected PresupuestoRubroPK presupuestoRubroPK;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Min(value =0)
@Digits(integer=9, fraction=2)
@Column(name = "gastocomitente")
private BigDecimal gastocomitente;
@Min(value =0)
@Digits(integer=9, fraction=2)
@Column(name = "gastouniversidad")
private BigDecimal gastouniversidad;
@Min(value =0)
@Digits(integer=9, fraction=2)
@Column(name = "gastoorganismo")
private BigDecimal gastoorganismo;
@Min(value =0)
@Digits(integer=9, fraction=2)
@Column(name = "total")
private BigDecimal total;
@Column(name = "estado")
private Character estado;
@JoinColumn(name = "rubroid", referencedColumnName = "id", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Rubro rubro;
@JoinColumn(name = "presupuestoid", referencedColumnName = "id", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Presupuesto presupuesto;
public PresupuestoRubro() {
}
public PresupuestoRubro(PresupuestoRubroPK presupuestoRubroPK) {
this.presupuestoRubroPK = presupuestoRubroPK;
}
public PresupuestoRubro(int presupuestoid, int rubroid) {
this.presupuestoRubroPK = new PresupuestoRubroPK(presupuestoid, rubroid);
}
public PresupuestoRubroPK getPresupuestoRubroPK() {
return presupuestoRubroPK;
}
public void setPresupuestoRubroPK(PresupuestoRubroPK presupuestoRubroPK) {
this.presupuestoRubroPK = presupuestoRubroPK;
}
public BigDecimal getGastocomitente() {
return gastocomitente;
}
public void setGastocomitente(BigDecimal gastoentidad) {
this.gastocomitente = gastoentidad;
}
public BigDecimal getGastoorganismo() {
return gastoorganismo;
}
public void setGastoorganismo(BigDecimal gastoorganismo) {
this.gastoorganismo = gastoorganismo;
}
public BigDecimal getGastouniversidad() {
return gastouniversidad;
}
public void setGastouniversidad(BigDecimal gastouniversidad) {
this.gastouniversidad = gastouniversidad;
}
public BigDecimal getTotal() {
//System.out.println("PresupuestoRubro.getTotal = " + total.toString());
return total;
}
public void setTotal(BigDecimal total) {
this.total = total;
}
public Character getEstado() {
return estado;
}
public void setEstado(Character estado) {
this.estado = estado;
}
public Rubro getRubro() {
return rubro;
}
public void setRubro(Rubro rubro) {
this.rubro = rubro;
}
public Presupuesto getPresupuesto() {
return presupuesto;
}
public void setPresupuesto(Presupuesto presupuesto) {
this.presupuesto = presupuesto;
}
@Override
public int hashCode() {
int hash = 0;
hash += (presupuestoRubroPK != null ? presupuestoRubroPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PresupuestoRubro)) {
return false;
}
PresupuestoRubro other = (PresupuestoRubro) object;
if ((this.presupuestoRubroPK == null && other.presupuestoRubroPK != null) || (this.presupuestoRubroPK != null && !this.presupuestoRubroPK.equals(other.presupuestoRubroPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "ar.edu.undec.nortia.model.PresupuestoRubro[ presupuestoRubroPK=" + presupuestoRubroPK + " ]";
}
}
| bsd-3-clause |
jmfontaine/kornak | library/Kornak/View/Helper/BodyClass.php | 1978 | <?php
/**
* Kornak
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to jm@jmfontaine.net so we can send you a copy immediately.
*
* @category Kornak
* @package Kornak_View
* @copyright Copyright (c) 2007-2010 Jean-Marc Fontaine <jm@jmfontaine.net>
* @version $Id$
*/
require_once 'Zend/View/Helper/Placeholder/Container/Abstract.php';
require_once 'Zend/View/Helper/Placeholder/Container/Standalone.php';
class Kornak_View_Helper_BodyClass extends Zend_View_Helper_Placeholder_Container_Standalone
{
protected $_regKey = 'Kornak_View_Helper_BodyClass';
public function bodyClass($class = null, $setType = Zend_View_Helper_Placeholder_Container_Abstract::APPEND)
{
if ($class) {
if ($setType == Zend_View_Helper_Placeholder_Container_Abstract::SET) {
$this->set($class);
} elseif ($setType == Zend_View_Helper_Placeholder_Container_Abstract::PREPEND) {
$this->prepend($class);
} else {
$this->append($class);
}
}
return $this;
}
public function has($class)
{
$classes = (array) $this->getValue();
return in_array($class, $classes);
}
public function toString($indent = null)
{
$indent = (null !== $indent)
? $this->getWhitespace($indent)
: $this->getIndent();
$items = array();
foreach ($this as $item) {
$items[] = $item;
}
if (empty($items)) {
$result = '';
} else {
$result = $indent . ' class="' . implode(' ', $items) . '"';
}
return $result;
}
public function __toString()
{
return $this->toString();
}
} | bsd-3-clause |
sevki/rsc | google/chat.go | 907 | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package google
import "github.com/sevki/rsc/xmpp"
type ChatID struct {
ID string
Email string
Status xmpp.Status
StatusMsg string
}
type ChatSend struct {
ID *ChatID
Msg xmpp.Chat
}
func (g *Client) ChatRecv(cid *ChatID) (*xmpp.Chat, error) {
var msg xmpp.Chat
if err := g.client.Call("goog.ChatRecv", cid, &msg); err != nil {
return nil, err
}
return &msg, nil
}
func (g *Client) ChatStatus(cid *ChatID) error {
return g.client.Call("goog.ChatRecv", cid, &Empty{})
}
func (g *Client) ChatSend(cid *ChatID, msg *xmpp.Chat) error {
return g.client.Call("goog.ChatSend", &ChatSend{cid, *msg}, &Empty{})
}
func (g *Client) ChatRoster(cid *ChatID) error {
return g.client.Call("goog.ChatRoster", cid, &Empty{})
}
| bsd-3-clause |
sirixdb/sirix | bundles/sirix-core/src/main/java/org/sirix/index/art/AscendingSubMap.java | 3123 | package org.sirix.index.art;
import java.util.*;
final class AscendingSubMap<K, V> extends org.sirix.index.art.NavigableSubMap<K, V> {
// TODO: look into making ART and it's views (bounds) serializable later
// private static final long serialVersionUID = 912986545866124060L;
AscendingSubMap(AdaptiveRadixTree<K, V> tree, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi,
boolean hiInclusive) {
super(tree, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
@Override
public Comparator<? super K> comparator() {
return tree.comparator();
}
@Override
public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
if (!inRange(fromKey, fromInclusive))
throw new IllegalArgumentException("fromKey out of range");
if (!inRange(toKey, toInclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<>(tree, false, fromKey, fromInclusive, false, toKey, toInclusive);
}
// TODO: offer another ctor to take in loBytes
@Override
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
if (!inRange(toKey, inclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<>(tree, fromStart, lo, loInclusive, false, toKey, inclusive);
}
// TODO: offer another ctor to take in hiBytes
@Override
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
if (!inRange(fromKey, inclusive))
throw new IllegalArgumentException("fromKey out of range");
return new AscendingSubMap<>(tree, false, fromKey, inclusive, toEnd, hi, hiInclusive);
}
@Override
public NavigableMap<K, V> descendingMap() {
NavigableMap<K, V> mv = descendingMapView;
return (mv != null)
? mv
: (descendingMapView = new DescendingSubMap<>(tree, fromStart, lo, loInclusive, toEnd, hi, hiInclusive));
}
@Override
Iterator<K> keyIterator() {
return new SubMapKeyIterator(absLowest(), absHighFence());
}
@Override
Spliterator<K> keySpliterator() {
return new SubMapKeyIterator(absLowest(), absHighFence());
}
@Override
Iterator<K> descendingKeyIterator() {
return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
}
final class AscendingEntrySetView extends EntrySetView {
@Override
public Iterator<Entry<K, V>> iterator() {
return new SubMapEntryIterator(absLowest(), absHighFence());
}
}
@Override
public Set<Entry<K, V>> entrySet() {
EntrySetView es = entrySetView;
return (es != null) ? es : (entrySetView = new AscendingEntrySetView());
}
@Override
LeafNode<K, V> subLowest() {
return absLowest();
}
@Override
LeafNode<K, V> subHighest() {
return absHighest();
}
@Override
LeafNode<K, V> subCeiling(K key) {
return absCeiling(key);
}
@Override
LeafNode<K, V> subHigher(K key) {
return absHigher(key);
}
@Override
LeafNode<K, V> subFloor(K key) {
return absFloor(key);
}
@Override
LeafNode<K, V> subLower(K key) {
return absLower(key);
}
}
| bsd-3-clause |
grassrootza/grassroot-messaging | src/test/java/za/org/grassroot/messaging/IncomingGcmHandlerTest.java | 1681 | package za.org.grassroot.messaging;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.gcm.packet.GcmPacketExtension;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.junit4.SpringRunner;
import za.org.grassroot.core.domain.User;
/**
* Created by paballo on 2016/04/12.
*/
@RunWith(SpringRunner.class)
public class IncomingGcmHandlerTest {
private static final Logger log = LoggerFactory.getLogger(IncomingGcmHandlerTest.class);
private String registration =" {\n" +
" \"category\":\"com.techmorphosis.grassroot.gcm\",\n" +
" \"data\":\n" +
" {\n" +
" \"action\":\n" +
" \"REGISTER\",\n" +
" \"phoneNumber\":\"0616780986\"\n" +
" },\n" +
" \"message_id\":\"20\",\n" +
" \"from\":\"someRegistrationId\"\n" +
" }";
@Test
public void handleUpstream() throws Exception{
User user = makeDummy("0616780986", "some name");
log.info("Constructed user={}", user);
log.info("Created and saved user={}", user);
// gcmService.registerUser(new User("0616780986"),"someRegistrationId");
Message message = new Message();
message.addExtension(new GcmPacketExtension(registration));
// messageHandler.handleUpstreamMessage(message);
}
// for tests
public User makeDummy(String phoneNumber, String displayName) {
return new User(phoneNumber, displayName, null);
}
}
| bsd-3-clause |
maxhutch/magma | testing/testing_ssygst.cpp | 5071 | /*
-- MAGMA (version 2.1.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date August 2016
@author Mark Gates
@generated from testing/testing_zhegst.cpp, normal z -> s, Tue Aug 30 09:39:14 2016
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// includes, project
#include "flops.h"
#include "magma_v2.h"
#include "magma_lapack.h"
#include "testings.h"
#define REAL
/* ////////////////////////////////////////////////////////////////////////////
-- Testing ssygst
*/
int main( int argc, char** argv)
{
TESTING_CHECK( magma_init() );
magma_print_environment();
// Constants
const float c_neg_one = MAGMA_S_NEG_ONE;
const magma_int_t ione = 1;
// Local variables
real_Double_t gpu_time, cpu_time;
float *h_A, *h_B, *h_R;
float Anorm, error, work[1];
magma_int_t N, n2, lda, info;
magma_int_t ISEED[4] = {0,0,0,1};
int status = 0;
magma_opts opts;
opts.parse_opts( argc, argv );
opts.lapack |= opts.check; // check (-c) implies lapack (-l)
float tol = opts.tolerance * lapackf77_slamch("E");
printf("%% uplo = %s\n", lapack_uplo_const(opts.uplo) );
printf("%% itype N CPU time (sec) GPU time (sec) |R| \n");
printf("%%=======================================================\n");
for( int itest = 0; itest < opts.ntest; ++itest ) {
for( int iter = 0; iter < opts.niter; ++iter ) {
N = opts.nsize[itest];
lda = N;
n2 = N*lda;
TESTING_CHECK( magma_smalloc_cpu( &h_A, lda*N ));
TESTING_CHECK( magma_smalloc_cpu( &h_B, lda*N ));
TESTING_CHECK( magma_smalloc_pinned( &h_R, lda*N ));
/* ====================================================================
Initialize the matrix
=================================================================== */
lapackf77_slarnv( &ione, ISEED, &n2, h_A );
lapackf77_slarnv( &ione, ISEED, &n2, h_B );
magma_smake_symmetric( N, h_A, lda );
magma_smake_hpd( N, h_B, lda );
magma_spotrf( opts.uplo, N, h_B, lda, &info );
if (info != 0) {
printf("magma_spotrf returned error %lld: %s.\n",
(long long) info, magma_strerror( info ));
}
lapackf77_slacpy( MagmaFullStr, &N, &N, h_A, &lda, h_R, &lda );
/* ====================================================================
Performs operation using MAGMA
=================================================================== */
gpu_time = magma_wtime();
magma_ssygst( opts.itype, opts.uplo, N, h_R, lda, h_B, lda, &info );
gpu_time = magma_wtime() - gpu_time;
if (info != 0) {
printf("magma_ssygst returned error %lld: %s.\n",
(long long) info, magma_strerror( info ));
}
/* =====================================================================
Performs operation using LAPACK
=================================================================== */
if ( opts.lapack ) {
cpu_time = magma_wtime();
lapackf77_ssygst( &opts.itype, lapack_uplo_const(opts.uplo),
&N, h_A, &lda, h_B, &lda, &info );
cpu_time = magma_wtime() - cpu_time;
if (info != 0) {
printf("lapackf77_ssygst returned error %lld: %s.\n",
(long long) info, magma_strerror( info ));
}
blasf77_saxpy( &n2, &c_neg_one, h_A, &ione, h_R, &ione );
Anorm = safe_lapackf77_slansy("f", lapack_uplo_const(opts.uplo), &N, h_A, &lda, work );
error = safe_lapackf77_slansy("f", lapack_uplo_const(opts.uplo), &N, h_R, &lda, work )
/ Anorm;
bool okay = (error < tol);
status += ! okay;
printf("%3lld %5lld %7.2f %7.2f %8.2e %s\n",
(long long) opts.itype, (long long) N, cpu_time, gpu_time,
error, (okay ? "ok" : "failed"));
}
else {
printf("%3lld %5lld --- %7.2f\n",
(long long) opts.itype, (long long) N, gpu_time );
}
magma_free_cpu( h_A );
magma_free_cpu( h_B );
magma_free_pinned( h_R );
fflush( stdout );
}
if ( opts.niter > 1 ) {
printf( "\n" );
}
}
opts.cleanup();
TESTING_CHECK( magma_finalize() );
return status;
}
| bsd-3-clause |
dimitarp/basex | basex-core/src/main/java/org/basex/query/func/ft/FtTokenizeOptions.java | 729 | package org.basex.query.func.ft;
import org.basex.util.ft.*;
import org.basex.util.options.*;
/**
* Full-text tokenization options.
*
* @author BaseX Team 2005-20, BSD License
* @author Christian Gruen
*/
public final class FtTokenizeOptions extends Options {
/** Option: case. */
public static final EnumOption<FTCase> CASE = new EnumOption<>("case", FTCase.class);
/** Option: case. */
public static final EnumOption<FTDiacritics> DIACRITICS =
new EnumOption<>("diacritics", FTDiacritics.class);
/** Option: stemming. */
public static final BooleanOption STEMMING = new BooleanOption("stemming");
/** Option: language. */
public static final StringOption LANGUAGE = new StringOption("language");
}
| bsd-3-clause |
thermokarst/qiime2 | qiime2/util.py | 3260 | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2020, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------------------------------------
import os
import sys
import errno
import shutil
import threading
import contextlib
_REDIRECTED_STDIO_LOCK = threading.Lock()
@contextlib.contextmanager
def redirected_stdio(stdout=None, stderr=None):
with _REDIRECTED_STDIO_LOCK:
if stdout is not None:
with _redirected_fd(to=stdout, stdio=sys.stdout):
if stderr is not None:
with _redirected_fd(to=stderr, stdio=sys.stderr):
yield
else:
yield
elif stderr is not None:
with _redirected_fd(to=stderr, stdio=sys.stderr):
yield
else:
yield
# Taken whole-sale from: http://stackoverflow.com/a/22434262/579416
@contextlib.contextmanager
def _redirected_fd(to=os.devnull, stdio=None):
if stdio is None:
stdio = sys.stdout
stdio_fd = _get_fileno(stdio)
# copy stdio_fd before it is overwritten
# NOTE: `copied` is inheritable on Windows when duplicating a standard
# stream
with os.fdopen(os.dup(stdio_fd), 'wb') as copied:
stdio.flush() # flush library buffers that dup2 knows nothing about
try:
os.dup2(_get_fileno(to), stdio_fd) # $ exec >&to
except ValueError: # filename
with open(to, 'wb') as to_file:
os.dup2(to_file.fileno(), stdio_fd) # $ exec > to
try:
yield stdio # allow code to be run with the redirected stdio
finally:
# restore stdio to its previous value
# NOTE: dup2 makes stdio_fd inheritable unconditionally
stdio.flush()
os.dup2(copied.fileno(), stdio_fd) # $ exec >&copied
def _get_fileno(file_or_fd):
fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
if not isinstance(fd, int):
raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
return fd
def duplicate(src, dst):
"""Alternative to shutil.copyfile, this will use os.link when possible.
See shutil.copyfile for documention. Only `src` and `dst` are supported.
Unlike copyfile, this will not overwrite the destination if it exists.
"""
if os.path.isdir(src):
# os.link will give a permission error
raise OSError(errno.EISDIR, "Is a directory", src)
if os.path.isdir(dst):
# os.link will give a FileExists error
raise OSError(errno.EISDIR, "Is a directory", dst)
if os.path.exists(dst):
# shutil.copyfile will overwrite the existing file
raise OSError(errno.EEXIST, "File exists", src, "File exists", dst)
try:
os.link(src, dst)
except OSError as e:
if e.errno == errno.EXDEV: # Invalid cross-device link
shutil.copyfile(src, dst)
elif e.errno == errno.EPERM: # Permissions/ownership error
shutil.copyfile(src, dst)
else:
raise
| bsd-3-clause |
nas4free/nas4free | www/disks_crypt_tools.php | 10242 | <?php
/*
disks_crypt_tools.php
Part of NAS4Free (http://www.nas4free.org).
Copyright (c) 2012-2017 The NAS4Free Project <info@nas4free.org>.
All rights reserved.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the NAS4Free Project.
*/
require 'auth.inc';
require 'guiconfig.inc';
$pgtitle = [gtext('Disks'),gtext('Encryption'),gtext('Tools')];
// Omit no-cache headers because it confuses IE with file downloads.
$omit_nocacheheaders = true;
$a_geli = &array_make_branch($config,'geli','vdisk');
if(empty($a_geli)):
else:
array_sort_key($a_geli,'devicespecialfile');
endif;
$a_mount = &array_make_branch($config,'mounts','mount');
if(empty($a_mount)):
else:
array_sort_key($a_mount,'devicespecialfile');
endif;
if($config['system']['webgui']['protocol'] === "http") {
$nohttps_error = gtext("You should use HTTPS as WebGUI protocol for sending passphrase.");
}
if ($_POST) {
unset($input_errors);
// Input validation.
$reqdfields = ['disk','action'];
$reqdfieldsn = [gtext('Disk'),gtext('Command')];
if (isset($_POST['action']) && $_POST['action'] === "attach") {
$reqdfields = array_merge($reqdfields, ['passphrase']);
$reqdfieldsn = array_merge($reqdfieldsn, [gtext('Passphrase')]);
}
do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors);
if (0 != mwexec("/sbin/kldstat -q -m aesni")) {
mwexec("/sbin/kldload -q aesni.ko");
}
if (empty($input_errors)) {
$pconfig['do_action'] = true;
// Action = 'detach' => Check if device is mounted
if (($_POST['action'] === "detach") && (1 == disks_ismounted_ex($_POST['disk'], "devicespecialfile"))) {
$helpinghand = sprintf('disks_mount_tools.php?disk=%1$s&action=umount', $_POST['disk']);
$link = sprintf('<a href="%1$s">%2$s</a>', $helpinghand, gtext('Unmount this disk first before proceeding.'));
$errormsg = gtext('The encrypted device is currently mounted!') . ' ' . $link;
$pconfig['do_action'] = false;
}
$pconfig['action'] = $_POST['action'];
$pconfig['disk'] = $_POST['disk'];
$pconfig['oldpassphrase'] = $_POST['oldpassphrase'];
$pconfig['passphrase'] = $_POST['passphrase'];
// Get configuration.
$id = array_search_ex($pconfig['disk'], $a_geli, "devicespecialfile");
$geli = $a_geli[$id];
}
}
if (!isset($pconfig['action'])) {
$pconfig['do_action'] = false;
$pconfig['action'] = "";
$pconfig['disk'] = "";
$pconfig['oldpassphrase'] = "";
$pconfig['passphrase'] = "";
}
if (isset($_GET['disk'])) {
$pconfig['disk'] = $_GET['disk'];
}
if (isset($_GET['action'])) {
$pconfig['action'] = $_GET['action'];
}
if ("backup" === $pconfig['action']) {
$fn = "/var/tmp/{$geli['name']}.metadata";
mwexec("/sbin/geli backup {$geli['device'][0]} {$fn}");
$fs = get_filesize($fn);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename={$geli['name']}.metadata");
header("Content-Length: {$fs}");
readfile($fn);
unlink($fn);
exit;
}
if ("restore" === $pconfig['action']) {
if (is_uploaded_file($_FILES['backupfile']['tmp_name'])) {
$fn = "/var/tmp/{$geli['name']}.metadata";
// Move the metadata backup file so PHP won't delete it.
move_uploaded_file($_FILES['backupfile']['tmp_name'], $fn);
} else {
$errormsg = sprintf("%s %s", gtext("Failed to upload file."),
$g_file_upload_error[$_FILES['backupfile']['error']]);
}
}
?>
<?php include 'fbegin.inc';?>
<script type="text/javascript">
<!--
function action_change() {
switch(document.iform.action.value) {
case "attach":
showElementById('passphrase_tr','show');
showElementById('oldpassphrase_tr','hide');
showElementById('backupfile_tr','hide');
break;
case "setkey":
showElementById('passphrase_tr','show');
showElementById('oldpassphrase_tr','show');
showElementById('backupfile_tr','hide');
break;
case "restore":
showElementById('passphrase_tr','hide');
showElementById('oldpassphrase_tr','hide');
showElementById('backupfile_tr','show');
break;
default:
showElementById('passphrase_tr','hide');
showElementById('oldpassphrase_tr','hide');
showElementById('backupfile_tr','hide');
break;
}
}
//-->
</script>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="tabnavtbl">
<ul id="tabnav">
<li class="tabinact"><a href="disks_crypt.php"><span><?=gtext("Management");?></span></a></li>
<li class="tabact"><a href="disks_crypt_tools.php" title="<?=gtext('Reload page');?>" ><span><?=gtext("Tools");?></span></a></li>
</ul>
</td>
</tr>
<tr>
<td class="tabcont">
<?php if (!empty($nohttps_error)) print_warning_box($nohttps_error);?>
<?php if (!empty($input_errors)) print_input_errors($input_errors);?>
<?php if (!empty($errormsg)) print_error_box($errormsg);?>
<form action="disks_crypt_tools.php" method="post" name="iform" id="iform" enctype="multipart/form-data" onsubmit="spinner()">
<table width="100%" border="0" cellpadding="6" cellspacing="0">
<?php html_titleline(gtext("Encryption Tools"));?>
<tr>
<td width="22%" valign="top" class="vncellreq"><?=gtext("Disk");?></td>
<td width="78%" class="vtable">
<select name="disk" class="formfld" id="disk">
<option value=""><?=gtext("Must choose one");?></option>
<?php foreach ($a_geli as $geliv):?>
<option value="<?=$geliv['devicespecialfile'];?>" <?php if ($geliv['devicespecialfile'] === $pconfig['disk']) echo "selected=\"selected\"";?>>
<?php echo htmlspecialchars("{$geliv['name']}: {$geliv['size']} ({$geliv['desc']})");?>
</option>
<?php endforeach;?>
</select>
</td>
</tr>
<?php $options = ['attach' => gtext('Attach'),'detach' => gtext('Detach'),'setkey' => gtext('Setkey'),'list' => gtext('List'),'status' => gtext('Status'),'backup' => gtext('Backup'),'restore' => gtext('Restore')];?>
<?php html_combobox("action", gtext("Command"), $pconfig['action'], $options, "", true, false, "action_change()");?>
<tr id="oldpassphrase_tr" style="display: none">
<td width="22%" valign="top" class="vncellreq"><?=gtext("Old Passphrase");?></td>
<td width="78%" class="vtable">
<input name="oldpassphrase" type="password" class="formfld" id="oldpassphrase" size="20" />
</td>
</tr>
<tr id="passphrase_tr" style="display: none">
<td width="22%" valign="top" class="vncellreq"><?=gtext("Passphrase");?></td>
<td width="78%" class="vtable">
<input name="passphrase" type="password" class="formfld" id="passphrase" size="20" />
</td>
</tr>
<tr id="backupfile_tr" style="display: none">
<td width="22%" valign="top" class="vncellreq"><?=gtext("Backup File");?></td>
<td width="78%" class="vtable">
<input name="backupfile" type="file" class="formfld" size="40" /><br />
<span class="vexpl"><?=gtext("Restore metadata from the given file to the given provider.");?></span>
</td>
</tr>
</table>
<div id="submit">
<input name="Submit" type="submit" class="formbtn" value="<?=gtext("Execute");?>" />
</div>
<?php if ($pconfig['do_action']) {
echo(sprintf("<div id='cmdoutput'>%s</div>", gtext("Command Output:")));
echo('<pre class="cmdoutput">');
//ob_end_flush();
switch($pconfig['action']) {
case "attach":
$result = disks_geli_attach($geli['device'][0], $pconfig['passphrase'], true);
// When attaching the disk, then also mount it.
if (FALSE !== ($cnid = array_search_ex($geli['devicespecialfile'], $a_mount, "mdisk"))) {
echo("<br />" . gtext("Mounting device.") . "<br />");
echo((0 == disks_mount($a_mount[$cnid])) ? gtext("Successful.") : gtext("Failed."));
}
break;
case "detach":
$result = disks_geli_detach($geli['devicespecialfile'], true);
echo((0 == $result) ? gtext("Done.") : gtext("Failed."));
break;
case "setkey":
disks_geli_setkey($geli['devicespecialfile'], $pconfig['oldpassphrase'], $pconfig['passphrase'], true);
break;
case "list":
system("/sbin/geli list");
break;
case "status":
system("/sbin/geli status");
break;
case "restore":
$fn = "/var/tmp/{$geli['name']}.metadata";
if (file_exists($fn)) {
system("/sbin/geli restore -v {$fn} {$geli['devicespecialfile']}");
unlink($fn);
} else {
echo gtext("Failed to upload metadata backup file.");
}
break;
}
echo('</pre>');
}?>
<?php include 'formend.inc';?>
</form>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
action_change();
//-->
</script>
<?php include 'fend.inc';?>
| bsd-3-clause |
ANYbotics/grid_map | grid_map_demos/src/GridmapToImageDemo.cpp | 1496 | /*
* GridMapToImageDemo.cpp
*
* Created on: October 19, 2020
* Author: Magnus Gärtner
* Institute: ETH Zurich, ANYbotics
*/
#include "grid_map_demos/GridmapToImageDemo.hpp"
#include <image_transport/image_transport.h>
#include <opencv2/imgcodecs.hpp>
namespace grid_map_demos {
GridMapToImageDemo::GridMapToImageDemo(ros::NodeHandle& nodeHandle)
: nodeHandle_(nodeHandle)
{
readParameters();
gridMapSubscriber_ = nodeHandle_.subscribe(gridMapTopic_, 1, &GridMapToImageDemo::gridMapCallback, this);
ROS_ERROR("Subscribed to %s", nodeHandle_.resolveName(gridMapTopic_).c_str());
}
GridMapToImageDemo::~GridMapToImageDemo()=default;
void GridMapToImageDemo::readParameters()
{
nodeHandle_.param("grid_map_topic", gridMapTopic_, std::string("/grid_map"));
nodeHandle_.param("file", filePath_, std::string("~/.ros/grid_map.png"));
}
void GridMapToImageDemo::gridMapCallback(const grid_map_msgs::GridMap& msg)
{
ROS_INFO("Saving map received from: %s to file %s.", nodeHandle_.resolveName(gridMapTopic_).c_str(), filePath_.c_str());
grid_map::GridMap map;
cv_bridge::CvImage image;
grid_map::GridMapRosConverter::fromMessage(msg, map, {"elevation"});
grid_map::GridMapRosConverter::toCvImage(map,"elevation", sensor_msgs::image_encodings::MONO8, image);
bool success = cv::imwrite(filePath_.c_str(),image.image, {cv::IMWRITE_PNG_STRATEGY_DEFAULT});
ROS_INFO("Success writing image: %s", success?"true":"false");
ros::shutdown();
}
} /* namespace */
| bsd-3-clause |
meishichao/yii2test | vendor/bower/jquery.inputmask/dist/jquery.inputmask.bundle.min.js | 111067 | /*!
* jquery.inputmask.bundle
* http://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) 2010 - 2015 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 3.1.62
*/
!function (a) {
function b(a) {
var b = document.createElement("input"), c = "on" + a, d = c in b;
return d || (b.setAttribute(c, "return;"), d = "function" == typeof b[c]), b = null, d
}
function c(a) {
var b = "text" == a || "tel" == a;
if (!b) {
var c = document.createElement("input");
c.setAttribute("type", a), b = "text" === c.type, c = null
}
return b
}
function d(b, c, e) {
var f = e.aliases[b];
return f ? (f.alias && d(f.alias, void 0, e), a.extend(!0, e, f), a.extend(!0, e, c), !0) : !1
}
function e(b, c) {
function d(c) {
function d(a, b, c, d) {
this.matches = [], this.isGroup = a || !1, this.isOptional = b || !1, this.isQuantifier = c || !1, this.isAlternator = d || !1, this.quantifier = {
min: 1,
max: 1
}
}
function e(c, d, e) {
var f = b.definitions[d], g = 0 == c.matches.length;
if (e = void 0 != e ? e : c.matches.length, f && !m) {
f.placeholder = a.isFunction(f.placeholder) ? f.placeholder.call(this, b) : f.placeholder;
for (var h = f.prevalidator, i = h ? h.length : 0, j = 1; j < f.cardinality; j++) {
var k = i >= j ? h[j - 1] : [], l = k.validator, n = k.cardinality;
c.matches.splice(e++, 0, {
fn: l ? "string" == typeof l ? new RegExp(l) : new function () {
this.test = l
} : new RegExp("."),
cardinality: n ? n : 1,
optionality: c.isOptional,
newBlockMarker: g,
casing: f.casing,
def: f.definitionSymbol || d,
placeholder: f.placeholder,
mask: d
})
}
c.matches.splice(e++, 0, {
fn: f.validator ? "string" == typeof f.validator ? new RegExp(f.validator) : new function () {
this.test = f.validator
} : new RegExp("."),
cardinality: f.cardinality,
optionality: c.isOptional,
newBlockMarker: g,
casing: f.casing,
def: f.definitionSymbol || d,
placeholder: f.placeholder,
mask: d
})
} else {
c.matches.splice(e++, 0, {
fn: null,
cardinality: 0,
optionality: c.isOptional,
newBlockMarker: g,
casing: null,
def: d,
placeholder: void 0,
mask: d
}), m = !1
}
}
for (var f, g, h, i, j, k, l = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})\??|[^.?*+^${[]()|\\]+|./g, m = !1, n = new d, o = [], p = []; f = l.exec(c);)switch (g = f[0], g.charAt(0)) {
case b.optionalmarker.end:
case b.groupmarker.end:
if (h = o.pop(), o.length > 0) {
if (i = o[o.length - 1], i.matches.push(h), i.isAlternator) {
j = o.pop();
for (var q = 0; q < j.matches.length; q++)j.matches[q].isGroup = !1;
o.length > 0 ? (i = o[o.length - 1], i.matches.push(j)) : n.matches.push(j)
}
} else {
n.matches.push(h);
}
break;
case b.optionalmarker.start:
o.push(new d(!1, !0));
break;
case b.groupmarker.start:
o.push(new d(!0));
break;
case b.quantifiermarker.start:
var r = new d(!1, !1, !0);
g = g.replace(/[{}]/g, "");
var s = g.split(","), t = isNaN(s[0]) ? s[0] : parseInt(s[0]), u = 1 == s.length ? t : isNaN(s[1]) ? s[1] : parseInt(s[1]);
if (("*" == u || "+" == u) && (t = "*" == u ? 0 : 1), r.quantifier = {
min: t,
max: u
}, o.length > 0) {
var v = o[o.length - 1].matches;
if (f = v.pop(), !f.isGroup) {
var w = new d(!0);
w.matches.push(f), f = w
}
v.push(f), v.push(r)
} else {
if (f = n.matches.pop(), !f.isGroup) {
var w = new d(!0);
w.matches.push(f), f = w
}
n.matches.push(f), n.matches.push(r)
}
break;
case b.escapeChar:
m = !0;
break;
case b.alternatormarker:
o.length > 0 ? (i = o[o.length - 1], k = i.matches.pop()) : k = n.matches.pop(), k.isAlternator ? o.push(k) : (j = new d(!1, !1, !1, !0), j.matches.push(k), o.push(j));
break;
default:
if (o.length > 0) {
if (i = o[o.length - 1], i.matches.length > 0 && !i.isAlternator && (k = i.matches[i.matches.length - 1], k.isGroup && (k.isGroup = !1, e(k, b.groupmarker.start, 0), e(k, b.groupmarker.end))), e(i, g), i.isAlternator) {
j = o.pop();
for (var q = 0; q < j.matches.length; q++)j.matches[q].isGroup = !1;
o.length > 0 ? (i = o[o.length - 1], i.matches.push(j)) : n.matches.push(j)
}
} else {
n.matches.length > 0 && (k = n.matches[n.matches.length - 1], k.isGroup && (k.isGroup = !1, e(k, b.groupmarker.start, 0), e(k, b.groupmarker.end))), e(n, g)
}
}
return n.matches.length > 0 && (k = n.matches[n.matches.length - 1], k.isGroup && (k.isGroup = !1, e(k, b.groupmarker.start, 0), e(k, b.groupmarker.end)), p.push(n)), p
}
function e(e, f) {
if (void 0 == e || "" == e) {
return void 0;
}
if (1 == e.length && 0 == b.greedy && 0 != b.repeat && (b.placeholder = ""), b.repeat > 0 || "*" == b.repeat || "+" == b.repeat) {
var g = "*" == b.repeat ? 0 : "+" == b.repeat ? 1 : b.repeat;
e = b.groupmarker.start + e + b.groupmarker.end + b.quantifiermarker.start + g + "," + b.repeat + b.quantifiermarker.end
}
var h;
return void 0 == a.inputmask.masksCache[e] || c === !0 ? (h = {
mask: e,
maskToken: d(e),
validPositions: {},
_buffer: void 0,
buffer: void 0,
tests: {},
metadata: f
}, c !== !0 && (a.inputmask.masksCache[e] = h)) : h = a.extend(!0, {}, a.inputmask.masksCache[e]), h
}
function f(a) {
if (a = a.toString(), b.numericInput) {
a = a.split("").reverse();
for (var c = 0; c < a.length; c++)a[c] == b.optionalmarker.start ? a[c] = b.optionalmarker.end : a[c] == b.optionalmarker.end ? a[c] = b.optionalmarker.start : a[c] == b.groupmarker.start ? a[c] = b.groupmarker.end : a[c] == b.groupmarker.end && (a[c] = b.groupmarker.start);
a = a.join("")
}
return a
}
var g = void 0;
if (a.isFunction(b.mask) && (b.mask = b.mask.call(this, b)), a.isArray(b.mask)) {
if (b.mask.length > 1) {
b.keepStatic = void 0 == b.keepStatic ? !0 : b.keepStatic;
var h = "(";
return a.each(b.mask, function (b, c) {
h.length > 1 && (h += ")|("), h += f(void 0 == c.mask || a.isFunction(c.mask) ? c : c.mask)
}), h += ")", e(h, b.mask)
}
b.mask = b.mask.pop()
}
return b.mask && (g = void 0 == b.mask.mask || a.isFunction(b.mask.mask) ? e(f(b.mask), b.mask) : e(f(b.mask.mask), b.mask)), g
}
function f(d, e, f) {
function g(a, b, c) {
b = b || 0;
var d, e, f, g = [], h = 0;
do {
if (a === !0 && l().validPositions[h]) {
var i = l().validPositions[h];
e = i.match, d = i.locator.slice(), g.push(c === !0 ? i.input : G(h, e))
} else {
f = q(h, d, h - 1), e = f.match, d = f.locator.slice(), g.push(G(h, e));
}
h++
} while ((void 0 == da || da > h - 1) && null != e.fn || null == e.fn && "" != e.def || b >= h);
return g.pop(), g
}
function l() {
return e
}
function m(a) {
var b = l();
b.buffer = void 0, b.tests = {}, a !== !0 && (b._buffer = void 0, b.validPositions = {}, b.p = 0)
}
function n(a, b) {
var c = l(), d = -1, e = c.validPositions;
void 0 == a && (a = -1);
var f = d, g = d;
for (var h in e) {
var i = parseInt(h);
e[i] && (b || null != e[i].match.fn) && (a >= i && (f = i), i >= a && (g = i))
}
return d = -1 != f && a - f > 1 || a > g ? f : g
}
function o(b, c, d) {
if (f.insertMode && void 0 != l().validPositions[b] && void 0 == d) {
var e, g = a.extend(!0, {}, l().validPositions), h = n();
for (e = b; h >= e; e++)delete l().validPositions[e];
l().validPositions[b] = c;
var i, j = !0, k = l().validPositions;
for (e = i = b; h >= e; e++) {
var m = g[e];
if (void 0 != m) {
for (var o = i; o < B() && (null == m.match.fn && k[e] && (k[e].match.optionalQuantifier === !0 || k[e].match.optionality === !0) || null != m.match.fn);) {
if (null == m.match.fn || !f.keepStatic && k[e] && (void 0 != k[e + 1] && t(e + 1, k[e].locator.slice(), e).length > 1 || void 0 != k[e].alternation) ? o++ : o = C(i), s(o, m.match.def)) {
j = z(o, m.input, !0, !0) !== !1, i = o;
break
}
j = null == m.match.fn
}
}
if (!j) {
break
}
}
if (!j) {
return l().validPositions = a.extend(!0, {}, g), !1
}
} else {
l().validPositions[b] = c;
}
return !0
}
function p(a, b, c, d) {
var e, g = a;
l().p = a, void 0 != l().validPositions[a] && l().validPositions[a].input == f.radixPoint && (b++, g++);
for (e = g; b > e; e++)void 0 != l().validPositions[e] && (c === !0 || 0 != f.canClearPosition(l(), e, n(), d, f)) && delete l().validPositions[e];
for (m(!0), e = g + 1; e <= n();) {
for (; void 0 != l().validPositions[g];)g++;
var h = l().validPositions[g];
g > e && (e = g + 1);
var i = l().validPositions[e];
void 0 != i && void 0 == h ? (s(g, i.match.def) && z(g, i.input, !0) !== !1 && (delete l().validPositions[e], e++), g++) : e++
}
var j = n(), k = B();
for (j >= a && void 0 != l().validPositions[j] && l().validPositions[j].input == f.radixPoint && delete l().validPositions[j], e = j + 1; k >= e; e++)l().validPositions[e] && delete l().validPositions[e];
m(!0)
}
function q(a, b, c) {
var d = l().validPositions[a];
if (void 0 == d) {
for (var e = t(a, b, c), g = n(), h = l().validPositions[g] || t(0, void 0, void 0)[0], i = void 0 != h.alternation ? h.locator[h.alternation].toString().split(",") : [], j = 0; j < e.length && (d = e[j], !(d.match && (f.greedy && d.match.optionalQuantifier !== !0 || (d.match.optionality === !1 || d.match.newBlockMarker === !1) && d.match.optionalQuantifier !== !0) && (void 0 == h.alternation || void 0 != d.locator[h.alternation] && y(d.locator[h.alternation].toString().split(","), i)))); j++);
}
return d
}
function r(a) {
return l().validPositions[a] ? l().validPositions[a].match : t(a)[0].match
}
function s(a, b) {
for (var c = !1, d = t(a), e = 0; e < d.length; e++)if (d[e].match && d[e].match.def == b) {
c = !0;
break
}
return c
}
function t(b, c, d, e) {
function f(c, d, e, g) {
function i(e, g, n) {
if (h > 1e4) {
return alert("jquery.inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + l().mask), !0;
}
if (h == b && void 0 == e.matches) {
return j.push({match: e, locator: g.reverse()}), !0;
}
if (void 0 != e.matches) {
if (e.isGroup && n !== !0) {
if (e = i(c.matches[m + 1], g)) {
return !0
}
} else if (e.isOptional) {
var o = e;
if (e = f(e, d, g, n)) {
var p = j[j.length - 1].match, q = 0 == a.inArray(p, o.matches);
if (!q) {
return !0;
}
k = !0, h = b
}
} else if (e.isAlternator) {
var r, s = e, t = [], u = j.slice(), v = g.length, w = d.length > 0 ? d.shift() : -1;
if (-1 == w || "string" == typeof w) {
var x, y = h, z = d.slice();
"string" == typeof w && (x = w.split(","));
for (var A = 0; A < s.matches.length; A++) {
j = [], e = i(s.matches[A], [A].concat(g), n) || e, r = j.slice(), h = y, j = [];
for (var B = 0; B < z.length; B++)d[B] = z[B];
for (var C = 0; C < r.length; C++) {
var D = r[C];
D.alternation = v;
for (var E = 0; E < t.length; E++) {
var F = t[E];
if (D.match.mask == F.match.mask && ("string" != typeof w || -1 != a.inArray(D.locator[v].toString(), x))) {
r.splice(C, 1), F.locator[v] = F.locator[v] + "," + D.locator[v], F.alternation = v;
break
}
}
}
t = t.concat(r)
}
"string" == typeof w && (t = a.map(t, function (b, c) {
if (isFinite(c)) {
var d, e = b.locator[v].toString().split(",");
b.locator[v] = void 0, b.alternation = void 0;
for (var f = 0; f < e.length; f++)d = -1 != a.inArray(e[f], x), d && (void 0 != b.locator[v] ? (b.locator[v] += ",", b.locator[v] += e[f]) : b.locator[v] = parseInt(e[f]), b.alternation = v);
if (void 0 != b.locator[v]) {
return b
}
}
})), j = u.concat(t), h = b, k = !0
} else {
e = i(s.matches[w], [w].concat(g), n);
}
if (e) {
return !0
}
} else if (e.isQuantifier && n !== !0) {
for (var G = e, H = d.length > 0 && n !== !0 ? d.shift() : 0; H < (isNaN(G.quantifier.max) ? H + 1 : G.quantifier.max) && b >= h; H++) {
var I = c.matches[a.inArray(G, c.matches) - 1];
if (e = i(I, [H].concat(g), !0)) {
var p = j[j.length - 1].match;
p.optionalQuantifier = H > G.quantifier.min - 1;
var q = 0 == a.inArray(p, I.matches);
if (q) {
if (H > G.quantifier.min - 1) {
k = !0, h = b;
break
}
return !0
}
return !0
}
}
} else if (e = f(e, d, g, n)) {
return !0
}
} else {
h++
}
}
for (var m = d.length > 0 ? d.shift() : 0; m < c.matches.length; m++)if (c.matches[m].isQuantifier !== !0) {
var n = i(c.matches[m], [m].concat(e), g);
if (n && h == b) {
return n;
}
if (h > b) {
break
}
}
}
var g = l().maskToken, h = c ? d : 0, i = c || [0], j = [], k = !1;
if (void 0 == c) {
for (var m, n = b - 1; void 0 == (m = l().validPositions[n]) && n > -1;)n--;
if (void 0 != m && n > -1) {
h = n, i = m.locator.slice();
} else {
for (n = b - 1; void 0 == (m = l().tests[n]) && n > -1;)n--;
void 0 != m && n > -1 && (h = n, i = m[0].locator.slice())
}
}
for (var o = i.shift(); o < g.length; o++) {
var p = f(g[o], i, [o]);
if (p && h == b || h > b) {
break
}
}
return (0 == j.length || k) && j.push({
match: {
fn: null,
cardinality: 0,
optionality: !0,
casing: null,
def: ""
}, locator: []
}), l().tests[b] = a.extend(!0, [], j), l().tests[b]
}
function u() {
return void 0 == l()._buffer && (l()._buffer = g(!1, 1)), l()._buffer
}
function v() {
return void 0 == l().buffer && (l().buffer = g(!0, n(), !0)), l().buffer
}
function w(a, b, c) {
if (c = c || v().slice(), a === !0) {
m(), a = 0, b = c.length;
} else {
for (var d = a; b > d; d++)delete l().validPositions[d], delete l().tests[d];
}
for (var d = a; b > d; d++)c[d] != f.skipOptionalPartCharacter && z(d, c[d], !0, !0)
}
function x(a, b) {
switch (b.casing) {
case"upper":
a = a.toUpperCase();
break;
case"lower":
a = a.toLowerCase()
}
return a
}
function y(b, c) {
for (var d = f.greedy ? c : c.slice(0, 1), e = !1, g = 0; g < b.length; g++)if (-1 != a.inArray(b[g], d)) {
e = !0;
break
}
return e
}
function z(b, c, d, e) {
function g(b, c, d, e) {
var g = !1;
return a.each(t(b), function (h, i) {
for (var j = i.match, k = c ? 1 : 0, q = "", r = (v(), j.cardinality); r > k; r--)q += E(b - (r - 1));
if (c && (q += c), g = null != j.fn ? j.fn.test(q, l(), b, d, f) : c != j.def && c != f.skipOptionalPartCharacter || "" == j.def ? !1 : {
c: j.def,
pos: b
}, g !== !1) {
var s = void 0 != g.c ? g.c : c;
s = s == f.skipOptionalPartCharacter && null === j.fn ? j.def : s;
var t = b, u = v();
if (void 0 != g.remove && (a.isArray(g.remove) || (g.remove = [g.remove]), a.each(g.remove.sort(function (a, b) {
return b - a
}), function (a, b) {
p(b, b + 1, !0)
})), void 0 != g.insert && (a.isArray(g.insert) || (g.insert = [g.insert]), a.each(g.insert.sort(function (a, b) {
return a - b
}), function (a, b) {
z(b.pos, b.c, !0)
})), g.refreshFromBuffer) {
var y = g.refreshFromBuffer;
if (d = !0, w(y === !0 ? y : y.start, y.end, u), void 0 == g.pos && void 0 == g.c) {
return g.pos = n(), !1;
}
if (t = void 0 != g.pos ? g.pos : b, t != b) {
return g = a.extend(g, z(t, s, !0)), !1
}
} else if (g !== !0 && void 0 != g.pos && g.pos != b && (t = g.pos, w(b, t), t != b)) {
return g = a.extend(g, z(t, s, !0)), !1;
}
return 1 != g && void 0 == g.pos && void 0 == g.c ? !1 : (h > 0 && m(!0), o(t, a.extend({}, i, {input: x(s, j)}), e) || (g = !1), !1)
}
}), g
}
function h(b, c, d, e) {
var g, h, i, j, k = a.extend(!0, {}, l().validPositions);
for (g = n(); g >= 0; g--)if (j = l().validPositions[g], j && void 0 != j.alternation && j.locator[j.alternation].length > 1) {
h = l().validPositions[g].alternation;
break
}
if (void 0 != h) {
for (var o in l().validPositions)if (j = l().validPositions[o], parseInt(o) > parseInt(g) && j.alternation) {
for (var p = j.locator[h], q = l().validPositions[g].locator[h].toString().split(","), r = 0; r < q.length; r++)if (p < q[r]) {
for (var s, t, u = o - 1; u >= 0; u--)if (s = l().validPositions[u], void 0 != s) {
t = s.locator[h], s.locator[h] = parseInt(q[r]);
break
}
if (p != s.locator[h]) {
for (var v = [], w = o; w < n() + 1; w++) {
var x = l().validPositions[w];
x && null != x.match.fn && v.push(x.input), delete l().validPositions[w], delete l().tests[w]
}
for (m(!0), f.keepStatic = !f.keepStatic, i = !0; v.length > 0;) {
var y = v.shift();
if (y != f.skipOptionalPartCharacter && !(i = z(n() + 1, y, !1, !0))) {
break
}
}
if (s.alternation = h, s.locator[h] = t, i && (i = z(b, c, d, e)), f.keepStatic = !f.keepStatic, i) {
return i;
}
m(), l().validPositions = a.extend(!0, {}, k)
}
}
break
}
}
return !1
}
function i(b, c) {
for (var d = l().validPositions[c], e = d.locator, f = e.length, g = b; c > g; g++)if (!A(g)) {
var h = t(g), i = h[0], j = -1;
a.each(h, function (a, b) {
for (var c = 0; f > c; c++)b.locator[c] && y(b.locator[c].toString().split(","), e[c].toString().split(",")) && c > j && (j = c, i = b)
}), o(g, a.extend({}, i, {input: i.match.def}), !0)
}
}
d = d === !0;
for (var j = v(), k = b - 1; k > -1 && !l().validPositions[k]; k--);
for (k++; b > k; k++)void 0 == l().validPositions[k] && ((!A(k) || j[k] != G(k)) && t(k).length > 1 || j[k] == f.radixPoint || "0" == j[k] && a.inArray(f.radixPoint, j) < k) && g(k, j[k], !0);
var q = b, r = !1, s = a.extend(!0, {}, l().validPositions);
if (q < B() && (r = g(q, c, d, e), (!d || e) && r === !1)) {
var u = l().validPositions[q];
if (!u || null != u.match.fn || u.match.def != c && c != f.skipOptionalPartCharacter) {
if ((f.insertMode || void 0 == l().validPositions[C(q)]) && !A(q)) {
for (var D = q + 1, F = C(q); F >= D; D++)if (r = g(D, c, d, e), r !== !1) {
i(q, D), q = D;
break
}
}
} else {
r = {caret: C(q)}
}
}
if (r === !1 && f.keepStatic && O(j) && (r = h(b, c, d, e)), r === !0 && (r = {pos: q}), a.isFunction(f.postValidation) && 0 != r && !d) {
m(!0);
var H = f.postValidation(v(), f);
if (!H) {
return m(!0), l().validPositions = a.extend(!0, {}, s), !1
}
}
return r
}
function A(a) {
var b = r(a);
if (null != b.fn) {
return b.fn;
}
if (!f.keepStatic && void 0 == l().validPositions[a]) {
for (var c = t(a), d = !0, e = 0; e < c.length; e++)if ("" != c[e].match.def && (null !== c[e].match.fn || void 0 == c[e].alternation || c[e].locator[c[e].alternation].length > 1)) {
d = !1;
break
}
return d
}
return !1
}
function B() {
var a;
da = ca.prop("maxLength"), -1 == da && (da = void 0);
var b, c = n(), d = l().validPositions[c], e = void 0 != d ? d.locator.slice() : void 0;
for (b = c + 1; void 0 == d || null != d.match.fn || null == d.match.fn && "" != d.match.def; b++)d = q(b, e, b - 1), e = d.locator.slice();
var f = r(b - 1);
return a = "" != f.def ? b : b - 1, void 0 == da || da > a ? a : da
}
function C(a) {
var b = B();
if (a >= b) {
return b;
}
for (var c = a; ++c < b && !A(c) && (f.nojumps !== !0 || f.nojumpsThreshold > c););
return c
}
function D(a) {
var b = a;
if (0 >= b) {
return 0;
}
for (; --b > 0 && !A(b););
return b
}
function E(a) {
return void 0 == l().validPositions[a] ? G(a) : l().validPositions[a].input
}
function F(b, c, d, e, g) {
if (e && a.isFunction(f.onBeforeWrite)) {
var h = f.onBeforeWrite.call(b, e, c, d, f);
if (h) {
if (h.refreshFromBuffer) {
var i = h.refreshFromBuffer;
w(i === !0 ? i : i.start, i.end, h.buffer), m(!0), c = v()
}
d = h.caret || d
}
}
b._valueSet(c.join("")), void 0 != d && L(b, d), g === !0 && (ga = !0, a(b).trigger("input"))
}
function G(a, b) {
if (b = b || r(a), void 0 != b.placeholder) {
return b.placeholder;
}
if (null == b.fn) {
if (!f.keepStatic && void 0 == l().validPositions[a]) {
for (var c = t(a), d = !0, e = 0; e < c.length; e++)if ("" != c[e].match.def && (null !== c[e].match.fn || void 0 == c[e].alternation || c[e].locator[c[e].alternation].length > 1)) {
d = !1;
break
}
if (d) {
return f.placeholder.charAt(a % f.placeholder.length)
}
}
return b.def
}
return f.placeholder.charAt(a % f.placeholder.length)
}
function H(b, c, d, e) {
function f() {
var a = !1, b = u().slice(i, C(i)).join("").indexOf(h);
if (-1 != b && !A(i)) {
a = !0;
for (var c = u().slice(i, i + b), d = 0; d < c.length; d++)if (" " != c[d]) {
a = !1;
break
}
}
return a
}
var g = void 0 != e ? e.slice() : b._valueGet().split(""), h = "", i = 0;
if (m(), l().p = C(-1), c && b._valueSet(""), !d) {
var j = u().slice(0, C(-1)).join(""), k = g.join("").match(new RegExp(I(j), "g"));
k && k.length > 0 && (g.splice(0, k.length * j.length), i = C(i))
}
a.each(g, function (c, e) {
var g = a.Event("keypress");
g.which = e.charCodeAt(0), h += e;
var j = n(void 0, !0), k = l().validPositions[j], m = q(j + 1, k ? k.locator.slice() : void 0, j);
if (!f() || d) {
var o = d ? c : null == m.match.fn && m.match.optionality && j + 1 < l().p ? j + 1 : l().p;
U.call(b, g, !0, !1, d, o), i = o + 1, h = ""
} else {
U.call(b, g, !0, !1, !0, j + 1)
}
}), c && F(b, v(), a(b).is(":focus") ? C(n(0)) : void 0, a.Event("checkval"))
}
function I(b) {
return a.inputmask.escapeRegex(b)
}
function J(b) {
if (b.data("_inputmask") && !b.hasClass("hasDatepicker")) {
var c = [], d = l().validPositions;
for (var e in d)d[e].match && null != d[e].match.fn && c.push(d[e].input);
var g = (ea ? c.reverse() : c).join(""), h = (ea ? v().slice().reverse() : v()).join("");
return a.isFunction(f.onUnMask) && (g = f.onUnMask.call(b, h, g, f) || g), g
}
return b[0]._valueGet()
}
function K(a) {
if (ea && "number" == typeof a && (!f.greedy || "" != f.placeholder)) {
var b = v().length;
a = b - a
}
return a
}
function L(b, c, d) {
var e, g = b.jquery && b.length > 0 ? b[0] : b;
if ("number" != typeof c) {
return g.setSelectionRange ? (c = g.selectionStart, d = g.selectionEnd) : window.getSelection ? (e = window.getSelection().getRangeAt(0), e.commonAncestorContainer.parentNode == g && (c = e.startOffset, d = e.endOffset)) : document.selection && document.selection.createRange && (e = document.selection.createRange(), c = 0 - e.duplicate().moveStart("character", -1e5), d = c + e.text.length), {
begin: K(c),
end: K(d)
};
}
if (c = K(c), d = K(d), d = "number" == typeof d ? d : c, a(g).is(":visible")) {
var h = a(g).css("font-size").replace("px", "") * d;
if (g.scrollLeft = h > g.scrollWidth ? h : 0, i || 0 != f.insertMode || c != d || d++, g.setSelectionRange) {
g.selectionStart = c, g.selectionEnd = d;
} else if (window.getSelection) {
e = document.createRange(), e.setStart(g.firstChild, c < g._valueGet().length ? c : g._valueGet().length), e.setEnd(g.firstChild, d < g._valueGet().length ? d : g._valueGet().length), e.collapse(!0);
var j = window.getSelection();
j.removeAllRanges(), j.addRange(e)
} else {
g.createTextRange && (e = g.createTextRange(), e.collapse(!0), e.moveEnd("character", d), e.moveStart("character", c), e.select())
}
}
}
function M(b) {
var c, d, e = v(), f = e.length, g = n(), h = {}, i = l().validPositions[g], j = void 0 != i ? i.locator.slice() : void 0;
for (c = g + 1; c < e.length; c++)d = q(c, j, c - 1), j = d.locator.slice(), h[c] = a.extend(!0, {}, d);
var k = i && void 0 != i.alternation ? i.locator[i.alternation] : void 0;
for (c = f - 1; c > g && (d = h[c].match, (d.optionality || d.optionalQuantifier || k && k != h[c].locator[i.alternation]) && e[c] == G(c, d)); c--)f--;
return b ? {l: f, def: h[f] ? h[f].match : void 0} : f
}
function N(a) {
for (var b = M(), c = a.length - 1; c > b && !A(c); c--);
return a.splice(b, c + 1 - b), a
}
function O(b) {
if (a.isFunction(f.isComplete)) {
return f.isComplete.call(ca, b, f);
}
if ("*" == f.repeat) {
return void 0;
}
{
var c = !1, d = M(!0), e = D(d.l);
n()
}
if (void 0 == d.def || d.def.newBlockMarker || d.def.optionality || d.def.optionalQuantifier) {
c = !0;
for (var g = 0; e >= g; g++) {
var h = A(g), i = r(g);
if (h && void 0 == l().validPositions[g] && i.optionality !== !0 && i.optionalQuantifier !== !0 || !h && b[g] != G(g)) {
c = !1;
break
}
}
}
return c
}
function P(a, b) {
return ea ? a - b > 1 || a - b == 1 && f.insertMode : b - a > 1 || b - a == 1 && f.insertMode
}
function Q(b) {
var c = a._data(b).events, d = !1;
a.each(c, function (b, c) {
a.each(c, function (a, b) {
if ("inputmask" == b.namespace && "setvalue" != b.type) {
var c = b.handler;
b.handler = function (a) {
if (!this.disabled && (!this.readOnly || "keydown" == a.type && a.ctrlKey && 67 == a.keyCode)) {
switch (a.type) {
case"input":
if (ga === !0 || d === !0) {
return ga = !1, a.preventDefault();
}
break;
case"keydown":
fa = !1, d = !1;
break;
case"keypress":
if (fa === !0) {
return a.preventDefault();
}
fa = !0;
break;
case"compositionstart":
d = !0;
break;
case"compositionupdate":
ga = !0;
break;
case"compositionend":
d = !1
}
return c.apply(this, arguments)
}
a.preventDefault()
}
}
})
})
}
function R(b) {
function c(b) {
if (void 0 == a.valHooks[b] || 1 != a.valHooks[b].inputmaskpatch) {
var c = a.valHooks[b] && a.valHooks[b].get ? a.valHooks[b].get : function (a) {
return a.value
}, d = a.valHooks[b] && a.valHooks[b].set ? a.valHooks[b].set : function (a, b) {
return a.value = b, a
};
a.valHooks[b] = {
get: function (b) {
var d = a(b);
if (d.data("_inputmask")) {
if (d.data("_inputmask").opts.autoUnmask) {
return d.inputmask("unmaskedvalue");
}
var e = c(b), f = d.data("_inputmask"), g = f.maskset, h = g._buffer;
return h = h ? h.join("") : "", e != h ? e : ""
}
return c(b)
}, set: function (b, c) {
var e, f = a(b), g = f.data("_inputmask");
return e = d(b, c), g && f.triggerHandler("setvalue.inputmask"), e
}, inputmaskpatch: !0
}
}
}
function d() {
var b = a(this), c = a(this).data("_inputmask");
return c ? c.opts.autoUnmask ? b.inputmask("unmaskedvalue") : g.call(this) != u().join("") ? g.call(this) : "" : g.call(this)
}
function e(b) {
var c = a(this).data("_inputmask");
h.call(this, b), c && a(this).triggerHandler("setvalue.inputmask")
}
function f(b) {
a(b).bind("mouseenter.inputmask", function () {
var b = a(this), c = this, d = c._valueGet();
"" != d && d != v().join("") && b.triggerHandler("setvalue.inputmask")
});
//!! the bound handlers are executed in the order they where bound
var c = a._data(b).events, d = c.mouseover;
if (d) {
for (var e = d[d.length - 1], f = d.length - 1; f > 0; f--)d[f] = d[f - 1];
d[0] = e
}
}
var g, h;
if (!b._valueGet) {
var i;
Object.getOwnPropertyDescriptor && void 0 == b.value ? (g = function () {
return this.textContent
}, h = function (a) {
this.textContent = a
}, Object.defineProperty(b, "value", {
get: d,
set: e
})) : ((i = Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(b, "value")) && i.configurable, document.__lookupGetter__ && b.__lookupGetter__("value") ? (g = b.__lookupGetter__("value"), h = b.__lookupSetter__("value"), b.__defineGetter__("value", d), b.__defineSetter__("value", e)) : (g = function () {
return b.value
}, h = function (a) {
b.value = a
}, c(b.type), f(b))), b._valueGet = function (a) {
return ea && a !== !0 ? g.call(this).split("").reverse().join("") : g.call(this)
}, b._valueSet = function (a) {
h.call(this, ea ? a.split("").reverse().join("") : a)
}
}
}
function S(b, c, d, e) {
function g() {
if (f.keepStatic) {
m(!0);
var c, d = [], e = a.extend(!0, {}, l().validPositions);
for (c = n(); c >= 0; c--) {
var g = l().validPositions[c];
if (g) {
if (void 0 != g.alternation && g.locator[g.alternation] == q(c).locator[g.alternation]) {
break;
}
null != g.match.fn && d.push(g.input), delete l().validPositions[c]
}
}
if (c > 0) {
for (; d.length > 0;) {
l().p = C(n());
var h = a.Event("keypress");
h.which = d.pop().charCodeAt(0), U.call(b, h, !0, !1, !1, l().p)
}
} else {
l().validPositions = a.extend(!0, {}, e)
}
}
}
if ((f.numericInput || ea) && (c == a.inputmask.keyCode.BACKSPACE ? c = a.inputmask.keyCode.DELETE : c == a.inputmask.keyCode.DELETE && (c = a.inputmask.keyCode.BACKSPACE), ea)) {
var h = d.end;
d.end = d.begin, d.begin = h
}
if (c == a.inputmask.keyCode.BACKSPACE && (d.end - d.begin < 1 || 0 == f.insertMode) ? d.begin = D(d.begin) : c == a.inputmask.keyCode.DELETE && d.begin == d.end && (d.end = A(d.end) ? d.end + 1 : C(d.end) + 1), p(d.begin, d.end, !1, e), e !== !0) {
g();
var i = n(d.begin);
i < d.begin ? (-1 == i && m(), l().p = C(i)) : l().p = d.begin
}
}
function T(c) {
var d = this, e = a(d), g = c.keyCode, i = L(d);
g == a.inputmask.keyCode.BACKSPACE || g == a.inputmask.keyCode.DELETE || h && 127 == g || c.ctrlKey && 88 == g && !b("cut") ? (c.preventDefault(), 88 == g && (_ = v().join("")), S(d, g, i), F(d, v(), l().p, c, _ != v().join("")), d._valueGet() == u().join("") ? e.trigger("cleared") : O(v()) === !0 && e.trigger("complete"), f.showTooltip && e.prop("title", l().mask)) : g == a.inputmask.keyCode.END || g == a.inputmask.keyCode.PAGE_DOWN ? setTimeout(function () {
var a = C(n());
f.insertMode || a != B() || c.shiftKey || a--, L(d, c.shiftKey ? i.begin : a, a)
}, 0) : g == a.inputmask.keyCode.HOME && !c.shiftKey || g == a.inputmask.keyCode.PAGE_UP ? L(d, 0, c.shiftKey ? i.begin : 0) : (f.undoOnEscape && g == a.inputmask.keyCode.ESCAPE || 90 == g && c.ctrlKey) && c.altKey !== !0 ? (H(d, !0, !1, _.split("")), e.click()) : g != a.inputmask.keyCode.INSERT || c.shiftKey || c.ctrlKey ? 0 != f.insertMode || c.shiftKey || (g == a.inputmask.keyCode.RIGHT ? setTimeout(function () {
var a = L(d);
L(d, a.begin)
}, 0) : g == a.inputmask.keyCode.LEFT && setTimeout(function () {
var a = L(d);
L(d, ea ? a.begin + 1 : a.begin - 1)
}, 0)) : (f.insertMode = !f.insertMode, L(d, f.insertMode || i.begin != B() ? i.begin : i.begin - 1)), f.onKeyDown.call(this, c, v(), L(d).begin, f), ha = -1 != a.inArray(g, f.ignorables)
}
function U(b, c, d, e, g) {
var h = this, i = a(h), j = b.which || b.charCode || b.keyCode;
if (!(c === !0 || b.ctrlKey && b.altKey) && (b.ctrlKey || b.metaKey || ha)) {
return !0;
}
if (j) {
46 == j && 0 == b.shiftKey && "," == f.radixPoint && (j = 44);
var k, n = c ? {begin: g, end: g} : L(h), p = String.fromCharCode(j), q = P(n.begin, n.end);
q && (l().undoPositions = a.extend(!0, {}, l().validPositions), S(h, a.inputmask.keyCode.DELETE, n, !0), n.begin = l().p, f.insertMode || (f.insertMode = !f.insertMode, o(n.begin, e), f.insertMode = !f.insertMode), q = !f.multi), l().writeOutBuffer = !0;
var r = ea && !q ? n.end : n.begin, s = z(r, p, e);
if (s !== !1) {
if (s !== !0 && (r = void 0 != s.pos ? s.pos : r, p = void 0 != s.c ? s.c : p), m(!0), void 0 != s.caret) {
k = s.caret;
} else {
var u = l().validPositions;
k = !f.keepStatic && (void 0 != u[r + 1] && t(r + 1, u[r].locator.slice(), r).length > 1 || void 0 != u[r].alternation) ? r + 1 : C(r)
}
l().p = k
}
if (d !== !1) {
var x = this;
if (setTimeout(function () {
f.onKeyValidation.call(x, s, f)
}, 0), l().writeOutBuffer && s !== !1) {
var y = v();
F(h, y, c ? void 0 : f.numericInput ? D(k) : k, b, c !== !0), c !== !0 && setTimeout(function () {
O(y) === !0 && i.trigger("complete")
}, 0)
} else {
q && (l().buffer = void 0, l().validPositions = l().undoPositions)
}
} else {
q && (l().buffer = void 0, l().validPositions = l().undoPositions);
}
if (f.showTooltip && i.prop("title", l().mask), c && a.isFunction(f.onBeforeWrite)) {
var A = f.onBeforeWrite.call(this, b, v(), k, f);
if (A && A.refreshFromBuffer) {
var B = A.refreshFromBuffer;
w(B === !0 ? B : B.start, B.end, A.buffer), m(!0), A.caret && (l().p = A.caret)
}
}
b.preventDefault()
}
}
function V(b) {
var c = this, d = a(c), e = c._valueGet(!0), g = L(c);
if ("propertychange" == b.type && c._valueGet().length <= B()) {
return !0;
}
if ("paste" == b.type) {
var h = e.substr(0, g.begin), i = e.substr(g.end, e.length);
h == u().slice(0, g.begin).join("") && (h = ""), i == u().slice(g.end).join("") && (i = ""), window.clipboardData && window.clipboardData.getData ? e = h + window.clipboardData.getData("Text") + i : b.originalEvent && b.originalEvent.clipboardData && b.originalEvent.clipboardData.getData && (e = h + b.originalEvent.clipboardData.getData("text/plain") + i)
}
var j = e;
if (a.isFunction(f.onBeforePaste)) {
if (j = f.onBeforePaste.call(c, e, f), j === !1) {
return b.preventDefault(), !1;
}
j || (j = e)
}
return H(c, !0, !1, ea ? j.split("").reverse() : j.split("")), d.click(), O(v()) === !0 && d.trigger("complete"), !1
}
function W(b) {
var c = this;
H(c, !0, !1), O(v()) === !0 && a(c).trigger("complete"), b.preventDefault()
}
function X(a) {
var b = this;
_ = v().join(""), ("" == ba || 0 != a.originalEvent.data.indexOf(ba)) && (aa = L(b))
}
function Y(b) {
var c = this, d = aa || L(c);
0 == b.originalEvent.data.indexOf(ba) && (m(), d = {begin: 0, end: 0});
var e = b.originalEvent.data;
L(c, d.begin, d.end);
for (var g = 0; g < e.length; g++) {
var h = a.Event("keypress");
h.which = e.charCodeAt(g), fa = !1, ha = !1, U.call(c, h)
}
setTimeout(function () {
var a = l().p;
F(c, v(), f.numericInput ? D(a) : a)
}, 0), ba = b.originalEvent.data
}
function Z() {
}
function $(b) {
if (ca = a(b), ca.is(":input") && c(ca.attr("type")) || b.isContentEditable || ca.is("div")) {
if (ca.data("_inputmask", {
maskset: e,
opts: f,
isRTL: !1
}), f.showTooltip && ca.prop("title", l().mask), ("rtl" == b.dir || f.rightAlign) && ca.css("text-align", "right"), "rtl" == b.dir || f.numericInput) {
b.dir = "ltr", ca.removeAttr("dir");
var d = ca.data("_inputmask");
d.isRTL = !0, ca.data("_inputmask", d), ea = !0
}
ca.unbind(".inputmask"), (ca.is(":input") || b.isContentEditable) && (ca.closest("form").bind("submit", function () {
_ != v().join("") && ca.change(), ca[0]._valueGet && ca[0]._valueGet() == u().join("") && ca[0]._valueSet(""), f.removeMaskOnSubmit && ca.inputmask("remove")
}).bind("reset", function () {
setTimeout(function () {
ca.triggerHandler("setvalue.inputmask")
}, 0)
}), ca.bind("mouseenter.inputmask", function () {
var b = a(this), c = this;
!b.is(":focus") && f.showMaskOnHover && c._valueGet() != v().join("") && F(c, v())
}).bind("blur.inputmask", function (b) {
var c = a(this), d = this;
if (c.data("_inputmask")) {
var e = d._valueGet(), g = v().slice();
ia = !0, _ != g.join("") && setTimeout(function () {
c.change(), _ = g.join("")
}, 0), "" != e && (f.clearMaskOnLostFocus && (e == u().join("") ? g = [] : N(g)), O(g) === !1 && (c.trigger("incomplete"), f.clearIncomplete && (m(), g = f.clearMaskOnLostFocus ? [] : u().slice())), F(d, g, void 0, b))
}
}).bind("focus.inputmask", function () {
var b = (a(this), this), c = b._valueGet();
f.showMaskOnFocus && (!f.showMaskOnHover || f.showMaskOnHover && "" == c) && b._valueGet() != v().join("") && F(b, v(), C(n())), _ = v().join("")
}).bind("mouseleave.inputmask", function () {
var b = a(this), c = this;
if (f.clearMaskOnLostFocus) {
var d = v().slice(), e = c._valueGet();
b.is(":focus") || e == b.attr("placeholder") || "" == e || (e == u().join("") ? d = [] : N(d), F(c, d))
}
}).bind("click.inputmask", function () {
var b = a(this), c = this;
if (b.is(":focus")) {
var d = L(c);
if (d.begin == d.end) {
if (f.radixFocus && "" != f.radixPoint && -1 != a.inArray(f.radixPoint, v()) && (ia || v().join("") == u().join(""))) {
L(c, a.inArray(f.radixPoint, v())), ia = !1;
} else {
var e = ea ? K(d.begin) : d.begin, g = C(n(e));
g > e ? L(c, A(e) ? e : C(e)) : L(c, g)
}
}
}
}).bind("dblclick.inputmask", function () {
var a = this;
setTimeout(function () {
L(a, 0, C(n()))
}, 0)
}).bind(k + ".inputmask dragdrop.inputmask drop.inputmask", V).bind("cut.inputmask", function (b) {
ga = !0;
var c = this, d = a(c), e = L(c);
S(c, a.inputmask.keyCode.DELETE, e), F(c, v(), l().p, b, _ != v().join("")), c._valueGet() == u().join("") && d.trigger("cleared"), f.showTooltip && d.prop("title", l().mask)
}).bind("complete.inputmask", f.oncomplete).bind("incomplete.inputmask", f.onincomplete).bind("cleared.inputmask", f.oncleared), ca.bind("keydown.inputmask", T).bind("keypress.inputmask", U), j || ca.bind("compositionstart.inputmask", X).bind("compositionupdate.inputmask", Y).bind("compositionend.inputmask", Z), "paste" === k && ca.bind("input.inputmask", W)), ca.bind("setvalue.inputmask", function () {
var b = this, c = b._valueGet();
b._valueSet(a.isFunction(f.onBeforeMask) ? f.onBeforeMask.call(b, c, f) || c : c), H(b, !0, !1), _ = v().join(""), (f.clearMaskOnLostFocus || f.clearIncomplete) && b._valueGet() == u().join("") && b._valueSet("")
}), R(b);
var g = a.isFunction(f.onBeforeMask) ? f.onBeforeMask.call(b, b._valueGet(), f) || b._valueGet() : b._valueGet();
H(b, !0, !1, g.split(""));
var h = v().slice();
_ = h.join("");
var i;
try {
i = document.activeElement
} catch (o) {
}
O(h) === !1 && f.clearIncomplete && m(), f.clearMaskOnLostFocus && (h.join("") == u().join("") ? h = [] : N(h)), F(b, h), i === b && L(b, C(n())), Q(b)
}
}
var _, aa, ba, ca, da, ea = !1, fa = !1, ga = !1, ha = !1, ia = !0;
if (void 0 != d) {
switch (d.action) {
case"isComplete":
return ca = a(d.el), e = ca.data("_inputmask").maskset, f = ca.data("_inputmask").opts, O(d.buffer);
case"unmaskedvalue":
return ca = d.$input, e = ca.data("_inputmask").maskset, f = ca.data("_inputmask").opts, ea = d.$input.data("_inputmask").isRTL, J(d.$input);
case"mask":
_ = v().join(""), $(d.el);
break;
case"format":
ca = a({}), ca.data("_inputmask", {
maskset: e,
opts: f,
isRTL: f.numericInput
}), f.numericInput && (ea = !0);
var ja = (a.isFunction(f.onBeforeMask) ? f.onBeforeMask.call(ca, d.value, f) || d.value : d.value).split("");
return H(ca, !1, !1, ea ? ja.reverse() : ja), a.isFunction(f.onBeforeWrite) && f.onBeforeWrite.call(this, void 0, v(), 0, f), d.metadata ? {
value: ea ? v().slice().reverse().join("") : v().join(""),
metadata: ca.inputmask("getmetadata")
} : ea ? v().slice().reverse().join("") : v().join("");
case"isValid":
ca = a({}), ca.data("_inputmask", {
maskset: e,
opts: f,
isRTL: f.numericInput
}), f.numericInput && (ea = !0);
var ja = d.value.split("");
H(ca, !1, !0, ea ? ja.reverse() : ja);
for (var ka = v(), la = M(), ma = ka.length - 1; ma > la && !A(ma); ma--);
return ka.splice(la, ma + 1 - la), O(ka) && d.value == ka.join("");
case"getemptymask":
return ca = a(d.el), e = ca.data("_inputmask").maskset, f = ca.data("_inputmask").opts, u();
case"remove":
var na = d.el;
ca = a(na), e = ca.data("_inputmask").maskset, f = ca.data("_inputmask").opts, na._valueSet(J(ca)), ca.unbind(".inputmask"), ca.removeData("_inputmask");
var oa;
Object.getOwnPropertyDescriptor && (oa = Object.getOwnPropertyDescriptor(na, "value")), oa && oa.get ? na._valueGet && Object.defineProperty(na, "value", {
get: na._valueGet,
set: na._valueSet
}) : document.__lookupGetter__ && na.__lookupGetter__("value") && na._valueGet && (na.__defineGetter__("value", na._valueGet), na.__defineSetter__("value", na._valueSet));
try {
delete na._valueGet, delete na._valueSet
} catch (pa) {
na._valueGet = void 0, na._valueSet = void 0
}
break;
case"getmetadata":
if (ca = a(d.el), e = ca.data("_inputmask").maskset, f = ca.data("_inputmask").opts, a.isArray(e.metadata)) {
for (var qa, ra = n(), sa = ra; sa >= 0; sa--)if (l().validPositions[sa] && void 0 != l().validPositions[sa].alternation) {
qa = l().validPositions[sa].alternation;
break
}
return void 0 != qa ? e.metadata[l().validPositions[ra].locator[qa]] : e.metadata[0]
}
return e.metadata
}
}
}
if (void 0 === a.fn.inputmask) {
var g = navigator.userAgent, h = null !== g.match(new RegExp("iphone", "i")), i = (null !== g.match(new RegExp("android.*safari.*", "i")), null !== g.match(new RegExp("android.*chrome.*", "i"))), j = null !== g.match(new RegExp("android.*firefox.*", "i")), k = (/Kindle/i.test(g) || /Silk/i.test(g) || /KFTT/i.test(g) || /KFOT/i.test(g) || /KFJWA/i.test(g) || /KFJWI/i.test(g) || /KFSOWI/i.test(g) || /KFTHWA/i.test(g) || /KFTHWI/i.test(g) || /KFAPWA/i.test(g) || /KFAPWI/i.test(g), b("paste") ? "paste" : b("input") ? "input" : "propertychange");
a.inputmask = {
defaults: {
placeholder: "_",
optionalmarker: {start: "[", end: "]"},
quantifiermarker: {start: "{", end: "}"},
groupmarker: {start: "(", end: ")"},
alternatormarker: "|",
escapeChar: "\\",
mask: null,
oncomplete: a.noop,
onincomplete: a.noop,
oncleared: a.noop,
repeat: 0,
greedy: !0,
autoUnmask: !1,
removeMaskOnSubmit: !1,
clearMaskOnLostFocus: !0,
insertMode: !0,
clearIncomplete: !1,
aliases: {},
alias: null,
onKeyDown: a.noop,
onBeforeMask: void 0,
onBeforePaste: void 0,
onBeforeWrite: void 0,
onUnMask: void 0,
showMaskOnFocus: !0,
showMaskOnHover: !0,
onKeyValidation: a.noop,
skipOptionalPartCharacter: " ",
showTooltip: !1,
numericInput: !1,
rightAlign: !1,
undoOnEscape: !0,
radixPoint: "",
radixFocus: !1,
nojumps: !1,
nojumpsThreshold: 0,
keepStatic: void 0,
definitions: {
9: {validator: "[0-9]", cardinality: 1, definitionSymbol: "*"},
a: {
validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",
cardinality: 1,
definitionSymbol: "*"
},
"*": {validator: "[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]", cardinality: 1}
},
ignorables: [8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123],
isComplete: void 0,
canClearPosition: a.noop,
postValidation: void 0
},
keyCode: {
ALT: 18,
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91,
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91
},
masksCache: {},
escapeRegex: function (a) {
var b = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^"];
return a.replace(new RegExp("(\\" + b.join("|\\") + ")", "gim"), "\\$1")
},
format: function (b, c, g) {
var h = a.extend(!0, {}, a.inputmask.defaults, c);
return d(h.alias, c, h), f({
action: "format",
value: b,
metadata: g
}, e(h, c && void 0 !== c.definitions), h)
},
isValid: function (b, c) {
var g = a.extend(!0, {}, a.inputmask.defaults, c);
return d(g.alias, c, g), f({action: "isValid", value: b}, e(g, c && void 0 !== c.definitions), g)
}
}, a.fn.inputmask = function (b, c) {
function g(b, c, e) {
var f = a(b);
f.data("inputmask-alias") && d(f.data("inputmask-alias"), a.extend(!0, {}, c), c);
for (var g in c) {
var h = f.data("inputmask-" + g.toLowerCase());
void 0 != h && ("mask" == g && 0 == h.indexOf("[") ? (c[g] = h.replace(/[\s[\]]/g, "").split("','"), c[g][0] = c[g][0].replace("'", ""), c[g][c[g].length - 1] = c[g][c[g].length - 1].replace("'", "")) : c[g] = "boolean" == typeof h ? h : h.toString(), e && (e[g] = c[g]))
}
return c
}
var h, i = a.extend(!0, {}, a.inputmask.defaults, c);
if ("string" == typeof b)switch (b) {
case"mask":
return d(i.alias, c, i), this.each(function () {
return g(this, i), h = e(i, c && void 0 !== c.definitions), void 0 == h ? this : void f({
action: "mask",
el: this
}, h, i)
});
case"unmaskedvalue":
var j = a(this);
return j.data("_inputmask") ? f({action: "unmaskedvalue", $input: j}) : j.val();
case"remove":
return this.each(function () {
var b = a(this);
b.data("_inputmask") && f({action: "remove", el: this})
});
case"getemptymask":
return this.data("_inputmask") ? f({action: "getemptymask", el: this}) : "";
case"hasMaskedValue":
return this.data("_inputmask") ? !this.data("_inputmask").opts.autoUnmask : !1;
case"isComplete":
return this.data("_inputmask") ? f({
action: "isComplete",
buffer: this[0]._valueGet().split(""),
el: this
}) : !0;
case"getmetadata":
return this.data("_inputmask") ? f({action: "getmetadata", el: this}) : void 0;
default:
return d(i.alias, c, i), d(b, c, i) || (i.mask = b), this.each(function () {
return g(this, i), h = e(i, c && void 0 !== c.definitions), void 0 == h ? this : void f({
action: "mask",
el: this
}, h, i)
})
} else {
if ("object" == typeof b)return i = a.extend(!0, {}, a.inputmask.defaults, b), d(i.alias, b, i), this.each(function () {
return g(this, i), h = e(i, b && void 0 !== b.definitions), void 0 == h ? this : void f({
action: "mask",
el: this
}, h, i)
});
if (void 0 == b)return this.each(function () {
var b = a(this).attr("data-inputmask");
if (b && "" != b)try {
b = b.replace(new RegExp("'", "g"), '"');
var e = a.parseJSON("{" + b + "}");
a.extend(!0, e, c), i = a.extend(!0, {}, a.inputmask.defaults, e), i = g(this, i), d(i.alias, e, i), i.alias = void 0, a(this).inputmask("mask", i)
} catch (f) {
}
if (a(this).attr("data-inputmask-mask") || a(this).attr("data-inputmask-alias")) {
i = a.extend(!0, {}, a.inputmask.defaults, {});
var h = {};
i = g(this, i, h), d(i.alias, h, i), i.alias = void 0, a(this).inputmask("mask", i)
}
})
}
}
}
return a.fn.inputmask
}(jQuery), function (a) {
return a.extend(a.inputmask.defaults.definitions, {
h: {
validator: "[01][0-9]|2[0-3]",
cardinality: 2,
prevalidator: [{validator: "[0-2]", cardinality: 1}]
},
s: {validator: "[0-5][0-9]", cardinality: 2, prevalidator: [{validator: "[0-5]", cardinality: 1}]},
d: {validator: "0[1-9]|[12][0-9]|3[01]", cardinality: 2, prevalidator: [{validator: "[0-3]", cardinality: 1}]},
m: {validator: "0[1-9]|1[012]", cardinality: 2, prevalidator: [{validator: "[01]", cardinality: 1}]},
y: {
validator: "(19|20)\\d{2}",
cardinality: 4,
prevalidator: [{validator: "[12]", cardinality: 1}, {
validator: "(19|20)",
cardinality: 2
}, {validator: "(19|20)\\d", cardinality: 3}]
}
}), a.extend(a.inputmask.defaults.aliases, {
"dd/mm/yyyy": {
mask: "1/2/y",
placeholder: "dd/mm/yyyy",
regex: {
val1pre: new RegExp("[0-3]"), val1: new RegExp("0[1-9]|[12][0-9]|3[01]"), val2pre: function (b) {
var c = a.inputmask.escapeRegex.call(this, b);
return new RegExp("((0[1-9]|[12][0-9]|3[01])" + c + "[01])")
}, val2: function (b) {
var c = a.inputmask.escapeRegex.call(this, b);
return new RegExp("((0[1-9]|[12][0-9])" + c + "(0[1-9]|1[012]))|(30" + c + "(0[13-9]|1[012]))|(31" + c + "(0[13578]|1[02]))")
}
},
leapday: "29/02/",
separator: "/",
yearrange: {minyear: 1900, maxyear: 2099},
isInYearRange: function (a, b, c) {
if (isNaN(a))return !1;
var d = parseInt(a.concat(b.toString().slice(a.length))), e = parseInt(a.concat(c.toString().slice(a.length)));
return (isNaN(d) ? !1 : d >= b && c >= d) || (isNaN(e) ? !1 : e >= b && c >= e)
},
determinebaseyear: function (a, b, c) {
var d = (new Date).getFullYear();
if (a > d)return a;
if (d > b) {
for (var e = b.toString().slice(0, 2), f = b.toString().slice(2, 4); e + c > b;)e--;
var g = e + f;
return a > g ? a : g
}
return d
},
onKeyDown: function (b) {
var c = a(this);
if (b.ctrlKey && b.keyCode == a.inputmask.keyCode.RIGHT) {
var d = new Date;
c.val(d.getDate().toString() + (d.getMonth() + 1).toString() + d.getFullYear().toString()), c.triggerHandler("setvalue.inputmask")
}
},
getFrontValue: function (a, b, c) {
for (var d = 0, e = 0, f = 0; f < a.length && "2" != a.charAt(f); f++) {
var g = c.definitions[a.charAt(f)];
g ? (d += e, e = g.cardinality) : e++
}
return b.join("").substr(d, e)
},
definitions: {
1: {
validator: function (a, b, c, d, e) {
var f = e.regex.val1.test(a);
return d || f || a.charAt(1) != e.separator && -1 == "-./".indexOf(a.charAt(1)) || !(f = e.regex.val1.test("0" + a.charAt(0))) ? f : (b.buffer[c - 1] = "0", {
refreshFromBuffer: {
start: c - 1,
end: c
}, pos: c, c: a.charAt(0)
})
}, cardinality: 2, prevalidator: [{
validator: function (a, b, c, d, e) {
var f = a;
isNaN(b.buffer[c + 1]) || (f += b.buffer[c + 1]);
var g = 1 == f.length ? e.regex.val1pre.test(f) : e.regex.val1.test(f);
if (!d && !g) {
if (g = e.regex.val1.test(a + "0"))return b.buffer[c] = a, b.buffer[++c] = "0", {
pos: c,
c: "0"
};
if (g = e.regex.val1.test("0" + a))return b.buffer[c] = "0", c++, {pos: c}
}
return g
}, cardinality: 1
}]
}, 2: {
validator: function (a, b, c, d, e) {
var f = e.getFrontValue(b.mask, b.buffer, e);
-1 != f.indexOf(e.placeholder[0]) && (f = "01" + e.separator);
var g = e.regex.val2(e.separator).test(f + a);
if (!d && !g && (a.charAt(1) == e.separator || -1 != "-./".indexOf(a.charAt(1))) && (g = e.regex.val2(e.separator).test(f + "0" + a.charAt(0))))return b.buffer[c - 1] = "0", {
refreshFromBuffer: {
start: c - 1,
end: c
}, pos: c, c: a.charAt(0)
};
if (e.mask.indexOf("2") == e.mask.length - 1 && g) {
var h = b.buffer.join("").substr(4, 4) + a;
if (h != e.leapday)return !0;
var i = parseInt(b.buffer.join("").substr(0, 4), 10);
return i % 4 === 0 ? i % 100 === 0 ? i % 400 === 0 ? !0 : !1 : !0 : !1
}
return g
}, cardinality: 2, prevalidator: [{
validator: function (a, b, c, d, e) {
isNaN(b.buffer[c + 1]) || (a += b.buffer[c + 1]);
var f = e.getFrontValue(b.mask, b.buffer, e);
-1 != f.indexOf(e.placeholder[0]) && (f = "01" + e.separator);
var g = 1 == a.length ? e.regex.val2pre(e.separator).test(f + a) : e.regex.val2(e.separator).test(f + a);
return d || g || !(g = e.regex.val2(e.separator).test(f + "0" + a)) ? g : (b.buffer[c] = "0", c++, {pos: c})
}, cardinality: 1
}]
}, y: {
validator: function (a, b, c, d, e) {
if (e.isInYearRange(a, e.yearrange.minyear, e.yearrange.maxyear)) {
var f = b.buffer.join("").substr(0, 6);
if (f != e.leapday)return !0;
var g = parseInt(a, 10);
return g % 4 === 0 ? g % 100 === 0 ? g % 400 === 0 ? !0 : !1 : !0 : !1
}
return !1
}, cardinality: 4, prevalidator: [{
validator: function (a, b, c, d, e) {
var f = e.isInYearRange(a, e.yearrange.minyear, e.yearrange.maxyear);
if (!d && !f) {
var g = e.determinebaseyear(e.yearrange.minyear, e.yearrange.maxyear, a + "0").toString().slice(0, 1);
if (f = e.isInYearRange(g + a, e.yearrange.minyear, e.yearrange.maxyear))return b.buffer[c++] = g.charAt(0), {pos: c};
if (g = e.determinebaseyear(e.yearrange.minyear, e.yearrange.maxyear, a + "0").toString().slice(0, 2), f = e.isInYearRange(g + a, e.yearrange.minyear, e.yearrange.maxyear))return b.buffer[c++] = g.charAt(0), b.buffer[c++] = g.charAt(1), {pos: c}
}
return f
}, cardinality: 1
}, {
validator: function (a, b, c, d, e) {
var f = e.isInYearRange(a, e.yearrange.minyear, e.yearrange.maxyear);
if (!d && !f) {
var g = e.determinebaseyear(e.yearrange.minyear, e.yearrange.maxyear, a).toString().slice(0, 2);
if (f = e.isInYearRange(a[0] + g[1] + a[1], e.yearrange.minyear, e.yearrange.maxyear))return b.buffer[c++] = g.charAt(1), {pos: c};
if (g = e.determinebaseyear(e.yearrange.minyear, e.yearrange.maxyear, a).toString().slice(0, 2), e.isInYearRange(g + a, e.yearrange.minyear, e.yearrange.maxyear)) {
var h = b.buffer.join("").substr(0, 6);
if (h != e.leapday)f = !0; else {
var i = parseInt(a, 10);
f = i % 4 === 0 ? i % 100 === 0 ? i % 400 === 0 ? !0 : !1 : !0 : !1
}
} else f = !1;
if (f)return b.buffer[c - 1] = g.charAt(0), b.buffer[c++] = g.charAt(1), b.buffer[c++] = a.charAt(0), {
refreshFromBuffer: {
start: c - 3,
end: c
}, pos: c
}
}
return f
}, cardinality: 2
}, {
validator: function (a, b, c, d, e) {
return e.isInYearRange(a, e.yearrange.minyear, e.yearrange.maxyear)
}, cardinality: 3
}]
}
},
insertMode: !1,
autoUnmask: !1
},
"mm/dd/yyyy": {
placeholder: "mm/dd/yyyy", alias: "dd/mm/yyyy", regex: {
val2pre: function (b) {
var c = a.inputmask.escapeRegex.call(this, b);
return new RegExp("((0[13-9]|1[012])" + c + "[0-3])|(02" + c + "[0-2])")
}, val2: function (b) {
var c = a.inputmask.escapeRegex.call(this, b);
return new RegExp("((0[1-9]|1[012])" + c + "(0[1-9]|[12][0-9]))|((0[13-9]|1[012])" + c + "30)|((0[13578]|1[02])" + c + "31)")
}, val1pre: new RegExp("[01]"), val1: new RegExp("0[1-9]|1[012]")
}, leapday: "02/29/", onKeyDown: function (b) {
var c = a(this);
if (b.ctrlKey && b.keyCode == a.inputmask.keyCode.RIGHT) {
var d = new Date;
c.val((d.getMonth() + 1).toString() + d.getDate().toString() + d.getFullYear().toString()), c.triggerHandler("setvalue.inputmask")
}
}
},
"yyyy/mm/dd": {
mask: "y/1/2",
placeholder: "yyyy/mm/dd",
alias: "mm/dd/yyyy",
leapday: "/02/29",
onKeyDown: function (b) {
var c = a(this);
if (b.ctrlKey && b.keyCode == a.inputmask.keyCode.RIGHT) {
var d = new Date;
c.val(d.getFullYear().toString() + (d.getMonth() + 1).toString() + d.getDate().toString()), c.triggerHandler("setvalue.inputmask")
}
}
},
"dd.mm.yyyy": {
mask: "1.2.y",
placeholder: "dd.mm.yyyy",
leapday: "29.02.",
separator: ".",
alias: "dd/mm/yyyy"
},
"dd-mm-yyyy": {
mask: "1-2-y",
placeholder: "dd-mm-yyyy",
leapday: "29-02-",
separator: "-",
alias: "dd/mm/yyyy"
},
"mm.dd.yyyy": {
mask: "1.2.y",
placeholder: "mm.dd.yyyy",
leapday: "02.29.",
separator: ".",
alias: "mm/dd/yyyy"
},
"mm-dd-yyyy": {
mask: "1-2-y",
placeholder: "mm-dd-yyyy",
leapday: "02-29-",
separator: "-",
alias: "mm/dd/yyyy"
},
"yyyy.mm.dd": {
mask: "y.1.2",
placeholder: "yyyy.mm.dd",
leapday: ".02.29",
separator: ".",
alias: "yyyy/mm/dd"
},
"yyyy-mm-dd": {
mask: "y-1-2",
placeholder: "yyyy-mm-dd",
leapday: "-02-29",
separator: "-",
alias: "yyyy/mm/dd"
},
datetime: {
mask: "1/2/y h:s",
placeholder: "dd/mm/yyyy hh:mm",
alias: "dd/mm/yyyy",
regex: {
hrspre: new RegExp("[012]"),
hrs24: new RegExp("2[0-4]|1[3-9]"),
hrs: new RegExp("[01][0-9]|2[0-4]"),
ampm: new RegExp("^[a|p|A|P][m|M]"),
mspre: new RegExp("[0-5]"),
ms: new RegExp("[0-5][0-9]")
},
timeseparator: ":",
hourFormat: "24",
definitions: {
h: {
validator: function (a, b, c, d, e) {
if ("24" == e.hourFormat && 24 == parseInt(a, 10))return b.buffer[c - 1] = "0", b.buffer[c] = "0", {
refreshFromBuffer: {
start: c - 1,
end: c
}, c: "0"
};
var f = e.regex.hrs.test(a);
if (!d && !f && (a.charAt(1) == e.timeseparator || -1 != "-.:".indexOf(a.charAt(1))) && (f = e.regex.hrs.test("0" + a.charAt(0))))return b.buffer[c - 1] = "0", b.buffer[c] = a.charAt(0), c++, {
refreshFromBuffer: {
start: c - 2,
end: c
}, pos: c, c: e.timeseparator
};
if (f && "24" !== e.hourFormat && e.regex.hrs24.test(a)) {
var g = parseInt(a, 10);
return 24 == g ? (b.buffer[c + 5] = "a", b.buffer[c + 6] = "m") : (b.buffer[c + 5] = "p", b.buffer[c + 6] = "m"), g -= 12, 10 > g ? (b.buffer[c] = g.toString(), b.buffer[c - 1] = "0") : (b.buffer[c] = g.toString().charAt(1), b.buffer[c - 1] = g.toString().charAt(0)), {
refreshFromBuffer: {
start: c - 1,
end: c + 6
}, c: b.buffer[c]
}
}
return f
}, cardinality: 2, prevalidator: [{
validator: function (a, b, c, d, e) {
var f = e.regex.hrspre.test(a);
return d || f || !(f = e.regex.hrs.test("0" + a)) ? f : (b.buffer[c] = "0", c++, {pos: c})
}, cardinality: 1
}]
}, s: {
validator: "[0-5][0-9]", cardinality: 2, prevalidator: [{
validator: function (a, b, c, d, e) {
var f = e.regex.mspre.test(a);
return d || f || !(f = e.regex.ms.test("0" + a)) ? f : (b.buffer[c] = "0", c++, {pos: c})
}, cardinality: 1
}]
}, t: {
validator: function (a, b, c, d, e) {
return e.regex.ampm.test(a + "m")
}, casing: "lower", cardinality: 1
}
},
insertMode: !1,
autoUnmask: !1
},
datetime12: {mask: "1/2/y h:s t\\m", placeholder: "dd/mm/yyyy hh:mm xm", alias: "datetime", hourFormat: "12"},
"hh:mm t": {mask: "h:s t\\m", placeholder: "hh:mm xm", alias: "datetime", hourFormat: "12"},
"h:s t": {mask: "h:s t\\m", placeholder: "hh:mm xm", alias: "datetime", hourFormat: "12"},
"hh:mm:ss": {mask: "h:s:s", placeholder: "hh:mm:ss", alias: "datetime", autoUnmask: !1},
"hh:mm": {mask: "h:s", placeholder: "hh:mm", alias: "datetime", autoUnmask: !1},
date: {alias: "dd/mm/yyyy"},
"mm/yyyy": {mask: "1/y", placeholder: "mm/yyyy", leapday: "donotuse", separator: "/", alias: "mm/dd/yyyy"}
}), a.fn.inputmask
}(jQuery), function (a) {
return a.extend(a.inputmask.defaults.definitions, {
A: {
validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",
cardinality: 1,
casing: "upper"
}, "#": {validator: "[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]", cardinality: 1, casing: "upper"}
}), a.extend(a.inputmask.defaults.aliases, {
url: {
mask: "ir",
placeholder: "",
separator: "",
defaultPrefix: "http://",
regex: {
urlpre1: new RegExp("[fh]"),
urlpre2: new RegExp("(ft|ht)"),
urlpre3: new RegExp("(ftp|htt)"),
urlpre4: new RegExp("(ftp:|http|ftps)"),
urlpre5: new RegExp("(ftp:/|ftps:|http:|https)"),
urlpre6: new RegExp("(ftp://|ftps:/|http:/|https:)"),
urlpre7: new RegExp("(ftp://|ftps://|http://|https:/)"),
urlpre8: new RegExp("(ftp://|ftps://|http://|https://)")
},
definitions: {
i: {
validator: function () {
return !0
}, cardinality: 8, prevalidator: function () {
for (var a = [], b = 8, c = 0; b > c; c++)a[c] = function () {
var a = c;
return {
validator: function (b, c, d, e, f) {
if (f.regex["urlpre" + (a + 1)]) {
var g, h = b;
a + 1 - b.length > 0 && (h = c.buffer.join("").substring(0, a + 1 - b.length) + "" + h);
var i = f.regex["urlpre" + (a + 1)].test(h);
if (!e && !i) {
for (d -= a, g = 0; g < f.defaultPrefix.length; g++)c.buffer[d] = f.defaultPrefix[g], d++;
for (g = 0; g < h.length - 1; g++)c.buffer[d] = h[g], d++;
return {pos: d}
}
return i
}
return !1
}, cardinality: a
}
}();
return a
}()
}, r: {validator: ".", cardinality: 50}
},
insertMode: !1,
autoUnmask: !1
},
ip: {
mask: "i[i[i]].i[i[i]].i[i[i]].i[i[i]]", definitions: {
i: {
validator: function (a, b, c) {
return c - 1 > -1 && "." != b.buffer[c - 1] ? (a = b.buffer[c - 1] + a, a = c - 2 > -1 && "." != b.buffer[c - 2] ? b.buffer[c - 2] + a : "0" + a) : a = "00" + a, new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]").test(a)
}, cardinality: 1
}
}
},
email: {
mask: "*{1,64}[.*{1,64}][.*{1,64}][.*{1,64}]@*{1,64}[.*{2,64}][.*{2,6}][.*{1,2}]",
greedy: !1,
onBeforePaste: function (a) {
return a = a.toLowerCase(), a.replace("mailto:", "")
},
definitions: {"*": {validator: "[0-9A-Za-z!#$%&'*+/=?^_`{|}~-]", cardinality: 1, casing: "lower"}}
}
}), a.fn.inputmask
}(jQuery), function (a) {
return a.extend(a.inputmask.defaults.aliases, {
numeric: {
mask: function (a) {
function b(b) {
for (var c = "", d = 0; d < b.length; d++)c += a.definitions[b[d]] ? "\\" + b[d] : b[d];
return c
}
if (0 !== a.repeat && isNaN(a.integerDigits) && (a.integerDigits = a.repeat), a.repeat = 0, a.groupSeparator == a.radixPoint && (a.groupSeparator = "." == a.radixPoint ? "," : "," == a.radixPoint ? "." : ""), " " === a.groupSeparator && (a.skipOptionalPartCharacter = void 0), a.autoGroup = a.autoGroup && "" != a.groupSeparator, a.autoGroup && ("string" == typeof a.groupSize && isFinite(a.groupSize) && (a.groupSize = parseInt(a.groupSize)), isFinite(a.integerDigits))) {
var c = Math.floor(a.integerDigits / a.groupSize), d = a.integerDigits % a.groupSize;
a.integerDigits = parseInt(a.integerDigits) + (0 == d ? c - 1 : c)
}
a.placeholder.length > 1 && (a.placeholder = a.placeholder.charAt(0)), a.radixFocus = a.radixFocus && "0" == a.placeholder, a.definitions[";"] = a.definitions["~"];
var e = b(a.prefix);
return e += "[+]", e += "~{1," + a.integerDigits + "}", void 0 != a.digits && (isNaN(a.digits) || parseInt(a.digits) > 0) && (e += a.digitsOptional ? "[" + (a.decimalProtect ? ":" : a.radixPoint) + ";{" + a.digits + "}]" : (a.decimalProtect ? ":" : a.radixPoint) + ";{" + a.digits + "}"), "" != a.negationSymbol.back && (e += "[-]"), e += b(a.suffix), a.greedy = !1, e
},
placeholder: "",
greedy: !1,
digits: "*",
digitsOptional: !0,
groupSeparator: "",
radixPoint: ".",
radixFocus: !0,
groupSize: 3,
autoGroup: !1,
allowPlus: !0,
allowMinus: !0,
negationSymbol: {front: "-", back: ""},
integerDigits: "+",
prefix: "",
suffix: "",
rightAlign: !0,
decimalProtect: !0,
min: void 0,
max: void 0,
postFormat: function (b, c, d, e) {
var f = !1;
b.length >= e.suffix.length && b.join("").indexOf(e.suffix) == b.length - e.suffix.length && (b.length = b.length - e.suffix.length, f = !0), c = c >= b.length ? b.length - 1 : c < e.prefix.length ? e.prefix.length : c;
var g = !1, h = b[c];
if ("" == e.groupSeparator || -1 != a.inArray(e.radixPoint, b) && c >= a.inArray(e.radixPoint, b) || new RegExp("[" + a.inputmask.escapeRegex(e.negationSymbol.front) + "+]").test(h)) {
if (f)for (var i = 0, j = e.suffix.length; j > i; i++)b.push(e.suffix.charAt(i));
return {pos: c}
}
var k = b.slice();
h == e.groupSeparator && (k.splice(c--, 1), h = k[c]), d ? k[c] = "?" : k.splice(c, 0, "?");
var l = k.join(""), m = l;
if (l.length > 0 && e.autoGroup || d && -1 != l.indexOf(e.groupSeparator)) {
var n = a.inputmask.escapeRegex(e.groupSeparator);
g = 0 == l.indexOf(e.groupSeparator), l = l.replace(new RegExp(n, "g"), "");
var o = l.split(e.radixPoint);
if (l = "" == e.radixPoint ? l : o[0], l != e.prefix + "?0" && l.length >= e.groupSize + e.prefix.length)for (var p = new RegExp("([-+]?[\\d?]+)([\\d?]{" + e.groupSize + "})"); p.test(l);)l = l.replace(p, "$1" + e.groupSeparator + "$2"), l = l.replace(e.groupSeparator + e.groupSeparator, e.groupSeparator);
"" != e.radixPoint && o.length > 1 && (l += e.radixPoint + o[1])
}
g = m != l, b.length = l.length;
for (var i = 0, j = l.length; j > i; i++)b[i] = l.charAt(i);
var q = a.inArray("?", b);
if (d ? b[q] = h : b.splice(q, 1), !g && f)for (var i = 0, j = e.suffix.length; j > i; i++)b.push(e.suffix.charAt(i));
return {pos: q, refreshFromBuffer: g, buffer: b}
},
onBeforeWrite: function (b, c, d, e) {
if (b && "blur" == b.type) {
var f = c.join(""), g = f.replace(e.prefix, "");
if (g = g.replace(e.suffix, ""), g = g.replace(new RegExp(a.inputmask.escapeRegex(e.groupSeparator), "g"), ""), "," === e.radixPoint && (g = g.replace(a.inputmask.escapeRegex(e.radixPoint), ".")), isFinite(g) && isFinite(e.min) && parseFloat(g) < parseFloat(e.min))return a.extend(!0, {
refreshFromBuffer: !0,
buffer: (e.prefix + e.min).split("")
}, e.postFormat((e.prefix + e.min).split(""), 0, !0, e));
var h = "" != e.radixPoint ? c.join("").split(e.radixPoint) : [c.join("")], i = h[0].match(e.regex.integerPart(e)), j = 2 == h.length ? h[1].match(e.regex.integerNPart(e)) : void 0;
!i || i[0] != e.negationSymbol.front + "0" && i[0] != e.negationSymbol.front && "+" != i[0] || void 0 != j && !j[0].match(/^0+$/) || c.splice(i.index, 1);
var k = a.inArray(e.radixPoint, c);
if (-1 != k && isFinite(e.digits) && !e.digitsOptional) {
for (var l = 1; l <= e.digits; l++)(void 0 == c[k + l] || c[k + l] == e.placeholder.charAt(0)) && (c[k + l] = "0");
return {refreshFromBuffer: !0, buffer: c}
}
}
if (e.autoGroup) {
var m = e.postFormat(c, d - 1, !0, e);
return m.caret = d <= e.prefix.length ? m.pos : m.pos + 1, m
}
},
regex: {
integerPart: function (b) {
return new RegExp("[" + a.inputmask.escapeRegex(b.negationSymbol.front) + "+]?\\d+")
}, integerNPart: function (b) {
return new RegExp("[\\d" + a.inputmask.escapeRegex(b.groupSeparator) + "]+")
}
},
signHandler: function (a, b, c, d, e) {
if (!d && e.allowMinus && "-" === a || e.allowPlus && "+" === a) {
var f = b.buffer.join("").match(e.regex.integerPart(e));
if (f && f[0].length > 0)return b.buffer[f.index] == ("-" === a ? "+" : e.negationSymbol.front) ? "-" == a ? "" != e.negationSymbol.back ? {
pos: f.index,
c: e.negationSymbol.front,
remove: f.index,
caret: c,
insert: {pos: b.buffer.length - e.suffix.length - 1, c: e.negationSymbol.back}
} : {
pos: f.index,
c: e.negationSymbol.front,
remove: f.index,
caret: c
} : "" != e.negationSymbol.back ? {
pos: f.index,
c: "+",
remove: [f.index, b.buffer.length - e.suffix.length - 1],
caret: c
} : {
pos: f.index,
c: "+",
remove: f.index,
caret: c
} : b.buffer[f.index] == ("-" === a ? e.negationSymbol.front : "+") ? "-" == a && "" != e.negationSymbol.back ? {
remove: [f.index, b.buffer.length - e.suffix.length - 1],
caret: c - 1
} : {remove: f.index, caret: c - 1} : "-" == a ? "" != e.negationSymbol.back ? {
pos: f.index,
c: e.negationSymbol.front,
caret: c + 1,
insert: {pos: b.buffer.length - e.suffix.length, c: e.negationSymbol.back}
} : {pos: f.index, c: e.negationSymbol.front, caret: c + 1} : {pos: f.index, c: a, caret: c + 1}
}
return !1
},
radixHandler: function (b, c, d, e, f) {
if (!e && b === f.radixPoint && f.digits > 0) {
var g = a.inArray(f.radixPoint, c.buffer), h = c.buffer.join("").match(f.regex.integerPart(f));
if (-1 != g && c.validPositions[g])return c.validPositions[g - 1] ? {caret: g + 1} : {
pos: h.index,
c: h[0],
caret: g + 1
};
if (!h || "0" == h[0] && h.index + 1 != d)return c.buffer[h ? h.index : d] = "0", {pos: (h ? h.index : d) + 1}
}
return !1
},
leadingZeroHandler: function (b, c, d, e, f) {
var g = c.buffer.join("").match(f.regex.integerNPart(f)), h = a.inArray(f.radixPoint, c.buffer);
if (g && !e && (-1 == h || h >= d))if (0 == g[0].indexOf("0")) {
d < f.prefix.length && (d = g.index);
var i = a.inArray(f.radixPoint, c._buffer), j = c._buffer && c.buffer.slice(h).join("") == c._buffer.slice(i).join("") || 0 == parseInt(c.buffer.slice(h + 1).join("")), k = c._buffer && c.buffer.slice(g.index, h).join("") == c._buffer.slice(f.prefix.length, i).join("") || "0" == c.buffer.slice(g.index, h).join("");
if (-1 == h || j && k)return c.buffer.splice(g.index, 1), d = d > g.index ? d - 1 : g.index, {
pos: d,
remove: g.index
};
if (g.index + 1 == d || "0" == b)return c.buffer.splice(g.index, 1), d = g.index, {
pos: d,
remove: g.index
}
} else if ("0" === b && d <= g.index && g[0] != f.groupSeparator)return !1;
return !0
},
postValidation: function (b, c) {
var d = !0, e = b.join(""), f = e.replace(c.prefix, "");
return f = f.replace(c.suffix, ""), f = f.replace(new RegExp(a.inputmask.escapeRegex(c.groupSeparator), "g"), ""), "," === c.radixPoint && (f = f.replace(a.inputmask.escapeRegex(c.radixPoint), ".")), f = f.replace(new RegExp("^" + a.inputmask.escapeRegex(c.negationSymbol.front)), "-"), f = f.replace(new RegExp(a.inputmask.escapeRegex(c.negationSymbol.back) + "$"), ""), isFinite(f) && isFinite(c.max) && (d = parseFloat(f) <= parseFloat(c.max)), d
},
definitions: {
"~": {
validator: function (b, c, d, e, f) {
var g = f.signHandler(b, c, d, e, f);
if (!g && (g = f.radixHandler(b, c, d, e, f), !g && (g = e ? new RegExp("[0-9" + a.inputmask.escapeRegex(f.groupSeparator) + "]").test(b) : new RegExp("[0-9]").test(b), g === !0 && (g = f.leadingZeroHandler(b, c, d, e, f), g === !0)))) {
var h = a.inArray(f.radixPoint, c.buffer);
g = f.digitsOptional === !1 && d > h && !e ? {pos: d, remove: d} : {pos: d}
}
return g
}, cardinality: 1, prevalidator: null
}, "+": {
validator: function (a, b, c, d, e) {
var f = e.signHandler(a, b, c, d, e);
return !f && (d && e.allowMinus && a === e.negationSymbol.front || e.allowMinus && "-" == a || e.allowPlus && "+" == a) && (f = "-" == a ? "" != e.negationSymbol.back ? {
pos: c,
c: "-" === a ? e.negationSymbol.front : "+",
caret: c + 1,
insert: {pos: b.buffer.length, c: e.negationSymbol.back}
} : {pos: c, c: "-" === a ? e.negationSymbol.front : "+", caret: c + 1} : !0), f
}, cardinality: 1, prevalidator: null, placeholder: ""
}, "-": {
validator: function (a, b, c, d, e) {
var f = e.signHandler(a, b, c, d, e);
return !f && d && e.allowMinus && a === e.negationSymbol.back && (f = !0), f
}, cardinality: 1, prevalidator: null, placeholder: ""
}, ":": {
validator: function (b, c, d, e, f) {
var g = f.signHandler(b, c, d, e, f);
if (!g) {
var h = "[" + a.inputmask.escapeRegex(f.radixPoint) + "]";
g = new RegExp(h).test(b), g && c.validPositions[d] && c.validPositions[d].match.placeholder == f.radixPoint && (g = {caret: d + 1})
}
return g
}, cardinality: 1, prevalidator: null, placeholder: function (a) {
return a.radixPoint
}
}
},
insertMode: !0,
autoUnmask: !1,
unmaskAsNumber: !1,
onUnMask: function (b, c, d) {
var e = b.replace(d.prefix, "");
return e = e.replace(d.suffix, ""), e = e.replace(new RegExp(a.inputmask.escapeRegex(d.groupSeparator), "g"), ""), d.unmaskAsNumber ? (e = e.replace(a.inputmask.escapeRegex.call(this, d.radixPoint), "."), Number(e)) : e
},
isComplete: function (b, c) {
var d = b.join(""), e = b.slice();
if (c.postFormat(e, 0, !0, c), e.join("") != d)return !1;
var f = d.replace(c.prefix, "");
return f = f.replace(c.suffix, ""), f = f.replace(new RegExp(a.inputmask.escapeRegex(c.groupSeparator), "g"), ""), "," === c.radixPoint && (f = f.replace(a.inputmask.escapeRegex(c.radixPoint), ".")), isFinite(f)
},
onBeforeMask: function (b, c) {
if ("" != c.radixPoint && isFinite(b))b = b.toString().replace(".", c.radixPoint); else {
var d = b.match(/,/g), e = b.match(/\./g);
e && d ? e.length > d.length ? (b = b.replace(/\./g, ""), b = b.replace(",", c.radixPoint)) : d.length > e.length ? (b = b.replace(/,/g, ""), b = b.replace(".", c.radixPoint)) : b = b.indexOf(".") < b.indexOf(",") ? b.replace(/\./g, "") : b = b.replace(/,/g, "") : b = b.replace(new RegExp(a.inputmask.escapeRegex(c.groupSeparator), "g"), "")
}
return 0 == c.digits && (-1 != b.indexOf(".") ? b = b.substring(0, b.indexOf(".")) : -1 != b.indexOf(",") && (b = b.substring(0, b.indexOf(",")))), b
},
canClearPosition: function (b, c, d, e, f) {
var g = b.validPositions[c].input, h = g != f.radixPoint && isFinite(g) || c == d || g == f.groupSeparator || g == f.negationSymbol.front || g == f.negationSymbol.back;
if (h && isFinite(g)) {
var i;
if (!e && b.buffer) {
i = b.buffer.join("").substr(0, c).match(f.regex.integerNPart(f));
var j = c + 1, k = null == i || 0 == parseInt(i[0].replace(new RegExp(a.inputmask.escapeRegex(f.groupSeparator), "g"), ""));
if (k)for (; b.validPositions[j] && (b.validPositions[j].input == f.groupSeparator || "0" == b.validPositions[j].input);)delete b.validPositions[j], j++
}
var l = [];
for (var m in b.validPositions)l.push(b.validPositions[m].input);
i = l.join("").match(f.regex.integerNPart(f));
var n = a.inArray(f.radixPoint, b.buffer);
if (i && (-1 == n || n >= c))if (0 == i[0].indexOf("0"))h = i.index != c || -1 == n; else {
var o = parseInt(i[0].replace(new RegExp(a.inputmask.escapeRegex(f.groupSeparator), "g"), ""));
-1 != n && 10 > o && "0" == f.placeholder.charAt(0) && (b.validPositions[c].input = "0", b.p = f.prefix.length + 1, h = !1)
}
}
return h
}
},
currency: {
prefix: "$ ",
groupSeparator: ",",
alias: "numeric",
placeholder: "0",
autoGroup: !0,
digits: 2,
digitsOptional: !1,
clearMaskOnLostFocus: !1
},
decimal: {alias: "numeric"},
integer: {alias: "numeric", digits: "0", radixPoint: ""}
}), a.fn.inputmask
}(jQuery), function (a) {
return a.extend(a.inputmask.defaults.aliases, {
phone: {
url: "phone-codes/phone-codes.js",
maskInit: "+pp(pp)pppppppp",
countrycode: "",
mask: function (b) {
b.definitions = {
p: {
validator: function () {
return !1
}, cardinality: 1
}, "#": {validator: "[0-9]", cardinality: 1}
};
var c = [];
return a.ajax({
url: b.url, async: !1, dataType: "json", success: function (a) {
c = a
}, error: function (a, c, d) {
alert(d + " - " + b.url)
}
}), c = c.sort(function (a, b) {
return (a.mask || a) < (b.mask || b) ? -1 : 1
}), "" != b.countrycode && (b.maskInit = "+" + b.countrycode + b.maskInit.substring(3)), c.splice(0, 0, b.maskInit), c
},
nojumps: !0,
nojumpsThreshold: 1,
onBeforeMask: function (a, b) {
var c = a.replace(/^0/g, "");
return (c.indexOf(b.countrycode) > 1 || -1 == c.indexOf(b.countrycode)) && (c = "+" + b.countrycode + c), c
}
}, phonebe: {alias: "phone", url: "phone-codes/phone-be.js", countrycode: "32", nojumpsThreshold: 4}
}), a.fn.inputmask
}(jQuery), function (a) {
return a.extend(a.inputmask.defaults.aliases, {
Regex: {
mask: "r",
greedy: !1,
repeat: "*",
regex: null,
regexTokens: null,
tokenizer: /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g,
quantifierFilter: /[0-9]+[^,]/,
isComplete: function (a, b) {
return new RegExp(b.regex).test(a.join(""))
},
definitions: {
r: {
validator: function (b, c, d, e, f) {
function g(a, b) {
this.matches = [], this.isGroup = a || !1, this.isQuantifier = b || !1, this.quantifier = {
min: 1,
max: 1
}, this.repeaterPart = void 0
}
function h() {
var a, b, c = new g, d = [];
for (f.regexTokens = []; a = f.tokenizer.exec(f.regex);)switch (b = a[0], b.charAt(0)) {
case"(":
d.push(new g(!0));
break;
case")":
var e = d.pop();
d.length > 0 ? d[d.length - 1].matches.push(e) : c.matches.push(e);
break;
case"{":
case"+":
case"*":
var h = new g(!1, !0);
b = b.replace(/[{}]/g, "");
var i = b.split(","), j = isNaN(i[0]) ? i[0] : parseInt(i[0]), k = 1 == i.length ? j : isNaN(i[1]) ? i[1] : parseInt(i[1]);
if (h.quantifier = {min: j, max: k}, d.length > 0) {
var l = d[d.length - 1].matches;
if (a = l.pop(), !a.isGroup) {
var e = new g(!0);
e.matches.push(a), a = e
}
l.push(a), l.push(h)
} else {
if (a = c.matches.pop(), !a.isGroup) {
var e = new g(!0);
e.matches.push(a), a = e
}
c.matches.push(a), c.matches.push(h)
}
break;
default:
d.length > 0 ? d[d.length - 1].matches.push(b) : c.matches.push(b)
}
c.matches.length > 0 && f.regexTokens.push(c)
}
function i(b, c) {
var d = !1;
c && (k += "(", m++);
for (var e = 0; e < b.matches.length; e++) {
var f = b.matches[e];
if (1 == f.isGroup)d = i(f, !0); else if (1 == f.isQuantifier) {
var g = a.inArray(f, b.matches), h = b.matches[g - 1], j = k;
if (isNaN(f.quantifier.max)) {
for (; f.repeaterPart && f.repeaterPart != k && f.repeaterPart.length > k.length && !(d = i(h, !0)););
d = d || i(h, !0), d && (f.repeaterPart = k), k = j + f.quantifier.max
} else {
for (var l = 0, o = f.quantifier.max - 1; o > l && !(d = i(h, !0)); l++);
k = j + "{" + f.quantifier.min + "," + f.quantifier.max + "}"
}
} else if (void 0 != f.matches)for (var p = 0; p < f.length && !(d = i(f[p], c)); p++); else {
var q;
if ("[" == f.charAt(0)) {
q = k, q += f;
for (var r = 0; m > r; r++)q += ")";
var s = new RegExp("^(" + q + ")$");
d = s.test(n)
} else for (var t = 0, u = f.length; u > t; t++)if ("\\" != f.charAt(t)) {
q = k, q += f.substr(0, t + 1), q = q.replace(/\|$/, "");
for (var r = 0; m > r; r++)q += ")";
var s = new RegExp("^(" + q + ")$");
if (d = s.test(n))break
}
k += f
}
if (d)break
}
return c && (k += ")", m--), d
}
null == f.regexTokens && h();
var j = c.buffer.slice(), k = "", l = !1, m = 0;
j.splice(d, 0, b);
for (var n = j.join(""), o = 0; o < f.regexTokens.length; o++) {
var g = f.regexTokens[o];
if (l = i(g, g.isGroup))break
}
return l
}, cardinality: 1
}
}
}
}), a.fn.inputmask
}(jQuery);
| bsd-3-clause |
endlessm/chromium-browser | chrome/browser/extensions/external_install_manager.cc | 11314 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/external_install_manager.h"
#include <string>
#include "base/check_op.h"
#include "base/metrics/histogram_macros.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/extension_management.h"
#include "chrome/browser/extensions/external_install_error.h"
#include "chrome/browser/profiles/profile.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/common/extension.h"
#include "extensions/common/feature_switch.h"
#include "extensions/common/features/feature_channel.h"
#include "extensions/common/manifest.h"
#include "extensions/common/manifest_url_handlers.h"
namespace extensions {
namespace {
// Histogram values for logging events related to externally installed
// extensions.
enum ExternalExtensionEvent {
EXTERNAL_EXTENSION_INSTALLED = 0,
EXTERNAL_EXTENSION_IGNORED,
EXTERNAL_EXTENSION_REENABLED,
EXTERNAL_EXTENSION_UNINSTALLED,
EXTERNAL_EXTENSION_BUCKET_BOUNDARY,
};
// Prompt the user this many times before considering an extension acknowledged.
const int kMaxExtensionAcknowledgePromptCount = 3;
void LogExternalExtensionEvent(const Extension* extension,
ExternalExtensionEvent event) {
UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
event,
EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
if (ManifestURL::UpdatesFromGallery(extension)) {
UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
event,
EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
} else {
UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
event,
EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
}
}
} // namespace
ExternalInstallManager::ExternalInstallManager(
content::BrowserContext* browser_context,
bool is_first_run)
: browser_context_(browser_context),
is_first_run_(is_first_run),
extension_prefs_(ExtensionPrefs::Get(browser_context_)),
currently_visible_install_alert_(nullptr) {
DCHECK(browser_context_);
extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_));
Profile* profile = Profile::FromBrowserContext(browser_context_);
registrar_.Add(this, extensions::NOTIFICATION_EXTENSION_REMOVED,
content::Source<Profile>(profile));
// Populate the set of unacknowledged external extensions now. We can't just
// rely on IsUnacknowledgedExternalExtension() for cases like
// OnExtensionLoaded(), since we need to examine the disable reasons, which
// can be removed throughout the session.
for (const auto& extension :
ExtensionRegistry::Get(browser_context)->disabled_extensions()) {
if (IsUnacknowledgedExternalExtension(*extension))
unacknowledged_ids_.insert(extension->id());
}
}
ExternalInstallManager::~ExternalInstallManager() {
// Shutdown should have been called.
DCHECK(errors_.empty());
}
void ExternalInstallManager::Shutdown() {
// Delete all errors when the profile is shutting down, before associated
// services are deleted.
errors_.clear();
}
bool ExternalInstallManager::IsPromptingEnabled() {
return FeatureSwitch::prompt_for_external_extensions()->IsEnabled();
}
void ExternalInstallManager::AddExternalInstallError(const Extension* extension,
bool is_new_profile) {
// Error already exists or has been previously shown.
if (base::Contains(errors_, extension->id()) ||
shown_ids_.count(extension->id()) > 0)
return;
ExternalInstallError::AlertType alert_type =
(ManifestURL::UpdatesFromGallery(extension) && !is_new_profile)
? ExternalInstallError::BUBBLE_ALERT
: ExternalInstallError::MENU_ALERT;
std::unique_ptr<ExternalInstallError> error(new ExternalInstallError(
browser_context_, extension->id(), alert_type, this));
shown_ids_.insert(extension->id());
errors_.insert(std::make_pair(extension->id(), std::move(error)));
}
void ExternalInstallManager::RemoveExternalInstallError(
const std::string& extension_id) {
auto iter = errors_.find(extension_id);
if (iter != errors_.end()) {
// The |extension_id| may be owned by the ExternalInstallError, which is
// deleted subsequently. To avoid any UAFs, make a safe copy of
// |extension_id| now.
std::string extension_id_copy = extension_id;
if (iter->second.get() == currently_visible_install_alert_)
currently_visible_install_alert_ = nullptr;
errors_.erase(iter);
// No need to erase the ID from |unacknowledged_ids_|; it's already in
// |shown_ids_|.
UpdateExternalExtensionAlert();
}
}
void ExternalInstallManager::UpdateExternalExtensionAlert() {
// If the feature is not enabled do nothing.
if (!IsPromptingEnabled())
return;
// Look for any extensions that were disabled because of being unacknowledged
// external extensions.
const ExtensionSet& disabled_extensions =
ExtensionRegistry::Get(browser_context_)->disabled_extensions();
const ExtensionSet& blocked_extensions =
ExtensionRegistry::Get(browser_context_)->blocked_extensions();
// The list of ids can be mutated during this loop, so make a copy.
const std::set<ExtensionId> ids_copy = unacknowledged_ids_;
for (const auto& id : ids_copy) {
if (base::Contains(errors_, id) || shown_ids_.count(id) > 0)
continue;
// Ignore the blocked and disabled extensions. They will be put into
// disabled list once unblocked.
if (blocked_extensions.GetByID(id))
continue;
const Extension* extension = disabled_extensions.GetByID(id);
CHECK(extension);
// Warn the user about the suspicious extension.
if (extension_prefs_->IncrementAcknowledgePromptCount(id) >
kMaxExtensionAcknowledgePromptCount) {
// Stop prompting for this extension and record metrics.
extension_prefs_->AcknowledgeExternalExtension(id);
LogExternalExtensionEvent(extension, EXTERNAL_EXTENSION_IGNORED);
unacknowledged_ids_.erase(id);
continue;
}
if (is_first_run_)
extension_prefs_->SetExternalInstallFirstRun(id);
// |first_run| is true if the extension was installed during a first run
// (even if it's post-first run now).
AddExternalInstallError(extension,
extension_prefs_->IsExternalInstallFirstRun(id));
}
}
void ExternalInstallManager::AcknowledgeExternalExtension(
const std::string& id) {
unacknowledged_ids_.erase(id);
extension_prefs_->AcknowledgeExternalExtension(id);
UpdateExternalExtensionAlert();
}
void ExternalInstallManager::DidChangeInstallAlertVisibility(
ExternalInstallError* external_install_error,
bool visible) {
if (visible) {
currently_visible_install_alert_ = external_install_error;
} else if (!visible &&
currently_visible_install_alert_ == external_install_error) {
currently_visible_install_alert_ = nullptr;
}
}
std::vector<ExternalInstallError*>
ExternalInstallManager::GetErrorsForTesting() {
std::vector<ExternalInstallError*> errors;
for (auto const& error : errors_)
errors.push_back(error.second.get());
return errors;
}
void ExternalInstallManager::ClearShownIdsForTesting() {
shown_ids_.clear();
}
void ExternalInstallManager::OnExtensionLoaded(
content::BrowserContext* browser_context,
const Extension* extension) {
if (!unacknowledged_ids_.count(extension->id()))
return;
// We treat loading as acknowledgement (since the user consciously chose to
// re-enable the extension).
AcknowledgeExternalExtension(extension->id());
LogExternalExtensionEvent(extension, EXTERNAL_EXTENSION_REENABLED);
// If we had an error for this extension, remove it.
RemoveExternalInstallError(extension->id());
}
void ExternalInstallManager::OnExtensionInstalled(
content::BrowserContext* browser_context,
const Extension* extension,
bool is_update) {
ExtensionManagement* settings =
ExtensionManagementFactory::GetForBrowserContext(
Profile::FromBrowserContext(browser_context_));
bool is_recommended_by_policy = settings->GetInstallationMode(extension) ==
ExtensionManagement::INSTALLATION_RECOMMENDED;
// Certain extension locations are specific enough that we can
// auto-acknowledge any extension that came from one of them.
// Extensions recommended by policy can also be auto-acknowledged.
if (Manifest::IsPolicyLocation(extension->location()) ||
extension->location() == Manifest::EXTERNAL_COMPONENT ||
is_recommended_by_policy) {
AcknowledgeExternalExtension(extension->id());
return;
}
if (!IsUnacknowledgedExternalExtension(*extension))
return;
unacknowledged_ids_.insert(extension->id());
LogExternalExtensionEvent(extension, EXTERNAL_EXTENSION_INSTALLED);
UpdateExternalExtensionAlert();
}
void ExternalInstallManager::OnExtensionUninstalled(
content::BrowserContext* browser_context,
const Extension* extension,
extensions::UninstallReason reason) {
if (unacknowledged_ids_.erase(extension->id()))
LogExternalExtensionEvent(extension, EXTERNAL_EXTENSION_UNINSTALLED);
}
bool ExternalInstallManager::IsUnacknowledgedExternalExtension(
const Extension& extension) const {
if (!IsPromptingEnabled())
return false;
int disable_reasons = extension_prefs_->GetDisableReasons(extension.id());
bool is_from_sideload_wipeout =
(disable_reasons & disable_reason::DISABLE_SIDELOAD_WIPEOUT) != 0;
// We don't consider extensions that weren't disabled for being external so
// that we grandfather in extensions. External extensions are only disabled on
// install with the "prompt for external extensions" feature enabled.
bool is_disabled_external =
(disable_reasons & disable_reason::DISABLE_EXTERNAL_EXTENSION) != 0;
return is_disabled_external && !is_from_sideload_wipeout &&
Manifest::IsExternalLocation(extension.location()) &&
!extension_prefs_->IsExternalExtensionAcknowledged(extension.id());
}
void ExternalInstallManager::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(type, extensions::NOTIFICATION_EXTENSION_REMOVED);
// The error is invalidated if the extension has been loaded or removed.
// It's a shame we have to use the notification system (instead of the
// registry observer) for this, but the ExtensionUnloaded notification is
// not sent out if the extension is disabled (which it is here).
const std::string& extension_id =
content::Details<const Extension>(details).ptr()->id();
if (base::Contains(errors_, extension_id))
RemoveExternalInstallError(extension_id);
}
} // namespace extensions
| bsd-3-clause |
vivo-project/Vitro | webapp/src/main/webapp/js/search/searchIndex.js | 854 | /* $This file is distributed under the terms of the license in LICENSE$ */
/*
Functions for use by searchIndex.ftl
*/
function updateSearchIndexerStatus() {
$.ajax({
url: searchIndexerStatusUrl,
dataType: "html",
complete: function(xhr, status) {
if (xhr.status == 200) {
updatePanelContents(xhr.responseText);
setTimeout(updateSearchIndexerStatus,5000);
} else {
displayErrorMessage(xhr.status + " " + xhr.statusText);
}
}
});
}
function updatePanelContents(contents) {
document.getElementById("searchIndexerStatus").innerHTML = contents;
}
function displayErrorMessage(message) {
document.getElementById("searchIndexerError").innerHTML = "<h3>" + message + "</h3>";
}
$(document).ready(updateSearchIndexerStatus());
| bsd-3-clause |
haroon-sheikh/django-dynamic-preferences | setup.py | 1637 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import dynamic_preferences
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
version = dynamic_preferences.__version__
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
print("You probably want to also tag the version now:")
print(" git tag -a %s -m 'version %s'" % (version, version))
print(" git push --tags")
sys.exit()
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='django-dynamic-preferences',
version=version,
description="""Dynamic global and instance settings for your django project""",
long_description=readme + '\n\n' + history,
author='Eliot Berriot',
author_email='contact@eliotberriot.com',
url='https://github.com/EliotBerriot/django-dynamic-preferences',
packages=[
'dynamic_preferences',
],
include_package_data=True,
install_requires=[
'django>=1.8',
'six',
'persisting_theory==0.2.1',
],
license="BSD",
zip_safe=False,
keywords='django-dynamic-preferences',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
)
| bsd-3-clause |
piaoxuedtian/myrepo | framework/i18n/data/ca_es.php | 30724 | <?php
/**
* Locale data for 'ca_ES'.
*
* This file is automatically generated by yiic cldr command.
*
* Copyright © 1991-2007 Unicode, Inc. All rights reserved.
* Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
*
* Copyright © 2008-2011 Yii Software LLC (http://www.yiiframework.com/license/)
*/
return array (
'version' => '4123',
'numberSymbols' =>
array (
'decimal' => ',',
'group' => '.',
'list' => ';',
'percentSign' => '%',
'plusSign' => '+',
'minusSign' => '-',
'exponential' => 'E',
'perMille' => '‰',
'infinity' => '∞',
'nan' => 'NaN',
'alias' => '',
),
'decimalFormat' => '#,##0.###',
'scientificFormat' => '#E0',
'percentFormat' => '#,##0%',
'currencyFormat' => '#,##0.00 ¤',
'currencySymbols' =>
array (
'AUD' => 'AU$',
'BRL' => 'BR$',
'CAD' => 'CA$',
'CNY' => 'CN¥',
'EUR' => '€',
'GBP' => '£',
'HKD' => 'HK$',
'ILS' => '₪',
'INR' => '₹',
'JPY' => 'JP¥',
'KRW' => '₩',
'MXN' => 'MX$',
'NZD' => 'NZ$',
'THB' => '฿',
'TWD' => 'NT$',
'USD' => 'US$',
'VND' => '₫',
'XAF' => 'FCFA',
'XCD' => 'EC$',
'XOF' => 'CFA',
'XPF' => 'CFPF',
'ESP' => '₧',
),
'monthNames' =>
array (
'wide' =>
array (
1 => 'de gener',
2 => 'de febrer',
3 => 'de març',
4 => 'd’abril',
5 => 'de maig',
6 => 'de juny',
7 => 'de juliol',
8 => 'd’agost',
9 => 'de setembre',
10 => 'd’octubre',
11 => 'de novembre',
12 => 'de desembre',
),
'abbreviated' =>
array (
1 => 'de gen.',
2 => 'de febr.',
3 => 'de març',
4 => 'd’abr.',
5 => 'de maig',
6 => 'de juny',
7 => 'de jul.',
8 => 'd’ag.',
9 => 'de set.',
10 => 'd’oct.',
11 => 'de nov.',
12 => 'de des.',
),
'narrow' =>
array (
1 => 'G',
2 => 'F',
3 => 'M',
4 => 'A',
5 => 'M',
6 => 'J',
7 => 'G',
8 => 'A',
9 => 'S',
10 => 'O',
11 => 'N',
12 => 'D',
),
),
'monthNamesSA' =>
array (
'narrow' =>
array (
1 => 'g',
2 => 'f',
3 => 'm',
4 => 'a',
5 => 'm',
6 => 'j',
7 => 'j',
8 => 'a',
9 => 's',
10 => 'o',
11 => 'n',
12 => 'd',
),
'abbreviated' =>
array (
1 => 'gen.',
2 => 'febr.',
3 => 'març',
4 => 'abr.',
5 => 'maig',
6 => 'juny',
7 => 'jul.',
8 => 'ag.',
9 => 'set.',
10 => 'oct.',
11 => 'nov.',
12 => 'des.',
),
'wide' =>
array (
1 => 'gener',
2 => 'febrer',
3 => 'març',
4 => 'abril',
5 => 'maig',
6 => 'juny',
7 => 'juliol',
8 => 'agost',
9 => 'setembre',
10 => 'octubre',
11 => 'novembre',
12 => 'desembre',
),
),
'weekDayNames' =>
array (
'wide' =>
array (
0 => 'diumenge',
1 => 'dilluns',
2 => 'dimarts',
3 => 'dimecres',
4 => 'dijous',
5 => 'divendres',
6 => 'dissabte',
),
'abbreviated' =>
array (
0 => 'dg.',
1 => 'dl.',
2 => 'dt.',
3 => 'dc.',
4 => 'dj.',
5 => 'dv.',
6 => 'ds.',
),
'narrow' =>
array (
0 => 'G',
1 => 'l',
2 => 'T',
3 => 'C',
4 => 'J',
5 => 'V',
6 => 'S',
),
),
'weekDayNamesSA' =>
array (
'narrow' =>
array (
0 => 'g',
1 => 'l',
2 => 't',
3 => 'c',
4 => 'j',
5 => 'v',
6 => 's',
),
'abbreviated' =>
array (
0 => 'dg',
1 => 'dl',
2 => 'dt',
3 => 'dc',
4 => 'dj',
5 => 'dv',
6 => 'ds',
),
'wide' =>
array (
0 => 'Diumenge',
1 => 'Dilluns',
2 => 'Dimarts',
3 => 'Dimecres',
4 => 'Dijous',
5 => 'Divendres',
6 => 'Dissabte',
),
),
'eraNames' =>
array (
'abbreviated' =>
array (
0 => 'aC',
1 => 'dC',
),
'wide' =>
array (
0 => 'abans de Crist',
1 => 'després de Crist',
),
'narrow' =>
array (
0 => 'aC',
1 => 'dC',
),
),
'dateFormats' =>
array (
'full' => 'EEEE d MMMM \'de\' y',
'long' => 'd MMMM \'de\' y',
'medium' => 'dd/MM/yyyy',
'short' => 'dd/MM/yy',
),
'timeFormats' =>
array (
'full' => 'H:mm:ss zzzz',
'long' => 'H:mm:ss z',
'medium' => 'H:mm:ss',
'short' => 'H:mm',
),
'dateTimeFormat' => '{1} {0}',
'amName' => 'a.m.',
'pmName' => 'p.m.',
'orientation' => 'ltr',
'languages' =>
array (
'aa' => 'àfar',
'ab' => 'abkhaz',
'ace' => 'atjeh',
'ach' => 'acoli',
'ada' => 'adangme',
'ady' => 'adigué',
'ae' => 'avèstic',
'af' => 'afrikaans',
'afa' => 'llengua afroasiàtica',
'afh' => 'afrihili',
'ain' => 'ainu',
'ak' => 'àkan',
'akk' => 'accadi',
'ale' => 'aleuta',
'alg' => 'llengua algonquina',
'alt' => 'altaic meridional',
'am' => 'amhàric',
'an' => 'aragonès',
'ang' => 'anglès antic',
'anp' => 'angika',
'apa' => 'llengua apatxe',
'ar' => 'àrab',
'arc' => 'arameu',
'arn' => 'araucà',
'arp' => 'arapaho',
'art' => 'llengua artificial',
'arw' => 'arauac',
'as' => 'assamès',
'ast' => 'asturià',
'ath' => 'llengua atapascana',
'aus' => 'llengua australiana',
'av' => 'àvar',
'awa' => 'awadhi',
'ay' => 'aimara',
'az' => 'àzeri',
'ba' => 'baixkir',
'bad' => 'banda',
'bai' => 'bamileké',
'bal' => 'balutxi',
'ban' => 'balinès',
'bas' => 'basa',
'bat' => 'llengua bàltica',
'be' => 'bielorús',
'bej' => 'beja',
'bem' => 'bemba',
'ber' => 'berber',
'bg' => 'búlgar',
'bh' => 'bihari',
'bho' => 'bhojpuri',
'bi' => 'bislama',
'bik' => 'bicol',
'bin' => 'bini',
'bla' => 'blackfoot',
'bm' => 'bambara',
'bn' => 'bengalí',
'bnt' => 'bantu',
'bo' => 'tibetà',
'br' => 'bretó',
'bra' => 'braj',
'bs' => 'bosnià',
'btk' => 'batak',
'bua' => 'buriat',
'bug' => 'bugui',
'byn' => 'bilin',
'ca' => 'català',
'cad' => 'caddo',
'cai' => 'llengua ameríndia d\'Amèrica Central',
'car' => 'carib',
'cau' => 'llengua caucàsica',
'cch' => 'atsam',
'ce' => 'txetxè',
'ceb' => 'cebuà',
'cel' => 'llengua cèltica',
'ch' => 'chamorro',
'chb' => 'txibtxa',
'chg' => 'txagatai',
'chk' => 'chuuk',
'chm' => 'mari',
'chn' => 'pidgin chinook',
'cho' => 'choctaw',
'chp' => 'chipewyan',
'chr' => 'cherokee',
'chy' => 'xeienne',
'cmc' => 'txam',
'co' => 'cors',
'cop' => 'copte',
'cpe' => 'llengua criolla o pidgin basada en l\'anglès',
'cpf' => 'llengua criolla o pidgin basada en el francès',
'cpp' => 'llengua criolla o pidgin basada en el portuguès',
'cr' => 'cree',
'crh' => 'tàtar de Crimea',
'crp' => 'llengua criolla o pidgin',
'cs' => 'txec',
'csb' => 'caixubi',
'cu' => 'eslau eclesiàstic',
'cus' => 'llengua cuixítica',
'cv' => 'txuvaix',
'cy' => 'gal·lès',
'da' => 'danès',
'dak' => 'dakota',
'dar' => 'darguà',
'day' => 'daiak',
'de' => 'alemany',
'de_at' => 'alemany austríac',
'de_ch' => 'alt alemany suís',
'del' => 'delaware',
'den' => 'slavey',
'dgr' => 'dogrib',
'din' => 'dinka',
'doi' => 'dogri',
'dra' => 'llengua dravídica',
'dsb' => 'baix sòrab',
'dua' => 'duala',
'dum' => 'neerlandès mitjà',
'dv' => 'divehi',
'dyu' => 'jula',
'dz' => 'dzongka',
'ee' => 'ewe',
'efi' => 'efik',
'egy' => 'egipci antic',
'eka' => 'ekajuk',
'el' => 'grec',
'elx' => 'elamita',
'en' => 'anglès',
'en_au' => 'anglès australià',
'en_ca' => 'anglès canadenc',
'en_gb' => 'anglès britànic',
'en_us' => 'anglès americà',
'enm' => 'anglès mitjà',
'eo' => 'esperanto',
'es' => 'espanyol',
'es_419' => 'espanyol d\'Hispanoamèrica',
'es_es' => 'espanyol d\'Espanya',
'et' => 'estonià',
'eu' => 'basc',
'ewo' => 'ewondo',
'fa' => 'persa',
'fan' => 'fang',
'fat' => 'fanti',
'ff' => 'ful',
'fi' => 'finès',
'fil' => 'filipí',
'fiu' => 'llengua finoúgrica',
'fj' => 'fijià',
'fo' => 'feroès',
'fon' => 'fon',
'fr' => 'francès',
'fr_ca' => 'francès canadenc',
'fr_ch' => 'francès suís',
'frm' => 'francès mitjà',
'fro' => 'francès antic',
'frr' => 'frisó septentrional',
'frs' => 'frisó occidental',
'fur' => 'friülà',
'fy' => 'frisó oriental',
'ga' => 'irlandès',
'gaa' => 'ga',
'gay' => 'gayo',
'gba' => 'gbaya',
'gd' => 'gaèlic escocès',
'gem' => 'llengua germànica',
'gez' => 'gueez',
'gil' => 'gilbertès',
'gl' => 'gallec',
'gmh' => 'alt alemany mitjà',
'gn' => 'guaraní',
'goh' => 'alt alemany antic',
'gon' => 'gondi',
'gor' => 'gorontalo',
'got' => 'gòtic',
'grb' => 'grebo',
'grc' => 'grec antic',
'gsw' => 'alemany suís',
'gu' => 'gujarati',
'gv' => 'manx',
'gwi' => 'gwichin',
'ha' => 'haussa',
'hai' => 'haida',
'haw' => 'hawaià',
'he' => 'hebreu',
'hi' => 'hindi',
'hil' => 'hiligainon',
'him' => 'himachali',
'hit' => 'hitita',
'hmn' => 'hmong',
'ho' => 'hiri motu',
'hr' => 'croat',
'hsb' => 'alt sòrab',
'ht' => 'haitià',
'hu' => 'hongarès',
'hup' => 'hupa',
'hy' => 'armeni',
'hz' => 'herero',
'ia' => 'interlingua',
'iba' => 'iban',
'id' => 'indonesi',
'ie' => 'interlingue',
'ig' => 'igbo',
'ii' => 'yi sichuan',
'ijo' => 'ijo',
'ik' => 'inupiak',
'ilo' => 'ilocà',
'inc' => 'llengua índica',
'ine' => 'llengua indoeuropea',
'inh' => 'ingúix',
'io' => 'ido',
'ira' => 'llengua irànica',
'iro' => 'iroquès',
'is' => 'islandès',
'it' => 'italià',
'iu' => 'inuktitut',
'ja' => 'japonès',
'jbo' => 'lojban',
'jpr' => 'judeopersa',
'jrb' => 'judeoàrab',
'jv' => 'javanès',
'ka' => 'georgià',
'kaa' => 'karakalpak',
'kab' => 'cabilenc',
'kac' => 'katxin',
'kaj' => 'jju',
'kam' => 'kamba',
'kar' => 'karen',
'kaw' => 'kawi',
'kbd' => 'kabardí',
'kcg' => 'tyap',
'kfo' => 'koro',
'kg' => 'kongo',
'kha' => 'khasi',
'khi' => 'llengua khoisan',
'kho' => 'khotanès',
'ki' => 'kikuiu',
'kj' => 'kuanyama',
'kk' => 'kazakh',
'kl' => 'grenlandès',
'km' => 'khmer',
'kmb' => 'kimbundu',
'kn' => 'kannada',
'ko' => 'coreà',
'kok' => 'konkani',
'kos' => 'kosraeà',
'kpe' => 'kpelle',
'kr' => 'kanuri',
'krc' => 'karatxai',
'krl' => 'carelià',
'kro' => 'kru',
'kru' => 'kurukh',
'ks' => 'caixmiri',
'ku' => 'kurd',
'kum' => 'kúmik',
'kut' => 'kutenai',
'kv' => 'komi',
'kw' => 'còrnic',
'ky' => 'kirguís',
'la' => 'llatí',
'lad' => 'ladí',
'lah' => 'panjabi occidental',
'lam' => 'lamba',
'lb' => 'luxemburguès',
'lez' => 'lesguià',
'lg' => 'ganda',
'li' => 'limburguès',
'ln' => 'lingala',
'lo' => 'laosià',
'lol' => 'mongo',
'loz' => 'lozi',
'lt' => 'lituà',
'lu' => 'luba katanga',
'lua' => 'luba-lulua',
'lui' => 'luisenyo',
'lun' => 'lunda',
'luo' => 'luo',
'lus' => 'mizo',
'lv' => 'letó',
'mad' => 'madurès',
'mag' => 'magahi',
'mai' => 'maithili',
'mak' => 'makassar',
'man' => 'mandinga',
'map' => 'llengua austronèsia',
'mas' => 'massai',
'mdf' => 'mordovià moksa',
'mdr' => 'mandar',
'men' => 'mende',
'mg' => 'malgaix',
'mga' => 'gaèlic irlandès mitjà',
'mh' => 'marshallès',
'mi' => 'maori',
'mic' => 'micmac',
'min' => 'minangkabau',
'mis' => 'llengua miscel·lània',
'mk' => 'macedoni',
'mkh' => 'llengua monkhmer',
'ml' => 'malaialam',
'mn' => 'mongol',
'mnc' => 'manxú',
'mni' => 'manipurí',
'mno' => 'llengua manobo',
'mo' => 'moldau',
'moh' => 'mohawk',
'mos' => 'moré',
'mr' => 'marathi',
'ms' => 'malai',
'mt' => 'maltès',
'mul' => 'llengües vàries',
'mun' => 'llengua munda',
'mus' => 'creek',
'mwl' => 'mirandès',
'mwr' => 'marwari',
'my' => 'birmà',
'myn' => 'llengua maia',
'myv' => 'mordovià erza',
'na' => 'nauruà',
'nah' => 'nàhuatl',
'nai' => 'llengua ameríndia septentrional',
'nap' => 'napolità',
'nb' => 'noruec bokmål',
'nd' => 'ndebele septentrional',
'nds' => 'baix alemany',
'ne' => 'nepalès',
'new' => 'newari',
'ng' => 'ndonga',
'nia' => 'nias',
'nic' => 'llengua nigerokurdufaniana',
'niu' => 'niueà',
'nl' => 'neerlandès',
'nl_be' => 'flamenc',
'nn' => 'noruec nynorsk',
'no' => 'noruec',
'nog' => 'nogai',
'non' => 'nòrdic antic',
'nqo' => 'n’Ko',
'nr' => 'ndebele meridional',
'nso' => 'sotho septentrional',
'nub' => 'llengua nubiana',
'nv' => 'navaho',
'nwc' => 'newari clàssic',
'ny' => 'nyanja',
'nym' => 'nyamwesi',
'nyn' => 'nyankore',
'nyo' => 'nyoro',
'nzi' => 'nzema',
'oc' => 'occità',
'oj' => 'ojibwa',
'om' => 'oromo',
'or' => 'oriya',
'os' => 'osset',
'osa' => 'osage',
'ota' => 'turc otomà',
'oto' => 'llengua otomangueana',
'pa' => 'panjabi',
'paa' => 'llengua papú',
'pag' => 'pangasi',
'pal' => 'pahlavi',
'pam' => 'pampangà',
'pap' => 'papiamento',
'pau' => 'palauà',
'peo' => 'persa antic',
'phi' => 'llengua filipina',
'phn' => 'fenici',
'pi' => 'pali',
'pl' => 'polonès',
'pon' => 'ponapeà',
'pra' => 'pràcrit',
'pro' => 'provençal antic',
'ps' => 'pushto',
'pt' => 'portuguès',
'pt_br' => 'portuguès de Brasil',
'pt_pt' => 'portuguès de Portugal',
'qu' => 'quètxua',
'raj' => 'rajasthani',
'rap' => 'rapanui',
'rar' => 'rarotongà',
'rm' => 'retoromànic',
'rn' => 'rundi',
'ro' => 'romanès',
'roa' => 'llengua romànica',
'rom' => 'romaní',
'root' => 'arrel',
'ru' => 'rus',
'rup' => 'aromanès',
'rw' => 'ruandès',
'sa' => 'sànscrit',
'sad' => 'sandawe',
'sah' => 'iacut',
'sai' => 'llengua ameríndia meridional',
'sal' => 'llengua salish',
'sam' => 'arameu samarità',
'sas' => 'sasak',
'sat' => 'santali',
'sc' => 'sard',
'scn' => 'sicilià',
'sco' => 'escocès',
'sd' => 'sindhi',
'se' => 'sami septentrional',
'sel' => 'selkup',
'sem' => 'llengua semítica',
'sg' => 'sango',
'sga' => 'irlandès antic',
'sgn' => 'llengua de signes',
'sh' => 'serbocroat',
'shn' => 'xan',
'si' => 'singalès',
'sid' => 'sidamo',
'sio' => 'llengua sioux',
'sit' => 'llengua sinotibetana',
'sk' => 'eslovac',
'sl' => 'eslovè',
'sla' => 'llengua eslava',
'sm' => 'samoà',
'sma' => 'sami meridional',
'smi' => 'llengua sami',
'smj' => 'sami lule',
'smn' => 'sami d\'Inari',
'sms' => 'sami skolt',
'sn' => 'shona',
'snk' => 'soninke',
'so' => 'somali',
'sog' => 'sogdià',
'son' => 'songhai',
'sq' => 'albanès',
'sr' => 'serbi',
'srn' => 'sranan',
'srr' => 'serer',
'ss' => 'siswati',
'ssa' => 'llengua nilosahariana',
'st' => 'sotho meridional',
'su' => 'sundanès',
'suk' => 'sukuma',
'sus' => 'susú',
'sux' => 'sumeri',
'sv' => 'suec',
'sw' => 'suahili',
'swb' => 'comorià',
'syc' => 'siríac clàssic',
'syr' => 'siríac',
'ta' => 'tàmil',
'tai' => 'llengua tai',
'te' => 'telugu',
'tem' => 'temne',
'ter' => 'terena',
'tet' => 'tetun',
'tg' => 'tadjik',
'th' => 'thai',
'ti' => 'tigrinya',
'tig' => 'tigre',
'tiv' => 'tiv',
'tk' => 'turcman',
'tkl' => 'tokelauès',
'tl' => 'tagàlog',
'tlh' => 'klingonià',
'tli' => 'tlingit',
'tmh' => 'tamazight',
'tn' => 'tswana',
'to' => 'tongalès',
'tog' => 'tonga',
'tpi' => 'tok pisin',
'tr' => 'turc',
'ts' => 'tsonga',
'tsi' => 'tsimshià',
'tt' => 'tàtar',
'tum' => 'tumbuka',
'tup' => 'llengua tupí',
'tut' => 'llengua altaica',
'tvl' => 'tuvaluà',
'tw' => 'twi',
'ty' => 'tahitià',
'tyv' => 'tuvinià',
'udm' => 'udmurt',
'ug' => 'uigur',
'uga' => 'ugarític',
'uk' => 'ucraïnès',
'umb' => 'umbundu',
'und' => 'idioma desconegut o no vàlid',
'ur' => 'urdú',
'uz' => 'uzbek',
'vai' => 'vai',
've' => 'venda',
'vi' => 'vietnamita',
'vo' => 'volapük',
'vot' => 'vòtic',
'wa' => 'való',
'wak' => 'llengua wakash',
'wal' => 'ameto',
'war' => 'waray-waray',
'was' => 'washo',
'wen' => 'sòrab',
'wo' => 'wòlof',
'xal' => 'calmuc',
'xh' => 'xosa',
'yao' => 'yao',
'yap' => 'yapeà',
'yi' => 'jiddisch',
'yo' => 'ioruba',
'ypk' => 'llengua iupik',
'yue' => 'cantonès',
'za' => 'zhuang',
'zap' => 'zapoteca',
'zbl' => 'símbols Bliss',
'zen' => 'zenaga',
'zh' => 'xinès',
'zh_hans' => 'xinès simplificat',
'zh_hant' => 'xinès tradicional',
'znd' => 'zande',
'zu' => 'zulu',
'zun' => 'zuni',
'zxx' => 'sense contingut lingüístic',
'zza' => 'zaza',
),
'scripts' =>
array (
'arab' => 'perso-àrabic',
'armi' => 'arameu imperial',
'armn' => 'armeni',
'avst' => 'avèstic',
'bali' => 'balinès',
'batk' => 'batak',
'beng' => 'bengalí',
'blis' => 'símbols Bliss',
'bopo' => 'bopomofo',
'brah' => 'brahmi',
'brai' => 'braille',
'bugi' => 'buginès',
'buhd' => 'buhid',
'cakm' => 'chakma',
'cans' => 'síl·labes dels aborígens canadencs unificats',
'cari' => 'carià',
'cham' => 'cham',
'cher' => 'cherokee',
'cirt' => 'cirth',
'copt' => 'copte',
'cprt' => 'xipriota',
'cyrl' => 'ciríl·lic',
'cyrs' => 'ciríl·lic de l\'antic eslau eclesiàstic',
'deva' => 'devanagari',
'dsrt' => 'deseret',
'egyd' => 'demòtic egipci',
'egyh' => 'hieràtic egipci',
'egyp' => 'jeroglífic egipci',
'ethi' => 'etiòpic',
'geok' => 'georgià hucuri',
'geor' => 'georgià',
'glag' => 'glagolític',
'goth' => 'gòtic',
'grek' => 'grec',
'gujr' => 'gujarati',
'guru' => 'gurmukhi',
'hang' => 'hangul',
'hani' => 'han',
'hano' => 'hanunoo',
'hans' => 'xinès simplificat',
'hant' => 'xinès tradicional',
'hebr' => 'hebreu',
'hira' => 'hiragana',
'hmng' => 'pahawh hmong',
'hrkt' => 'katakana o hiragana',
'hung' => 'hongarès antic',
'inds' => 'escriptura de la vall de l\'Indus',
'ital' => 'cursiva antiga',
'java' => 'javanès',
'jpan' => 'japonès',
'kali' => 'kayah li',
'kana' => 'katakana',
'khar' => 'kharosthi',
'khmr' => 'khmer',
'knda' => 'kannada',
'kore' => 'coreà',
'kthi' => 'kaithi',
'lana' => 'lanna',
'laoo' => 'lao',
'latf' => 'llatí fraktur',
'latg' => 'llatí gaèlic',
'latn' => 'llatí',
'lepc' => 'lepcha',
'limb' => 'limbu',
'lina' => 'lineal A',
'linb' => 'lineal B',
'lyci' => 'lici',
'lydi' => 'lidi',
'mand' => 'mandaic',
'mani' => 'maniqueu',
'maya' => 'jeroglífics maies',
'mero' => 'meroític',
'mlym' => 'malaialam',
'mong' => 'mongol',
'moon' => 'moon',
'mtei' => 'manipurí',
'mymr' => 'birmà',
'nkoo' => 'n’Ko',
'ogam' => 'ogham',
'olck' => 'santali',
'orkh' => 'orkhon',
'orya' => 'oriya',
'osma' => 'osmanya',
'perm' => 'antic pèrmic',
'phag' => 'phagspa',
'phli' => 'pahlavi inscripcional',
'phlp' => 'psalter pahlavi',
'phlv' => 'pahlavi',
'phnx' => 'fenici',
'plrd' => 'pollard miao',
'prti' => 'parthià inscripcional',
'rjng' => 'rejang',
'roro' => 'rongo-rongo',
'runr' => 'rúnic',
'samr' => 'samarità',
'sara' => 'sarati',
'saur' => 'saurashtra',
'shaw' => 'shavià',
'sinh' => 'singalès',
'sund' => 'sundanès',
'sylo' => 'syloti nagri',
'syrc' => 'siríac',
'syre' => 'siríac estrangelo',
'syrj' => 'siríac occidental',
'syrn' => 'siríac oriental',
'tagb' => 'tagbanwa',
'tale' => 'tai le',
'talu' => 'nou tai lue',
'taml' => 'tàmil',
'tavt' => 'tai viet',
'telu' => 'telugu',
'teng' => 'tengwar',
'tfng' => 'tifinagh',
'tglg' => 'tagàlog',
'thaa' => 'thaana',
'thai' => 'tailandès',
'tibt' => 'tibetà',
'ugar' => 'ugarític',
'vaii' => 'vai',
'visp' => 'llenguatge visible',
'xpeo' => 'persa antic',
'xsux' => 'cuneïforme sumeri-accadi',
'yiii' => 'yi',
'zinh' => 'heretat',
'zmth' => 'notació matemàtica',
'zsym' => 'símbols',
'zxxx' => 'sense escriptura',
'zyyy' => 'comú',
'zzzz' => 'escriptura desconeguda o no vàlida',
),
'territories' =>
array (
'001' => 'Món',
'002' => 'Àfrica',
'003' => 'Amèrica del Nord',
'005' => 'Amèrica del Sud',
'009' => 'Oceania',
'011' => 'Àfrica Occidental',
'013' => 'Amèrica Central',
'014' => 'Àfrica Oriental',
'015' => 'Àfrica septentrional',
'017' => 'Àfrica Central',
'018' => 'Àfrica meridional',
'019' => 'Amèrica',
'021' => 'Amèrica septentrional',
'029' => 'Carib',
'030' => 'Àsia Oriental',
'034' => 'Àsia meridional',
'035' => 'Àsia Sud-oriental',
'039' => 'Europa meridional',
'053' => 'Austràlia i Nova Zelanda',
'054' => 'Melanèsia',
'057' => 'Regió de la Micronèsia',
'061' => 'Polinèsia',
'062' => 'Àsia Sud-central',
142 => 'Àsia',
143 => 'Àsia Central',
145 => 'Àsia Occidental',
150 => 'Europa',
151 => 'Europa Oriental',
154 => 'Europa septentrional',
155 => 'Europa Occidental',
172 => 'Comunitat d\'Estats Independents',
419 => 'Amèrica Llatina',
'ac' => 'Illa de l\'Ascensió',
'ad' => 'Andorra',
'ae' => 'Unió dels Emirats Àrabs',
'af' => 'Afganistan',
'ag' => 'Antigua i Barbuda',
'ai' => 'Anguilla',
'al' => 'Albània',
'am' => 'Armènia',
'an' => 'Antilles Neerlandeses',
'ao' => 'Angola',
'aq' => 'Antàrtida',
'ar' => 'Argentina',
'as' => 'Samoa Americana',
'at' => 'Àustria',
'au' => 'Austràlia',
'aw' => 'Aruba',
'ax' => 'Illes Åland',
'az' => 'Azerbaidjan',
'ba' => 'Bòsnia i Hercegovina',
'bb' => 'Barbados',
'bd' => 'Bangla Desh',
'be' => 'Bèlgica',
'bf' => 'Burkina Faso',
'bg' => 'Bulgària',
'bh' => 'Bahrain',
'bi' => 'Burundi',
'bj' => 'Benín',
'bl' => 'Saint Barthélemy',
'bm' => 'Bermudes',
'bn' => 'Brunei',
'bo' => 'Bolívia',
'br' => 'Brasil',
'bs' => 'Bahames',
'bt' => 'Bhutan',
'bv' => 'Illa Bouvet',
'bw' => 'Botswana',
'by' => 'Bielorússia',
'bz' => 'Belize',
'ca' => 'Canadà',
'cc' => 'Illes Cocos',
'cd' => 'Congo [República Democràtica del Congo]',
'cf' => 'República Centreafricana',
'cg' => 'Congo [República del Congo]',
'ch' => 'Suïssa',
'ci' => 'Costa d’Ivori',
'ck' => 'Illes Cook',
'cl' => 'Xile',
'cm' => 'Camerun',
'cn' => 'Xina',
'co' => 'Colòmbia',
'cp' => 'Illa Clipperton',
'cr' => 'Costa Rica',
'cs' => 'Sèrbia i Montenegro',
'cu' => 'Cuba',
'cv' => 'Cap Verd',
'cx' => 'Illa Christmas',
'cy' => 'Xipre',
'cz' => 'República Txeca',
'de' => 'Alemanya',
'dg' => 'Diego Garcia',
'dj' => 'Djibouti',
'dk' => 'Dinamarca',
'dm' => 'Dominica',
'do' => 'República Dominicana',
'dz' => 'Algèria',
'ea' => 'Ceuta i Melilla',
'ec' => 'Equador',
'ee' => 'Estònia',
'eg' => 'Egipte',
'eh' => 'Sàhara Occidental',
'er' => 'Eritrea',
'es' => 'Espanya',
'et' => 'Etiòpia',
'eu' => 'Unió Europea',
'fi' => 'Finlàndia',
'fj' => 'Fiji',
'fk' => 'Illes Malvines [Illes Falkland]',
'fm' => 'Micronèsia',
'fo' => 'Illes Fèroe',
'fr' => 'França',
'fx' => 'França metropolitana',
'ga' => 'Gabon',
'gb' => 'Regne Unit',
'gd' => 'Grenada',
'ge' => 'Geòrgia',
'gf' => 'Guaiana Francesa',
'gg' => 'Guernsey',
'gh' => 'Ghana',
'gi' => 'Gibraltar',
'gl' => 'Grenlàndia',
'gm' => 'Gàmbia',
'gn' => 'Guinea',
'gp' => 'Guadeloupe',
'gq' => 'Guinea Equatorial',
'gr' => 'Grècia',
'gs' => 'Illes Geòrgia del Sud i Sandwich del Sud',
'gt' => 'Guatemala',
'gu' => 'Guam',
'gw' => 'Guinea Bissau',
'gy' => 'Guyana',
'hk' => 'Hong Kong',
'hm' => 'Illa Heard i Illes McDonald',
'hn' => 'Hondures',
'hr' => 'Croàcia',
'ht' => 'Haití',
'hu' => 'Hongria',
'ic' => 'Illes Canàries',
'id' => 'Indonèsia',
'ie' => 'Irlanda',
'il' => 'Israel',
'im' => 'Illa de Man',
'in' => 'Índia',
'io' => 'Territori Britànic de l\'Oceà Índic',
'iq' => 'Iraq',
'ir' => 'Iran',
'is' => 'Islàndia',
'it' => 'Itàlia',
'je' => 'Jersey',
'jm' => 'Jamaica',
'jo' => 'Jordània',
'jp' => 'Japó',
'ke' => 'Kenya',
'kg' => 'Kirguizistan',
'kh' => 'Cambodja',
'ki' => 'Kiribati',
'km' => 'Comores',
'kn' => 'Saint Christopher i Nevis',
'kp' => 'Corea del Nord',
'kr' => 'Corea del Sud',
'kw' => 'Kuwait',
'ky' => 'Illes Caiman',
'kz' => 'Kazakhstan',
'la' => 'Laos',
'lb' => 'Líban',
'lc' => 'Saint Lucia',
'li' => 'Liechtenstein',
'lk' => 'Sri Lanka',
'lr' => 'Libèria',
'ls' => 'Lesotho',
'lt' => 'Lituània',
'lu' => 'Luxemburg',
'lv' => 'Letònia',
'ly' => 'Líbia',
'ma' => 'Marroc',
'mc' => 'Mònaco',
'md' => 'Moldàvia',
'me' => 'Montenegro',
'mf' => 'Saint Martin',
'mg' => 'Madagascar',
'mh' => 'Illes Marshall',
'mk' => 'Macedònia [Exrepública Iugoslava de Macedònia]',
'ml' => 'Mali',
'mm' => 'Myanmar [Birmània]',
'mn' => 'Mongòlia',
'mo' => 'Macau',
'mp' => 'Illes Mariannes del Nord',
'mq' => 'Martinica',
'mr' => 'Mauritània',
'ms' => 'Montserrat',
'mt' => 'Malta',
'mu' => 'Maurici',
'mv' => 'Maldives',
'mw' => 'Malawi',
'mx' => 'Mèxic',
'my' => 'Malàisia',
'mz' => 'Moçambic',
'na' => 'Namíbia',
'nc' => 'Nova Caledònia',
'ne' => 'Níger',
'nf' => 'Illa Norfolk',
'ng' => 'Nigèria',
'ni' => 'Nicaragua',
'nl' => 'Països Baixos',
'no' => 'Noruega',
'np' => 'Nepal',
'nr' => 'Nauru',
'nu' => 'Niue',
'nz' => 'Nova Zelanda',
'om' => 'Oman',
'pa' => 'Panamà',
'pe' => 'Perú',
'pf' => 'Polinèsia Francesa',
'pg' => 'Papua Nova Guinea',
'ph' => 'Filipines',
'pk' => 'Pakistan',
'pl' => 'Polònia',
'pm' => 'Saint Pierre i Miquelon',
'pn' => 'Illes Pitcairn',
'pr' => 'Puerto Rico',
'ps' => 'Palestina',
'pt' => 'Portugal',
'pw' => 'Palau',
'py' => 'Paraguai',
'qa' => 'Qatar',
'qo' => 'Territoris allunyats d\'Oceania',
're' => 'Illa de la Reunió',
'ro' => 'Romania',
'rs' => 'Sèrbia',
'ru' => 'Rússia',
'rw' => 'Rwanda',
'sa' => 'Aràbia Saudita',
'sb' => 'Illes Salomó',
'sc' => 'Seychelles',
'sd' => 'Sudan',
'se' => 'Suècia',
'sg' => 'Singapur',
'sh' => 'Saint Helena',
'si' => 'Eslovènia',
'sj' => 'Svalbard i Jan Mayen',
'sk' => 'Eslovàquia',
'sl' => 'Sierra Leone',
'sm' => 'San Marino',
'sn' => 'Senegal',
'so' => 'Somàlia',
'sr' => 'Surinam',
'st' => 'São Tomé i Príncipe',
'sv' => 'El Salvador',
'sy' => 'Síria',
'sz' => 'Swazilàndia',
'ta' => 'Tristão da Cunha',
'tc' => 'Illes Turks i Caicos',
'td' => 'Txad',
'tf' => 'Territoris Francesos del Sud',
'tg' => 'Togo',
'th' => 'Tailàndia',
'tj' => 'Tadjikistan',
'tk' => 'Tokelau',
'tl' => 'Timor Oriental',
'tm' => 'Turkmenistan',
'tn' => 'Tunísia',
'to' => 'Tonga',
'tr' => 'Turquia',
'tt' => 'Trinitat i Tobago',
'tv' => 'Tuvalu',
'tw' => 'Taiwan',
'tz' => 'Tanzània',
'ua' => 'Ucraïna',
'ug' => 'Uganda',
'um' => 'Illes Perifèriques Menors dels EUA',
'us' => 'Estats Units',
'uy' => 'Uruguai',
'uz' => 'Uzbekistan',
'va' => 'Vaticà',
'vc' => 'Saint Vincent i les Grenadines',
've' => 'Veneçuela',
'vg' => 'Illes Verges Britàniques',
'vi' => 'Illes Verges Nord-americanes',
'vn' => 'Vietnam',
'vu' => 'Vanuatu',
'wf' => 'Wallis i Futuna',
'ws' => 'Samoa',
'ye' => 'Iemen',
'yt' => 'Mayotte',
'za' => 'República de Sud-àfrica',
'zm' => 'Zàmbia',
'zw' => 'Zimbabwe',
'zz' => 'Regió desconeguda o no vàlida',
),
'pluralRules' =>
array (
0 => 'n==1',
1 => 'true',
),
);
| bsd-3-clause |
liyuan989/leetcode | Algorithm/ValidParentheses/ValidParentheses.cpp | 1277 | /*
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
*/
#include <string>
#include <vector>
#include <string.h>
#include <stdio.h>
using namespace std;
class Solution
{
public:
bool isValid(const string& s)
{
if (s.empty())
{
return false;
}
int hash[256];
int map[256];
memset(hash, 0, sizeof(hash));
memset(map, 0, sizeof(map));
char left[] = "([{";
char right[] = ")]}";
for (int i = 0; i < 3; ++i)
{
hash[left[i]] = 1;
map[right[i]] = left[i];
}
vector<char> stack;
for (int i = 0; i < s.size(); ++i)
{
if (hash[s[i]] == 1)
{
stack.push_back(s[i]);
}
else
{
if (stack.empty() || stack.back() != map[s[i]])
{
return false;
}
stack.pop_back();
}
}
if (stack.empty())
{
return true;
}
return false;
}
};
| bsd-3-clause |
zpz/stats.go | random.go | 388 | package stats
// TODO: follow the example of the 'random' standard library
// of C++11 to achieve control and reproducibility of RNG.
import (
"math/rand"
)
type RandomNumberGenerator interface {
Seed(int64)
Next() float64
}
// TODO: temporary solution
type RNG struct{}
func (r *RNG) Seed(seed int64) {
rand.Seed(seed)
}
func (r *RNG) Next() float64 {
return rand.Float64()
}
| bsd-3-clause |
jaimeirazabal1/intercambio_de_perfiles | default/app/models/carpeta.php | 1055 | <?php
class Carpeta extends ActiveRecord{
public function nueva_carpeta($nombre_carpeta){
$carpeta_nueva = new Carpeta();
$carpeta_nueva->nombre = $nombre_carpeta;
$carpeta_nueva->usuario_id = Auth::get("id");
return $carpeta_nueva->save();
}
public function get_carpetas_by_user_id($id){
$query = "SELECT carpeta.id as carpeta_id,
carpeta.nombre as carpeta_nombre,
carpeta.created as carpeta_created,
usuario.id as usuario_id,
usuario.login as usuario_login,
carpeta_data.created as carpeta_data_created,
data.*
from carpeta
INNER JOIN usuario on usuario.id = carpeta.usuario_id
INNER JOIN carpeta_data on carpeta_data.carpeta_id = carpeta.id
INNER JOIN data on carpeta_data.data_id = `data`.`id`
WHERE carpeta.usuario_id = '$id'
order by carpeta_nombre asc";
$results = $this->find_all_by_sql($query);
return $results;
}
public function get_nombre_carpetas_by_user_id($id){
return $this->find("conditions: usuario_id = '".$id."' ");
}
}
?> | bsd-3-clause |
kjc88/packetfu | test/test_octets.rb | 754 | #!/usr/bin/env ruby
require 'test/unit'
$:.unshift File.join(File.expand_path(File.dirname(__FILE__)), "..", "lib")
require 'packetfu'
class OctetsTest < Test::Unit::TestCase
include PacketFu
def test_octets_read
o = Octets.new
o.read("\x04\x03\x02\x01")
assert_equal("4.3.2.1", o.to_x)
end
def test_octets_read_quad
o = Octets.new
o.read_quad("1.2.3.4")
assert_equal("1.2.3.4", o.to_x)
assert_equal("\x01\x02\x03\x04", o.to_s)
assert_equal(0x01020304, o.to_i)
end
def test_octets_single_octet
o = Octets.new
o.read("ABCD")
assert_equal(o.o1, 0x41)
assert_equal(o.o2, 0x42)
assert_equal(o.o3, 0x43)
assert_equal(o.o4, 0x44)
end
end
# vim: nowrap sw=2 sts=0 ts=2 ff=unix ft=ruby
| bsd-3-clause |
livingdreams/kidcrossing | views/user/childdashboard.php | 7434 | <?php
use yii\helpers\Html;
use yii\grid\GridView;
//use yii\helpers\Url;
//use yii\bootstrap\Modal;
use yii\widgets\ActiveForm;
use yii\widgets\ListView;
use yii\widgets\Pjax;
use app\models\Mood;
/* @var $this yii\web\View */
/* @var $model app\models\User */
/* @var $model app\models\Profile */
/* @var $form ActiveForm */
//var_dump($model->wishlists); die();
$this->title = 'Child Dashboard';
$this->params['breadcrumbs'][] = $this->title;
?>
<!-- Content Header (Page header) -->
<?php if(Yii::$app->user->identity->level != 0): ?>
<?=
$this->render('_mood', [
'model' => $moods,
]);
?>
<div class="background-white top-fixed-margin bordered-grey padding-large">
<?php
$count = ((int)Yii::$app->find->setting('number_of_moods_a_day') - Mood::find()->where(['user_id' => Yii::$app->user->getId(), 'date' => date("Y-m-d")])->count());
$count == 1 ? $entry_label = "Entry" : $entry_label = "Entries";
Pjax::begin(['id' => 'moodbox', 'class' => 'moodbox'])
?>
<?php if ($count != (int)Yii::$app->find->setting('number_of_moods_a_day')) { ?>
<?=
GridView::widget([
'dataProvider' => $moodsProvider,
'columns' => [
'mood',
],
'caption' => "<span class='label label-danger font-small'>" . $count . "</span>" . " " . "<span class='font-small color-bule'>" . $entry_label . " remaining today" . "</span>",
'options' => ['class' => 'moodbox-table'],
'emptyText' => '',
]);
?>
<?php } ?>
<?php Pjax::end() ?>
</div>
<?php endif; ?>
<div class="row">
<!-- column moods and parent profiles -->
<div class="col-md-12">
<div class="row">
<!-- display mode names -->
<div class="fundInfoContainer" data-fundId="1" style="display: none">
<p class="fonts-bold">You are Sad Today <a href="#" class="btn btn-success">Change now</a></p>
</div>
<div class="fundInfoContainer" data-fundId="2" style="display: none">
<p class="fonts-bold">You are Excited Today <a href="#" class="btn btn-success">Change now</a></p>
</div>
<div class="fundInfoContainer" data-fundId="3" style="display: none">
<p class="fonts-bold">You are Bored Today <a href="#" class="btn btn-success">Change now</a></p>
</div>
<div class="fundInfoContainer" data-fundId="4" style="display: none">
<p class="fonts-bold">You are Happy Today <a href="#" class="btn btn-success">Change now</a></p>
</div>
<div class="fundInfoContainer" data-fundId="5" style="display: none">
<p class="fonts-bold">You are Angry Today <a href="#" class="btn btn-success">Change now</a></p>
</div>
<!-- display mode names ends -->
<!--parent account panels -->
<!-- single user -->
<?=
ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_listparent',
'summary' => '',
]);
?>
<!--single user ends -->
<!--parent account panels -->
</div>
</div>
<div class="col-md-6">
<?php
foreach (array_reverse($model->wishlists) as $k=>$wishlist) {
if ($k > 0)
break;
?>
<!-- wishlists -->
<div class="col-md-12 semiwidget-white bordered-white bordered-grey">
<h4 class="heading-custom-one padding-bottom-sm color-blue text-center color-orange fonts-md margin-bottom-lg">Your Latest Wish</h4>
<div class="row">
<div class="col-xs-4">
<?= Html::img($wishlist->emoticon, ['alt' => $wishlist->emoticon ,'class' => 'thumbnail center-blocked top-fixed-margin']) ?>
</div>
<div class="col-xs-8 card-grey">
<h4 class="color-blue fonts-bold"><?= $wishlist->title ?></h4>
<p class="color-black">From <?= $wishlist->getAssignedFullname($wishlist->assigned_to) ?></p>
<?= Yii::$app->user->identity->level ==3 ? Html::a('Add new <i class="fa fa-plus"></i>', ['wishlist/index'], ['class' => 'btn btn-danger']) : ''; ?>
</div>
</div>
</div><!-- wishlists semi-widget ends -->
<?php } ?>
<!-- photo box -->
<!-- photos semi-widget -->
<div class="col-md-12 semiwidget-white bordered-grey top-fixed-margin">
<h4 class="heading-custom-one padding-bottom-sm color-blue text-center color-orange fonts-md margin-bottom-lg">My Photos</h4>
<?php if ($model->photos): ?>
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1" class=""></li>
<li data-target="#carousel-example-generic" data-slide-to="2" class=""></li>
</ol>
<!-- Wrapper for slides -->
<div class='carousel-inner setted-height'>
<?php
foreach (array_reverse($model->photos) as $k => $photo):
if ($k > 5)
break;
?>
<div class="item <?= $k == 0 ? 'active' : '' ?>">
<?= Html::img($photo->src, ['alt' => $photo->filename]) ?>
</div>
<?php endforeach; ?>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
<?php else: ?>
<div class="empty">No Photos Found</div>
<?php endif; ?>
</div><!-- photos semi-widget ends -->
<!-- photobox ends -->
</div>
<div class="col-md-6">
<div class="col-md-12 semiwidget-white bordered-white bordered-grey">
<h4 class="heading-custom-one padding-bottom-sm color-blue text-center color-orange fonts-md margin-bottom-lg">Recent Journal Entries</h4>
<?=
ListView::widget([
'dataProvider' => $journalProvider,
'itemView' => '_listjournal',
'summary' => '',
]);
?>
</div>
</div>
<!-- column moods and parent profiles -->
</div>
<!-- /.widget-user1 -->
| bsd-3-clause |
NCIP/cagrid-portal | cagrid-portal/portlets/src/java/gov/nih/nci/cagrid/portal/portlet/query/cql/DefaultCQLQueryInstanceExecutor.java | 4739 | /**
*============================================================================
* The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC,
* and Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-portal/LICENSE.txt for details.
*============================================================================
**/
/**
*
*/
package gov.nih.nci.cagrid.portal.portlet.query.cql;
import gov.nih.nci.cagrid.portal.authn.EncryptionService;
import gov.nih.nci.cagrid.portal.domain.dataservice.CQLQueryInstance;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.gsi.GlobusCredential;
import org.springframework.beans.factory.InitializingBean;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
/**
* @author <a href="mailto:joshua.phillips@semanticbits.com">Joshua Phillips</a>
*/
public class DefaultCQLQueryInstanceExecutor implements
CQLQueryInstanceExecutor, InitializingBean {
private static final Log logger = LogFactory.getLog(DefaultCQLQueryInstanceExecutor.class);
private EncryptionService encryptionService;
private ExecutorService executorService;
private CQLQueryInstance instance;
private CQLQueryInstanceListener listener;
private Future future;
private long timeout = 60000;
private Date endTime;
/**
*
*/
public DefaultCQLQueryInstanceExecutor() {
}
public boolean cancel() {
boolean cancelled = doCancel();
listener.onCancelled(instance, cancelled);
return cancelled;
}
public boolean timeout() {
boolean cancelled = doCancel();
listener.onTimeout(instance, cancelled);
return cancelled;
}
private boolean doCancel() {
if (future == null) {
throw new IllegalStateException("query has not been started");
}
return future.cancel(true);
}
public void setQueryInstance(CQLQueryInstance instance) {
this.instance = instance;
}
public void setCqlQueryInstanceListener(CQLQueryInstanceListener listener) {
this.listener = listener;
}
public void start() {
GlobusCredential cred = null;
if (instance.getPortalUser() != null) {
String proxyStr = instance.getPortalUser().getGridCredential();
proxyStr = getEncryptionService().decrypt(proxyStr);
if (proxyStr != null) {
try {
cred = new GlobusCredential(new ByteArrayInputStream(
proxyStr.getBytes()));
} catch (Exception ex) {
logger.warn("Error instantiating GlobusCredential: "
+ ex.getMessage(), ex);
}
}
}
CQLQueryTask task = new CQLQueryTask(instance, listener, cred);
listener.onSheduled(instance);
future = getExecutorService().submit(task);
setEndTime(new Date(new Date().getTime() + getTimeout()));
}
public ExecutorService getExecutorService() {
return executorService;
}
public void setExecutorService(ExecutorService executorService) {
this.executorService = executorService;
}
public void afterPropertiesSet() throws Exception {
if (getExecutorService() == null) {
throw new IllegalStateException(
"The executorService property is required.");
}
}
public CQLQueryInstance getQueryInstance() {
return instance;
}
public CQLQueryInstanceListener getCqlQueryInstanceListener() {
return listener;
}
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
private class TimeoutThread extends Thread {
public void run() {
while (new Date().before(getEndTime())) {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
break;
}
}
timeout();
}
}
public EncryptionService getEncryptionService() {
return encryptionService;
}
public void setEncryptionService(EncryptionService encryptionService) {
this.encryptionService = encryptionService;
}
}
| bsd-3-clause |
endlessm/chromium-browser | third_party/webrtc/modules/audio_device/android/audio_track_jni.cc | 9918 | /*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/audio_device/android/audio_track_jni.h"
#include <utility>
#include "modules/audio_device/android/audio_manager.h"
#include "rtc_base/arraysize.h"
#include "rtc_base/checks.h"
#include "rtc_base/format_macros.h"
#include "rtc_base/logging.h"
#include "rtc_base/platform_thread.h"
#include "system_wrappers/include/field_trial.h"
namespace webrtc {
// AudioTrackJni::JavaAudioTrack implementation.
AudioTrackJni::JavaAudioTrack::JavaAudioTrack(
NativeRegistration* native_reg,
std::unique_ptr<GlobalRef> audio_track)
: audio_track_(std::move(audio_track)),
init_playout_(native_reg->GetMethodId("initPlayout", "(IID)Z")),
start_playout_(native_reg->GetMethodId("startPlayout", "()Z")),
stop_playout_(native_reg->GetMethodId("stopPlayout", "()Z")),
set_stream_volume_(native_reg->GetMethodId("setStreamVolume", "(I)Z")),
get_stream_max_volume_(
native_reg->GetMethodId("getStreamMaxVolume", "()I")),
get_stream_volume_(native_reg->GetMethodId("getStreamVolume", "()I")) {}
AudioTrackJni::JavaAudioTrack::~JavaAudioTrack() {}
bool AudioTrackJni::JavaAudioTrack::InitPlayout(int sample_rate, int channels) {
double buffer_size_factor =
strtod(webrtc::field_trial::FindFullName(
"WebRTC-AudioDevicePlayoutBufferSizeFactor")
.c_str(),
nullptr);
if (buffer_size_factor == 0)
buffer_size_factor = 1.0;
return audio_track_->CallBooleanMethod(init_playout_, sample_rate, channels,
buffer_size_factor);
}
bool AudioTrackJni::JavaAudioTrack::StartPlayout() {
return audio_track_->CallBooleanMethod(start_playout_);
}
bool AudioTrackJni::JavaAudioTrack::StopPlayout() {
return audio_track_->CallBooleanMethod(stop_playout_);
}
bool AudioTrackJni::JavaAudioTrack::SetStreamVolume(int volume) {
return audio_track_->CallBooleanMethod(set_stream_volume_, volume);
}
int AudioTrackJni::JavaAudioTrack::GetStreamMaxVolume() {
return audio_track_->CallIntMethod(get_stream_max_volume_);
}
int AudioTrackJni::JavaAudioTrack::GetStreamVolume() {
return audio_track_->CallIntMethod(get_stream_volume_);
}
// TODO(henrika): possible extend usage of AudioManager and add it as member.
AudioTrackJni::AudioTrackJni(AudioManager* audio_manager)
: j_environment_(JVM::GetInstance()->environment()),
audio_parameters_(audio_manager->GetPlayoutAudioParameters()),
direct_buffer_address_(nullptr),
direct_buffer_capacity_in_bytes_(0),
frames_per_buffer_(0),
initialized_(false),
playing_(false),
audio_device_buffer_(nullptr) {
RTC_LOG(INFO) << "ctor";
RTC_DCHECK(audio_parameters_.is_valid());
RTC_CHECK(j_environment_);
JNINativeMethod native_methods[] = {
{"nativeCacheDirectBufferAddress", "(Ljava/nio/ByteBuffer;J)V",
reinterpret_cast<void*>(
&webrtc::AudioTrackJni::CacheDirectBufferAddress)},
{"nativeGetPlayoutData", "(IJ)V",
reinterpret_cast<void*>(&webrtc::AudioTrackJni::GetPlayoutData)}};
j_native_registration_ = j_environment_->RegisterNatives(
"org/webrtc/voiceengine/WebRtcAudioTrack", native_methods,
arraysize(native_methods));
j_audio_track_.reset(
new JavaAudioTrack(j_native_registration_.get(),
j_native_registration_->NewObject(
"<init>", "(J)V", PointerTojlong(this))));
// Detach from this thread since we want to use the checker to verify calls
// from the Java based audio thread.
thread_checker_java_.Detach();
}
AudioTrackJni::~AudioTrackJni() {
RTC_LOG(INFO) << "dtor";
RTC_DCHECK(thread_checker_.IsCurrent());
Terminate();
}
int32_t AudioTrackJni::Init() {
RTC_LOG(INFO) << "Init";
RTC_DCHECK(thread_checker_.IsCurrent());
return 0;
}
int32_t AudioTrackJni::Terminate() {
RTC_LOG(INFO) << "Terminate";
RTC_DCHECK(thread_checker_.IsCurrent());
StopPlayout();
return 0;
}
int32_t AudioTrackJni::InitPlayout() {
RTC_LOG(INFO) << "InitPlayout";
RTC_DCHECK(thread_checker_.IsCurrent());
RTC_DCHECK(!initialized_);
RTC_DCHECK(!playing_);
if (!j_audio_track_->InitPlayout(audio_parameters_.sample_rate(),
audio_parameters_.channels())) {
RTC_LOG(LS_ERROR) << "InitPlayout failed";
return -1;
}
initialized_ = true;
return 0;
}
int32_t AudioTrackJni::StartPlayout() {
RTC_LOG(INFO) << "StartPlayout";
RTC_DCHECK(thread_checker_.IsCurrent());
RTC_DCHECK(!playing_);
if (!initialized_) {
RTC_DLOG(LS_WARNING)
<< "Playout can not start since InitPlayout must succeed first";
return 0;
}
if (!j_audio_track_->StartPlayout()) {
RTC_LOG(LS_ERROR) << "StartPlayout failed";
return -1;
}
playing_ = true;
return 0;
}
int32_t AudioTrackJni::StopPlayout() {
RTC_LOG(INFO) << "StopPlayout";
RTC_DCHECK(thread_checker_.IsCurrent());
if (!initialized_ || !playing_) {
return 0;
}
if (!j_audio_track_->StopPlayout()) {
RTC_LOG(LS_ERROR) << "StopPlayout failed";
return -1;
}
// If we don't detach here, we will hit a RTC_DCHECK in OnDataIsRecorded()
// next time StartRecording() is called since it will create a new Java
// thread.
thread_checker_java_.Detach();
initialized_ = false;
playing_ = false;
direct_buffer_address_ = nullptr;
return 0;
}
int AudioTrackJni::SpeakerVolumeIsAvailable(bool& available) {
available = true;
return 0;
}
int AudioTrackJni::SetSpeakerVolume(uint32_t volume) {
RTC_LOG(INFO) << "SetSpeakerVolume(" << volume << ")";
RTC_DCHECK(thread_checker_.IsCurrent());
return j_audio_track_->SetStreamVolume(volume) ? 0 : -1;
}
int AudioTrackJni::MaxSpeakerVolume(uint32_t& max_volume) const {
RTC_DCHECK(thread_checker_.IsCurrent());
max_volume = j_audio_track_->GetStreamMaxVolume();
return 0;
}
int AudioTrackJni::MinSpeakerVolume(uint32_t& min_volume) const {
RTC_DCHECK(thread_checker_.IsCurrent());
min_volume = 0;
return 0;
}
int AudioTrackJni::SpeakerVolume(uint32_t& volume) const {
RTC_DCHECK(thread_checker_.IsCurrent());
volume = j_audio_track_->GetStreamVolume();
RTC_LOG(INFO) << "SpeakerVolume: " << volume;
return 0;
}
// TODO(henrika): possibly add stereo support.
void AudioTrackJni::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) {
RTC_LOG(INFO) << "AttachAudioBuffer";
RTC_DCHECK(thread_checker_.IsCurrent());
audio_device_buffer_ = audioBuffer;
const int sample_rate_hz = audio_parameters_.sample_rate();
RTC_LOG(INFO) << "SetPlayoutSampleRate(" << sample_rate_hz << ")";
audio_device_buffer_->SetPlayoutSampleRate(sample_rate_hz);
const size_t channels = audio_parameters_.channels();
RTC_LOG(INFO) << "SetPlayoutChannels(" << channels << ")";
audio_device_buffer_->SetPlayoutChannels(channels);
}
JNI_FUNCTION_ALIGN
void JNICALL AudioTrackJni::CacheDirectBufferAddress(JNIEnv* env,
jobject obj,
jobject byte_buffer,
jlong nativeAudioTrack) {
webrtc::AudioTrackJni* this_object =
reinterpret_cast<webrtc::AudioTrackJni*>(nativeAudioTrack);
this_object->OnCacheDirectBufferAddress(env, byte_buffer);
}
void AudioTrackJni::OnCacheDirectBufferAddress(JNIEnv* env,
jobject byte_buffer) {
RTC_LOG(INFO) << "OnCacheDirectBufferAddress";
RTC_DCHECK(thread_checker_.IsCurrent());
RTC_DCHECK(!direct_buffer_address_);
direct_buffer_address_ = env->GetDirectBufferAddress(byte_buffer);
jlong capacity = env->GetDirectBufferCapacity(byte_buffer);
RTC_LOG(INFO) << "direct buffer capacity: " << capacity;
direct_buffer_capacity_in_bytes_ = static_cast<size_t>(capacity);
const size_t bytes_per_frame = audio_parameters_.channels() * sizeof(int16_t);
frames_per_buffer_ = direct_buffer_capacity_in_bytes_ / bytes_per_frame;
RTC_LOG(INFO) << "frames_per_buffer: " << frames_per_buffer_;
}
JNI_FUNCTION_ALIGN
void JNICALL AudioTrackJni::GetPlayoutData(JNIEnv* env,
jobject obj,
jint length,
jlong nativeAudioTrack) {
webrtc::AudioTrackJni* this_object =
reinterpret_cast<webrtc::AudioTrackJni*>(nativeAudioTrack);
this_object->OnGetPlayoutData(static_cast<size_t>(length));
}
// This method is called on a high-priority thread from Java. The name of
// the thread is 'AudioRecordTrack'.
void AudioTrackJni::OnGetPlayoutData(size_t length) {
RTC_DCHECK(thread_checker_java_.IsCurrent());
const size_t bytes_per_frame = audio_parameters_.channels() * sizeof(int16_t);
RTC_DCHECK_EQ(frames_per_buffer_, length / bytes_per_frame);
if (!audio_device_buffer_) {
RTC_LOG(LS_ERROR) << "AttachAudioBuffer has not been called";
return;
}
// Pull decoded data (in 16-bit PCM format) from jitter buffer.
int samples = audio_device_buffer_->RequestPlayoutData(frames_per_buffer_);
if (samples <= 0) {
RTC_LOG(LS_ERROR) << "AudioDeviceBuffer::RequestPlayoutData failed";
return;
}
RTC_DCHECK_EQ(samples, frames_per_buffer_);
// Copy decoded data into common byte buffer to ensure that it can be
// written to the Java based audio track.
samples = audio_device_buffer_->GetPlayoutData(direct_buffer_address_);
RTC_DCHECK_EQ(length, bytes_per_frame * samples);
}
} // namespace webrtc
| bsd-3-clause |
CartoDB/Windshaft-cartodb | test/acceptance/widgets/ported/aggregation-test.js | 14099 | 'use strict';
require('../../../support/test-helper');
var assert = require('../../../support/assert');
var TestClient = require('../../../support/test-client');
describe('widgets', function () {
describe('aggregations', function () {
afterEach(function (done) {
if (this.testClient) {
this.testClient.drain(done);
} else {
done();
}
});
var aggregationMapConfig = {
version: '1.5.0',
layers: [
{
type: 'mapnik',
options: {
sql: 'select * from populated_places_simple_reduced',
cartocss: '#layer0 { marker-fill: red; marker-width: 10; }',
cartocss_version: '2.0.1',
widgets: {
adm0name: {
type: 'aggregation',
options: {
column: 'adm0name',
aggregation: 'count'
}
}
}
}
}
]
};
it('can be fetched from a valid aggregation', function (done) {
this.testClient = new TestClient(aggregationMapConfig);
this.testClient.getWidget('adm0name', { own_filter: 0 }, function (err, res, aggregation) {
assert.ok(!err, err);
assert.ok(aggregation);
assert.strictEqual(aggregation.type, 'aggregation');
assert.strictEqual(aggregation.categories.length, 6);
assert.deepStrictEqual(
aggregation.categories[0],
{ category: 'United States of America', value: 769, agg: false }
);
assert.deepStrictEqual(
aggregation.categories[aggregation.categories.length - 1],
{ category: 'Other', value: 4914, agg: true }
);
done();
});
});
var filteredCategoriesScenarios = [
{ accept: ['Canada'], values: [256] },
{ accept: ['Canada', 'Spain', 'Chile', 'Thailand'], values: [256, 49, 83, 79] },
{ accept: ['Canada', 'Spain', 'Chile', 'Thailand', 'Japan'], values: [256, 49, 83, 79, 69] },
{ accept: ['Canada', 'Spain', 'Chile', 'Thailand', 'Japan', 'France'], values: [256, 49, 83, 79, 69, 71] },
{
accept: ['United States of America', 'Canada', 'Spain', 'Chile', 'Thailand', 'Japan', 'France'],
values: [769, 256, 49, 83, 79, 69, 71]
}
];
filteredCategoriesScenarios.forEach(function (scenario) {
it('can filter some categories: ' + scenario.accept.join(', '), function (done) {
this.testClient = new TestClient(aggregationMapConfig);
var adm0nameFilter = {
adm0name: {
accept: scenario.accept
}
};
var params = {
own_filter: 1,
filters: {
layers: [
adm0nameFilter
]
}
};
this.testClient.getWidget('adm0name', params, function (err, res, aggregation) {
assert.ok(!err, err);
assert.ok(aggregation);
assert.strictEqual(aggregation.type, 'aggregation');
assert.strictEqual(aggregation.categories.length, scenario.accept.length);
var categoriesByCategory = aggregation.categories.reduce(function (byCategory, row) {
byCategory[row.category] = row;
return byCategory;
}, {});
var scenarioByCategory = scenario.accept.reduce(function (byCategory, category, index) {
byCategory[category] = { category: category, value: scenario.values[index], agg: false };
return byCategory;
}, {});
Object.keys(categoriesByCategory).forEach(function (category) {
assert.deepStrictEqual(categoriesByCategory[category], scenarioByCategory[category]);
});
done();
});
});
});
var aggregationSumMapConfig = {
version: '1.5.0',
layers: [
{
type: 'mapnik',
options: {
sql: 'select * from populated_places_simple_reduced',
cartocss: '#layer0 { marker-fill: red; marker-width: 10; }',
cartocss_version: '2.0.1',
widgets: {
adm0name: {
type: 'aggregation',
options: {
column: 'adm0name',
aggregation: 'sum',
aggregationColumn: 'pop_max'
}
}
}
}
}
]
};
it('can sum other column for aggregation value', function (done) {
this.testClient = new TestClient(aggregationSumMapConfig);
this.testClient.getWidget('adm0name', { own_filter: 0 }, function (err, res, aggregation) {
assert.ok(!err, err);
assert.ok(aggregation);
assert.strictEqual(aggregation.type, 'aggregation');
assert.strictEqual(aggregation.categories.length, 6);
assert.deepStrictEqual(
aggregation.categories[0],
{ category: 'China', value: 374537585, agg: false }
);
assert.deepStrictEqual(
aggregation.categories[aggregation.categories.length - 1],
{ category: 'Other', value: 1412626289, agg: true }
);
done();
});
});
var filteredCategoriesSumScenarios = [
{ accept: [], values: [] },
{ accept: ['Canada'], values: [23955084] },
{ accept: ['Canada', 'Spain', 'Chile', 'Thailand'], values: [23955084, 22902774, 14356263, 17492483] },
{
accept: ['United States of America', 'Canada', 'Spain', 'Chile', 'Thailand', 'Japan', 'France'],
values: [239098994, 23955084, 22902774, 14356263, 17492483, 93577001, 25473876]
}
];
filteredCategoriesSumScenarios.forEach(function (scenario) {
it('can filter some categories with sum aggregation: ' + scenario.accept.join(', '), function (done) {
this.testClient = new TestClient(aggregationSumMapConfig);
var adm0nameFilter = {
adm0name: {
accept: scenario.accept
}
};
var params = {
own_filter: 1,
filters: {
layers: [
adm0nameFilter
]
}
};
this.testClient.getWidget('adm0name', params, function (err, res, aggregation) {
assert.ok(!err, err);
assert.ok(aggregation);
assert.strictEqual(aggregation.type, 'aggregation');
assert.strictEqual(aggregation.categories.length, scenario.accept.length);
var categoriesByCategory = aggregation.categories.reduce(function (byCategory, row) {
byCategory[row.category] = row;
return byCategory;
}, {});
var scenarioByCategory = scenario.accept.reduce(function (byCategory, category, index) {
byCategory[category] = { category: category, value: scenario.values[index], agg: false };
return byCategory;
}, {});
Object.keys(categoriesByCategory).forEach(function (category) {
assert.deepStrictEqual(categoriesByCategory[category], scenarioByCategory[category]);
});
done();
});
});
});
var numericAggregationMapConfig = {
version: '1.5.0',
layers: [
{
type: 'mapnik',
options: {
sql: 'select * from populated_places_simple_reduced',
cartocss: '#layer0 { marker-fill: red; marker-width: 10; }',
cartocss_version: '2.3.0',
widgets: {
scalerank: {
type: 'aggregation',
options: {
column: 'scalerank',
aggregation: 'count'
}
}
}
}
}
]
};
['1', 1].forEach(function (filterValue) {
it('can filter numeric categories: ' + (typeof filterValue), function (done) {
this.testClient = new TestClient(numericAggregationMapConfig);
var scalerankFilter = {
scalerank: {
accept: [filterValue]
}
};
var params = {
own_filter: 1,
filters: {
layers: [scalerankFilter]
}
};
this.testClient.getWidget('scalerank', params, function (err, res, aggregation) {
assert.ok(!err, err);
assert.ok(aggregation);
assert.strictEqual(aggregation.type, 'aggregation');
assert.strictEqual(aggregation.categories.length, 1);
assert.deepStrictEqual(aggregation.categories[0], { category: 1, value: 179, agg: false });
done();
});
});
});
describe('search', function () {
afterEach(function (done) {
if (this.testClient) {
this.testClient.drain(done);
} else {
done();
}
});
['1', 1].forEach(function (userQuery) {
it('can search numeric categories: ' + (typeof userQuery), function (done) {
this.testClient = new TestClient(numericAggregationMapConfig);
var scalerankFilter = {
scalerank: {
accept: [userQuery]
}
};
var params = {
own_filter: 0,
filters: {
layers: [scalerankFilter]
}
};
this.testClient.widgetSearch('scalerank', userQuery, params, function (err, res, searchResult) {
assert.ok(!err, err);
assert.ok(searchResult);
assert.strictEqual(searchResult.type, 'aggregation');
assert.strictEqual(searchResult.categories.length, 2);
assert.deepStrictEqual(
searchResult.categories,
[{ category: 10, value: 515 }, { category: 1, value: 179 }]
);
done();
});
});
});
var adm0name = 'Argentina';
[adm0name, adm0name.toLowerCase(), adm0name.toUpperCase()].forEach(function (userQuery) {
it('should search with case insensitive: ' + userQuery, function (done) {
this.testClient = new TestClient(aggregationMapConfig);
this.testClient.widgetSearch('adm0name', userQuery, function (err, res, searchResult) {
assert.ok(!err, err);
assert.ok(searchResult);
assert.strictEqual(searchResult.type, 'aggregation');
assert.strictEqual(searchResult.categories.length, 1);
assert.deepStrictEqual(
searchResult.categories,
[{ category: 'Argentina', value: 159 }]
);
done();
});
});
});
[adm0name].forEach(function (userQuery) {
it('should search with sum aggregation: ' + userQuery, function (done) {
this.testClient = new TestClient(aggregationSumMapConfig);
this.testClient.widgetSearch('adm0name', userQuery, function (err, res, searchResult) {
assert.ok(!err, err);
assert.ok(searchResult);
assert.strictEqual(searchResult.type, 'aggregation');
assert.strictEqual(searchResult.categories.length, 1);
assert.deepStrictEqual(
searchResult.categories,
[{ category: 'Argentina', value: 28015640 }]
);
done();
});
});
});
});
});
});
| bsd-3-clause |
KennethPierce/pylearnk | pylearn2/datasets/tests/test_preprocessing.py | 7363 | """
Unit tests for ./preprocessing.py
"""
import numpy as np
from theano import config
import theano
from pylearn2.utils import as_floatX
from pylearn2.datasets import dense_design_matrix
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
from pylearn2.datasets.preprocessing import (GlobalContrastNormalization,
ExtractGridPatches,
ReassembleGridPatches,
LeCunLCN,
RGB_YUV,
ZCA)
class testGlobalContrastNormalization:
"""Tests for the GlobalContrastNormalization class """
def test_zero_vector(self):
""" Test that passing in the zero vector does not result in
a divide by 0 """
dataset = DenseDesignMatrix(X=as_floatX(np.zeros((1, 1))))
#the settings of subtract_mean and use_norm are not relevant to
#the test
#std_bias = 0.0 is the only value for which there should be a risk
#of failure occurring
preprocessor = GlobalContrastNormalization(subtract_mean=True,
sqrt_bias=0.0,
use_std=True)
dataset.apply_preprocessor(preprocessor)
result = dataset.get_design_matrix()
assert not np.any(np.isnan(result))
assert not np.any(np.isinf(result))
def test_unit_norm(self):
""" Test that using std_bias = 0.0 and use_norm = True
results in vectors having unit norm """
tol = 1e-5
num_examples = 5
num_features = 10
rng = np.random.RandomState([1, 2, 3])
X = as_floatX(rng.randn(num_examples, num_features))
dataset = DenseDesignMatrix(X=X)
#the setting of subtract_mean is not relevant to the test
#the test only applies when std_bias = 0.0 and use_std = False
preprocessor = GlobalContrastNormalization(subtract_mean=False,
sqrt_bias=0.0,
use_std=False)
dataset.apply_preprocessor(preprocessor)
result = dataset.get_design_matrix()
norms = np.sqrt(np.square(result).sum(axis=1))
max_norm_error = np.abs(norms-1.).max()
tol = 3e-5
assert max_norm_error < tol
def test_extract_reassemble():
""" Tests that ExtractGridPatches and ReassembleGridPatches are
inverse of each other """
rng = np.random.RandomState([1, 3, 7])
topo = rng.randn(4, 3*5, 3*7, 2)
dataset = DenseDesignMatrix(topo_view=topo)
patch_shape = (3, 7)
extractor = ExtractGridPatches(patch_shape, patch_shape)
reassemblor = ReassembleGridPatches(patch_shape=patch_shape,
orig_shape=topo.shape[1:3])
dataset.apply_preprocessor(extractor)
dataset.apply_preprocessor(reassemblor)
new_topo = dataset.get_topological_view()
assert new_topo.shape == topo.shape
if not np.all(new_topo == topo):
assert False
class testLeCunLCN:
"""
Test LeCunLCN
"""
def test_random_image(self):
"""
Test on a random image if the per-processor loads and works without
anyerror and doesn't result in any nan or inf values
"""
rng = np.random.RandomState([1, 2, 3])
X = as_floatX(rng.randn(5, 32*32*3))
axes = ['b', 0, 1, 'c']
view_converter = dense_design_matrix.DefaultViewConverter((32, 32, 3),
axes)
dataset = DenseDesignMatrix(X=X, view_converter=view_converter)
dataset.axes = axes
preprocessor = LeCunLCN(img_shape=[32, 32])
dataset.apply_preprocessor(preprocessor)
result = dataset.get_design_matrix()
assert not np.any(np.isnan(result))
assert not np.any(np.isinf(result))
def test_zero_image(self):
"""
Test on zero-value image if cause any division by zero
"""
X = as_floatX(np.zeros((5, 32*32*3)))
axes = ['b', 0, 1, 'c']
view_converter = dense_design_matrix.DefaultViewConverter((32, 32, 3),
axes)
dataset = DenseDesignMatrix(X=X, view_converter=view_converter)
dataset.axes = axes
preprocessor = LeCunLCN(img_shape=[32, 32])
dataset.apply_preprocessor(preprocessor)
result = dataset.get_design_matrix()
assert not np.any(np.isnan(result))
assert not np.any(np.isinf(result))
def test_channel(self):
"""
Test if works fine withe different number of channel as argument
"""
rng = np.random.RandomState([1, 2, 3])
X = as_floatX(rng.randn(5, 32*32*3))
axes = ['b', 0, 1, 'c']
view_converter = dense_design_matrix.DefaultViewConverter((32, 32, 3),
axes)
dataset = DenseDesignMatrix(X=X, view_converter=view_converter)
dataset.axes = axes
preprocessor = LeCunLCN(img_shape=[32, 32], channels=[1, 2])
dataset.apply_preprocessor(preprocessor)
result = dataset.get_design_matrix()
assert not np.any(np.isnan(result))
assert not np.any(np.isinf(result))
def test_rgb_yuv():
"""
Test on a random image if the per-processor loads and works without
anyerror and doesn't result in any nan or inf values
"""
rng = np.random.RandomState([1, 2, 3])
X = as_floatX(rng.randn(5, 32*32*3))
axes = ['b', 0, 1, 'c']
view_converter = dense_design_matrix.DefaultViewConverter((32, 32, 3),
axes)
dataset = DenseDesignMatrix(X=X, view_converter=view_converter)
dataset.axes = axes
preprocessor = RGB_YUV()
dataset.apply_preprocessor(preprocessor)
result = dataset.get_design_matrix()
assert not np.any(np.isnan(result))
assert not np.any(np.isinf(result))
def test_zca():
"""
Confirm that ZCA.inv_P_ is the correct inverse of ZCA.P_.
There's a lot else about the ZCA class that could be tested here.
"""
rng = np.random.RandomState([1, 2, 3])
X = as_floatX(rng.randn(15, 10))
preprocessor = ZCA()
preprocessor.fit(X)
def is_identity(matrix):
identity = np.identity(matrix.shape[0], theano.config.floatX)
abs_difference = np.abs(identity - matrix)
return (abs_difference < .0001).all()
assert preprocessor.P_.shape == (X.shape[1], X.shape[1])
assert not is_identity(preprocessor.P_)
assert is_identity(np.dot(preprocessor.P_, preprocessor.inv_P_))
def test_zca_dtypes():
"""
Confirm that ZCA.fit works regardless of dtype of data and config.floatX
"""
orig_floatX = config.floatX
try:
for floatX in ['float32', 'float64']:
for dtype in ['float32', 'float64']:
rng = np.random.RandomState([1, 2, 3])
X = rng.randn(15, 10).astype(dtype)
preprocessor = ZCA()
preprocessor.fit(X)
finally:
config.floatX = orig_floatX
| bsd-3-clause |
artempetrovjava/yii-project | modules/likes/Likes.php | 234 | <?php
/**
* Created by PhpStorm.
* User: petrov
* Date: 08.07.16
* Time: 12:20
*/
namespace app\modules\likes;
use yii\base\Module;
class Likes extends Module
{
public function init()
{
parent::init();
}
} | bsd-3-clause |
endlessm/chromium-browser | chrome/browser/heavy_ad_intervention/heavy_ad_service.cc | 2606 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/heavy_ad_intervention/heavy_ad_service.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/memory/scoped_refptr.h"
#include "base/metrics/field_trial_params.h"
#include "base/sequenced_task_runner.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/time/default_clock.h"
#include "chrome/browser/heavy_ad_intervention/heavy_ad_blocklist.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_features.h"
#include "components/blacklist/opt_out_blacklist/sql/opt_out_store_sql.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
// Whether an opt out store should be used or not.
bool HeavyAdOptOutStoreDisabled() {
return base::GetFieldTrialParamByFeatureAsBool(
features::kHeavyAdPrivacyMitigations, "OptOutStoreDisabled", false);
}
HeavyAdService::HeavyAdService() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}
HeavyAdService::~HeavyAdService() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}
void HeavyAdService::Initialize(const base::FilePath& profile_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!base::FeatureList::IsEnabled(features::kHeavyAdPrivacyMitigations))
return;
std::unique_ptr<blacklist::OptOutStoreSQL> opt_out_store;
if (!HeavyAdOptOutStoreDisabled()) {
// Get the background thread to run SQLite on.
scoped_refptr<base::SequencedTaskRunner> background_task_runner =
base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::BEST_EFFORT});
opt_out_store = std::make_unique<blacklist::OptOutStoreSQL>(
base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}),
background_task_runner,
profile_path.Append(chrome::kHeavyAdInterventionOptOutDBFilename));
}
heavy_ad_blocklist_ = std::make_unique<HeavyAdBlocklist>(
std::move(opt_out_store), base::DefaultClock::GetInstance(), this);
}
void HeavyAdService::InitializeOffTheRecord() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!base::FeatureList::IsEnabled(features::kHeavyAdPrivacyMitigations))
return;
// Providing a null out_out_store which sets up the blocklist in-memory only.
heavy_ad_blocklist_ = std::make_unique<HeavyAdBlocklist>(
nullptr /* opt_out_store */, base::DefaultClock::GetInstance(), this);
}
| bsd-3-clause |
devbharat/gtsam | doc/html/a00343.js | 1052 | var a00343 =
[
[ "It", "a00343.html#ae93e8cc9363ab49ca1ee78161221051b", null ],
[ "createF", "a00343.html#a4b1b3bd23c314a33f5a765cf66dc1f3d", null ],
[ "createT", "a00343.html#a6f3b24d3101a0f0371e94949a26c7a3a", null ],
[ "logic", "a00343.html#a5721f2eb37ec883933ca19a906fe326a", null ],
[ "operator%", "a00343.html#ab98cf2a4777006c28d6983db5d8ec574", null ],
[ "operator%", "a00343.html#ae4856250df52ce4b9b4b16c7a833408c", null ],
[ "operator<<", "a00343.html#a8c37843912deeded5d819732ae2152a7", null ],
[ "operator<<", "a00343.html#a488af348118a5965a2e4142c9cd6ba42", null ],
[ "operator<<", "a00343.html#ada56b99f564432dcf54a04a0db7dd178", null ],
[ "operator|", "a00343.html#aa6c58dfb2fc9398a026e3268ba2edfad", null ],
[ "parse_table", "a00343.html#aa5050eb56dbbcd247865937208862c43", null ],
[ "F", "a00343.html#aba27e5c58709649abc1dbbb42aec3f08", null ],
[ "grammar", "a00343.html#a3b95f02cdf143d612085777290b341fb", null ],
[ "T", "a00343.html#a6b8662cf435a5e81bb64f24f2452e813", null ]
]; | bsd-3-clause |
softnep0531/tabrisjs | src/js/util-colors.js | 2320 | (function() {
util.colorArrayToString = function(array) {
var r = array[0];
var g = array[1];
var b = array[2];
var a = array.length === 3 ? 1 : Math.round(array[3] * 100 / 255) / 100;
return "rgba(" + r + ", " + g + ", " + b + ", " + a + ")";
};
util.colorStringToArray = function(str) {
if (str === "transparent") {
return [0, 0, 0, 0];
}
// #xxxxxx
if (/^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/.test(str)) {
return [
parseInt(RegExp.$1, 16),
parseInt(RegExp.$2, 16),
parseInt(RegExp.$3, 16),
255
];
}
// #xxx
if (/^#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])$/.test(str)) {
return [
parseInt(RegExp.$1, 16) * 17,
parseInt(RegExp.$2, 16) * 17,
parseInt(RegExp.$3, 16) * 17,
255
];
}
// #rgb(r, g, b)
if (/^rgb\s*\(\s*([+\-]?[0-9]+)\s*,\s*([+\-]?[0-9]+)\s*,\s*([+\-]?[0-9]+)\s*\)$/.test(str)) {
return [
Math.max(0, Math.min(255, parseInt(RegExp.$1))),
Math.max(0, Math.min(255, parseInt(RegExp.$2))),
Math.max(0, Math.min(255, parseInt(RegExp.$3))),
255
];
}
// rgba(r, g, b, a)
if (/^rgba\s*\(\s*([+\-]?[0-9]+)\s*,\s*([+\-]?[0-9]+)\s*,\s*([+\-]?[0-9]+)\s*,\s*([+\-]?([0-9]*\.)?[0-9]+)\s*\)$/.test(str)) {
return [
Math.max(0, Math.min(255, parseInt(RegExp.$1))),
Math.max(0, Math.min(255, parseInt(RegExp.$2))),
Math.max(0, Math.min(255, parseInt(RegExp.$3))),
Math.round(Math.max(0, Math.min(1, parseFloat(RegExp.$4))) * 255)
];
}
// named colors
if (str in NAMES) {
var rgb = NAMES[str];
return [rgb[0], rgb[1], rgb[2], 255];
}
throw new Error("invalid color: " + str);
};
/*
* Basic color keywords as defined in CSS 3
* See http://www.w3.org/TR/css3-color/#html4
*/
var NAMES = {
black: [0, 0, 0],
silver: [192, 192, 192],
gray: [128, 128, 128],
white: [255, 255, 255],
maroon: [128, 0, 0],
red: [255, 0, 0],
purple: [128, 0, 128],
fuchsia: [255, 0, 255],
green: [0, 128, 0],
lime: [0, 255, 0],
olive: [128, 128, 0],
yellow: [255, 255, 0],
navy: [0, 0, 128],
blue: [0, 0, 255],
teal: [0, 128, 128],
aqua: [0, 255, 255]
};
})();
| bsd-3-clause |
tiagoamaro/spree_cpf | lib/generators/spree_cpf/install/install_generator.rb | 1164 | module SpreeCpf
module Generators
class InstallGenerator < Rails::Generators::Base
class_option :auto_run_migrations, :type => :boolean, :default => false
def add_javascripts
# append_file 'app/assets/javascripts/store/all.js', "//= require store/spree_cpf\n"
# append_file 'app/assets/javascripts/admin/all.js', "//= require admin/spree_cpf\n"
end
def add_stylesheets
# inject_into_file 'app/assets/stylesheets/store/all.css', " *= require store/spree_cpf\n", :before => /\*\//, :verbose => true
# inject_into_file 'app/assets/stylesheets/admin/all.css', " *= require admin/spree_cpf\n", :before => /\*\//, :verbose => true
end
def add_migrations
run 'bundle exec rake railties:install:migrations FROM=spree_cpf'
end
def run_migrations
run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]')
if run_migrations
run 'bundle exec rake db:migrate'
else
puts 'Skipping rake db:migrate, don\'t forget to run it!'
end
end
end
end
end
| bsd-3-clause |
nicholasserra/sentry | tests/sentry/options/test_manager.py | 10356 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from exam import fixture, around
from mock import patch
from sentry.models import Option
from sentry.options.store import OptionsStore
from sentry.options.manager import (
OptionsManager, UnknownOption, DEFAULT_FLAGS,
FLAG_IMMUTABLE, FLAG_NOSTORE, FLAG_STOREONLY, FLAG_REQUIRED, FLAG_PRIORITIZE_DISK)
from sentry.utils.types import Int, String
from sentry.testutils import TestCase
class OptionsManagerTest(TestCase):
store = fixture(OptionsStore)
@fixture
def manager(self):
return OptionsManager(store=self.store)
@around
def register(self):
self.store.flush_local_cache()
self.manager.register('foo')
yield
self.manager.unregister('foo')
def test_simple(self):
assert self.manager.get('foo') == ''
with self.settings(SENTRY_OPTIONS={'foo': 'bar'}):
assert self.manager.get('foo') == 'bar'
self.manager.set('foo', 'bar')
assert self.manager.get('foo') == 'bar'
self.manager.delete('foo')
assert self.manager.get('foo') == ''
def test_register(self):
with self.assertRaises(UnknownOption):
self.manager.get('does-not-exit')
with self.assertRaises(UnknownOption):
self.manager.set('does-not-exist', 'bar')
self.manager.register('does-not-exist')
self.manager.get('does-not-exist') # Just shouldn't raise
self.manager.unregister('does-not-exist')
with self.assertRaises(UnknownOption):
self.manager.get('does-not-exist')
with self.assertRaises(AssertionError):
# This key should already exist, and we can't re-register
self.manager.register('foo')
with self.assertRaises(TypeError):
self.manager.register('wrong-type', default=1, type=String)
with self.assertRaises(TypeError):
self.manager.register('none-type', default=None, type=type(None))
def test_coerce(self):
self.manager.register('some-int', type=Int)
self.manager.set('some-int', 0)
assert self.manager.get('some-int') == 0
self.manager.set('some-int', '0')
assert self.manager.get('some-int') == 0
with self.assertRaises(TypeError):
self.manager.set('some-int', 'foo')
with self.assertRaises(TypeError):
self.manager.set('some-int', '0', coerce=False)
def test_legacy_key(self):
"""
Allow sentry: prefixed keys without any registration
"""
# These just shouldn't blow up since they are implicitly registered
assert self.manager.get('sentry:foo') == ''
self.manager.set('sentry:foo', 'bar')
assert self.manager.get('sentry:foo') == 'bar'
assert self.manager.delete('sentry:foo')
assert self.manager.get('sentry:foo') == ''
def test_types(self):
self.manager.register('some-int', type=Int, default=0)
with self.assertRaises(TypeError):
self.manager.set('some-int', 'foo')
self.manager.set('some-int', 1)
assert self.manager.get('some-int') == 1
def test_default(self):
self.manager.register('awesome', default='lol')
assert self.manager.get('awesome') == 'lol'
self.manager.set('awesome', 'bar')
assert self.manager.get('awesome') == 'bar'
self.manager.delete('awesome')
assert self.manager.get('awesome') == 'lol'
self.manager.register('callback', default=lambda: True)
assert self.manager.get('callback') is True
self.manager.register('default-type', type=Int)
assert self.manager.get('default-type') == 0
def test_flag_immutable(self):
self.manager.register('immutable', flags=FLAG_IMMUTABLE)
with self.assertRaises(AssertionError):
self.manager.set('immutable', 'thing')
with self.assertRaises(AssertionError):
self.manager.delete('immutable')
def test_flag_nostore(self):
self.manager.register('nostore', flags=FLAG_NOSTORE)
with self.assertRaises(AssertionError):
self.manager.set('nostore', 'thing')
# Make sure that we don't touch either of the stores
with patch.object(self.store.cache, 'get', side_effect=Exception()):
with patch.object(Option.objects, 'get_queryset', side_effect=Exception()):
assert self.manager.get('nostore') == ''
self.store.flush_local_cache()
with self.settings(SENTRY_OPTIONS={'nostore': 'foo'}):
assert self.manager.get('nostore') == 'foo'
self.store.flush_local_cache()
with self.assertRaises(AssertionError):
self.manager.delete('nostore')
def test_validate(self):
with self.assertRaises(UnknownOption):
self.manager.validate({'unknown': ''})
self.manager.register('unknown')
self.manager.register('storeonly', flags=FLAG_STOREONLY)
self.manager.validate({'unknown': ''})
with self.assertRaises(AssertionError):
self.manager.validate({'storeonly': ''})
with self.assertRaises(TypeError):
self.manager.validate({'unknown': True})
def test_flag_storeonly(self):
self.manager.register('storeonly', flags=FLAG_STOREONLY)
assert self.manager.get('storeonly') == ''
with self.settings(SENTRY_OPTIONS={'storeonly': 'something-else!'}):
assert self.manager.get('storeonly') == ''
def test_flag_prioritize_disk(self):
self.manager.register('prioritize_disk', flags=FLAG_PRIORITIZE_DISK)
assert self.manager.get('prioritize_disk') == ''
with self.settings(SENTRY_OPTIONS={'prioritize_disk': 'something-else!'}):
with self.assertRaises(AssertionError):
assert self.manager.set('prioritize_disk', 'foo')
assert self.manager.get('prioritize_disk') == 'something-else!'
self.manager.set('prioritize_disk', 'foo')
assert self.manager.get('prioritize_disk') == 'foo'
# Make sure the database value is overridden if defined
with self.settings(SENTRY_OPTIONS={'prioritize_disk': 'something-else!'}):
assert self.manager.get('prioritize_disk') == 'something-else!'
def test_db_unavailable(self):
with patch.object(Option.objects, 'get_queryset', side_effect=Exception()):
# we can't update options if the db is unavailable
with self.assertRaises(Exception):
self.manager.set('foo', 'bar')
self.manager.set('foo', 'bar')
self.store.flush_local_cache()
with patch.object(Option.objects, 'get_queryset', side_effect=Exception()):
assert self.manager.get('foo') == 'bar'
self.store.flush_local_cache()
with patch.object(self.store.cache, 'get', side_effect=Exception()):
assert self.manager.get('foo') == ''
self.store.flush_local_cache()
with patch.object(self.store.cache, 'set', side_effect=Exception()):
assert self.manager.get('foo') == ''
self.store.flush_local_cache()
def test_db_and_cache_unavailable(self):
self.manager.set('foo', 'bar')
self.store.flush_local_cache()
with self.settings(SENTRY_OPTIONS={'foo': 'baz'}):
with patch.object(Option.objects, 'get_queryset', side_effect=Exception()):
with patch.object(self.store.cache, 'get', side_effect=Exception()):
assert self.manager.get('foo') == 'baz'
self.store.flush_local_cache()
with patch.object(self.store.cache, 'set', side_effect=Exception()):
assert self.manager.get('foo') == 'baz'
self.store.flush_local_cache()
def test_cache_unavailable(self):
self.manager.set('foo', 'bar')
self.store.flush_local_cache()
with patch.object(self.store.cache, 'get', side_effect=Exception()):
assert self.manager.get('foo') == 'bar'
self.store.flush_local_cache()
with patch.object(self.store.cache, 'set', side_effect=Exception()):
assert self.manager.get('foo') == 'bar'
self.store.flush_local_cache()
# we should still be able to write a new value
self.manager.set('foo', 'baz')
self.store.flush_local_cache()
# the cache should be incorrect now, but sync_options will eventually
# correct the state
assert self.manager.get('foo') == 'bar'
self.store.flush_local_cache()
# when the cache poofs, the db will be return the most-true answer
with patch.object(self.store.cache, 'get', side_effect=Exception()):
assert self.manager.get('foo') == 'baz'
self.store.flush_local_cache()
with patch.object(self.store.cache, 'set', side_effect=Exception()):
assert self.manager.get('foo') == 'baz'
self.store.flush_local_cache()
def test_unregister(self):
with self.assertRaises(UnknownOption):
self.manager.unregister('does-not-exist')
def test_all(self):
self.manager.register('bar')
keys = list(self.manager.all())
assert {k.name for k in keys} == {'foo', 'bar'}
def test_filter(self):
self.manager.register('nostore', flags=FLAG_NOSTORE)
self.manager.register('required', flags=FLAG_REQUIRED)
self.manager.register('nostorerequired', flags=FLAG_NOSTORE | FLAG_REQUIRED)
assert list(self.manager.filter()) == list(self.manager.all())
keys = list(self.manager.filter())
assert {k.name for k in keys} == {'foo', 'nostore', 'required', 'nostorerequired'}
keys = list(self.manager.filter(flag=DEFAULT_FLAGS))
assert {k.name for k in keys} == {'foo'}
keys = list(self.manager.filter(flag=FLAG_NOSTORE))
assert {k.name for k in keys} == {'nostore', 'nostorerequired'}
keys = list(self.manager.filter(flag=FLAG_REQUIRED))
assert {k.name for k in keys} == {'required', 'nostorerequired'}
| bsd-3-clause |
was4444/chromium.src | chrome/browser/metrics/chrome_metrics_service_client.cc | 26756 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/metrics/chrome_metrics_service_client.h"
#include <stddef.h>
#include <vector>
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/strings/string16.h"
#include "base/threading/platform_thread.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/google/google_brand.h"
#include "chrome/browser/metrics/chrome_stability_metrics_provider.h"
#include "chrome/browser/metrics/metrics_reporting_state.h"
#include "chrome/browser/metrics/subprocess_metrics_provider.h"
#include "chrome/browser/metrics/time_ticks_experiment_win.h"
#include "chrome/browser/sync/chrome_sync_client.h"
#include "chrome/browser/ui/browser_otr_state.h"
#include "chrome/common/channel_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/common/features.h"
#include "chrome/installer/util/util_constants.h"
#include "components/metrics/call_stack_profile_metrics_provider.h"
#include "components/metrics/drive_metrics_provider.h"
#include "components/metrics/file_metrics_provider.h"
#include "components/metrics/gpu/gpu_metrics_provider.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/metrics/metrics_service.h"
#include "components/metrics/metrics_service_client.h"
#include "components/metrics/net/net_metrics_log_uploader.h"
#include "components/metrics/net/network_metrics_provider.h"
#include "components/metrics/net/version_utils.h"
#include "components/metrics/profiler/profiler_metrics_provider.h"
#include "components/metrics/profiler/tracking_synchronizer.h"
#include "components/metrics/stability_metrics_helper.h"
#include "components/metrics/ui/screen_info_metrics_provider.h"
#include "components/metrics/url_constants.h"
#include "components/omnibox/browser/omnibox_metrics_provider.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/sync_driver/device_count_metrics_provider.h"
#include "components/variations/variations_associated_data.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/histogram_fetcher.h"
#include "content/public/browser/notification_service.h"
#if BUILDFLAG(ANDROID_JAVA_UI)
#include "chrome/browser/metrics/android_metrics_provider.h"
#endif
#if defined(ENABLE_PRINT_PREVIEW)
#include "chrome/browser/service_process/service_process_control.h"
#endif
#if defined(ENABLE_EXTENSIONS)
#include "chrome/browser/metrics/extensions_metrics_provider.h"
#endif
#if defined(ENABLE_PLUGINS)
#include "chrome/browser/metrics/plugin_metrics_provider.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/browser/metrics/chromeos_metrics_provider.h"
#include "chrome/browser/signin/signin_status_metrics_provider_chromeos.h"
#endif
#if defined(OS_WIN)
#include <windows.h>
#include "chrome/browser/metrics/google_update_metrics_provider_win.h"
#include "chrome/installer/util/browser_distribution.h"
#include "components/browser_watcher/watcher_metrics_provider_win.h"
#endif
#if !defined(OS_CHROMEOS)
#include "chrome/browser/signin/chrome_signin_status_metrics_provider_delegate.h"
#include "components/signin/core/browser/signin_status_metrics_provider.h"
#endif // !defined(OS_CHROMEOS)
namespace {
// This specifies the amount of time to wait for all renderers to send their
// data.
const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
// Standard interval between log uploads, in seconds.
#if defined(OS_ANDROID)
const int kStandardUploadIntervalSeconds = 5 * 60; // Five minutes.
const int kStandardUploadIntervalCellularSeconds = 15 * 60; // Fifteen minutes.
#else
const int kStandardUploadIntervalSeconds = 30 * 60; // Thirty minutes.
#endif
// Returns true if current connection type is cellular and user is assigned to
// experimental group for enabled cellular uploads.
bool IsCellularLogicEnabled() {
if (variations::GetVariationParamValue("UMA_EnableCellularLogUpload",
"Enabled") != "true" ||
variations::GetVariationParamValue("UMA_EnableCellularLogUpload",
"Optimize") == "false") {
return false;
}
return net::NetworkChangeNotifier::IsConnectionCellular(
net::NetworkChangeNotifier::GetConnectionType());
}
// Checks whether it is the first time that cellular uploads logic should be
// enabled based on whether the the preference for that logic is initialized.
// This should happen only once as the used preference will be initialized
// afterwards in |UmaSessionStats.java|.
bool ShouldClearSavedMetrics() {
#if BUILDFLAG(ANDROID_JAVA_UI)
PrefService* local_state = g_browser_process->local_state();
return !local_state->HasPrefPath(metrics::prefs::kMetricsReportingEnabled) &&
variations::GetVariationParamValue("UMA_EnableCellularLogUpload",
"Enabled") == "true";
#else
return false;
#endif
}
void RegisterInstallerFileMetricsPreferences(PrefRegistrySimple* registry) {
#if defined(OS_WIN)
metrics::FileMetricsProvider::RegisterPrefs(
registry, installer::kSetupHistogramAllocatorName);
#endif
}
void RegisterInstallerFileMetricsProvider(
metrics::MetricsService* metrics_service) {
#if defined(OS_WIN)
scoped_ptr<metrics::FileMetricsProvider> file_metrics(
new metrics::FileMetricsProvider(
content::BrowserThread::GetBlockingPool()
->GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN),
g_browser_process->local_state()));
base::FilePath program_dir;
base::PathService::Get(base::DIR_EXE, &program_dir);
file_metrics->RegisterFile(
program_dir.AppendASCII(installer::kSetupHistogramAllocatorName)
.AddExtension(L".pma"),
metrics::FileMetricsProvider::FILE_HISTOGRAMS_ATOMIC,
installer::kSetupHistogramAllocatorName);
metrics_service->RegisterMetricsProvider(std::move(file_metrics));
#endif
}
} // namespace
ChromeMetricsServiceClient::ChromeMetricsServiceClient(
metrics::MetricsStateManager* state_manager)
: metrics_state_manager_(state_manager),
#if defined(OS_CHROMEOS)
chromeos_metrics_provider_(nullptr),
#endif
waiting_for_collect_final_metrics_step_(false),
num_async_histogram_fetches_in_progress_(0),
profiler_metrics_provider_(nullptr),
#if defined(ENABLE_PLUGINS)
plugin_metrics_provider_(nullptr),
#endif
#if defined(OS_WIN)
google_update_metrics_provider_(nullptr),
#endif
drive_metrics_provider_(nullptr),
start_time_(base::TimeTicks::Now()),
has_uploaded_profiler_data_(false),
weak_ptr_factory_(this) {
DCHECK(thread_checker_.CalledOnValidThread());
RecordCommandLineMetrics();
RegisterForNotifications();
}
ChromeMetricsServiceClient::~ChromeMetricsServiceClient() {
DCHECK(thread_checker_.CalledOnValidThread());
}
// static
scoped_ptr<ChromeMetricsServiceClient> ChromeMetricsServiceClient::Create(
metrics::MetricsStateManager* state_manager,
PrefService* local_state) {
// Perform two-phase initialization so that |client->metrics_service_| only
// receives pointers to fully constructed objects.
scoped_ptr<ChromeMetricsServiceClient> client(
new ChromeMetricsServiceClient(state_manager));
client->Initialize();
return client;
}
// static
void ChromeMetricsServiceClient::RegisterPrefs(PrefRegistrySimple* registry) {
metrics::MetricsService::RegisterPrefs(registry);
metrics::StabilityMetricsHelper::RegisterPrefs(registry);
RegisterInstallerFileMetricsPreferences(registry);
RegisterMetricsReportingStatePrefs(registry);
#if BUILDFLAG(ANDROID_JAVA_UI)
AndroidMetricsProvider::RegisterPrefs(registry);
#endif // BUILDFLAG(ANDROID_JAVA_UI)
#if defined(ENABLE_PLUGINS)
PluginMetricsProvider::RegisterPrefs(registry);
#endif // defined(ENABLE_PLUGINS)
}
metrics::MetricsService* ChromeMetricsServiceClient::GetMetricsService() {
return metrics_service_.get();
}
void ChromeMetricsServiceClient::SetMetricsClientId(
const std::string& client_id) {
crash_keys::SetMetricsClientIdFromGUID(client_id);
}
void ChromeMetricsServiceClient::OnRecordingDisabled() {
crash_keys::ClearMetricsClientId();
}
bool ChromeMetricsServiceClient::IsOffTheRecordSessionActive() {
return chrome::IsOffTheRecordSessionActive();
}
int32_t ChromeMetricsServiceClient::GetProduct() {
return metrics::ChromeUserMetricsExtension::CHROME;
}
std::string ChromeMetricsServiceClient::GetApplicationLocale() {
return g_browser_process->GetApplicationLocale();
}
bool ChromeMetricsServiceClient::GetBrand(std::string* brand_code) {
return google_brand::GetBrand(brand_code);
}
metrics::SystemProfileProto::Channel ChromeMetricsServiceClient::GetChannel() {
return metrics::AsProtobufChannel(chrome::GetChannel());
}
std::string ChromeMetricsServiceClient::GetVersionString() {
return metrics::GetVersionString();
}
void ChromeMetricsServiceClient::OnLogUploadComplete() {
// Collect time ticks stats after each UMA upload.
#if defined(OS_WIN)
chrome::CollectTimeTicksStats();
#endif
}
void ChromeMetricsServiceClient::InitializeSystemProfileMetrics(
const base::Closure& done_callback) {
finished_init_task_callback_ = done_callback;
base::Closure got_hardware_class_callback =
base::Bind(&ChromeMetricsServiceClient::OnInitTaskGotHardwareClass,
weak_ptr_factory_.GetWeakPtr());
#if defined(OS_CHROMEOS)
chromeos_metrics_provider_->InitTaskGetHardwareClass(
got_hardware_class_callback);
#else
got_hardware_class_callback.Run();
#endif // defined(OS_CHROMEOS)
}
void ChromeMetricsServiceClient::CollectFinalMetricsForLog(
const base::Closure& done_callback) {
DCHECK(thread_checker_.CalledOnValidThread());
collect_final_metrics_done_callback_ = done_callback;
if (ShouldIncludeProfilerDataInLog()) {
// Fetch profiler data. This will call into
// |FinishedReceivingProfilerData()| when the task completes.
metrics::TrackingSynchronizer::FetchProfilerDataAsynchronously(
weak_ptr_factory_.GetWeakPtr());
} else {
CollectFinalHistograms();
}
}
scoped_ptr<metrics::MetricsLogUploader>
ChromeMetricsServiceClient::CreateUploader(
const base::Callback<void(int)>& on_upload_complete) {
return scoped_ptr<metrics::MetricsLogUploader>(
new metrics::NetMetricsLogUploader(
g_browser_process->system_request_context(),
metrics::kDefaultMetricsServerUrl,
metrics::kDefaultMetricsMimeType,
on_upload_complete));
}
base::TimeDelta ChromeMetricsServiceClient::GetStandardUploadInterval() {
#if defined(OS_ANDROID)
if (IsCellularLogicEnabled())
return base::TimeDelta::FromSeconds(kStandardUploadIntervalCellularSeconds);
#endif
return base::TimeDelta::FromSeconds(kStandardUploadIntervalSeconds);
}
base::string16 ChromeMetricsServiceClient::GetRegistryBackupKey() {
#if defined(OS_WIN)
BrowserDistribution* distribution = BrowserDistribution::GetDistribution();
return distribution->GetRegistryPath().append(L"\\StabilityMetrics");
#else
return base::string16();
#endif
}
void ChromeMetricsServiceClient::OnPluginLoadingError(
const base::FilePath& plugin_path) {
#if defined(ENABLE_PLUGINS)
plugin_metrics_provider_->LogPluginLoadingError(plugin_path);
#else
NOTREACHED();
#endif // defined(ENABLE_PLUGINS)
}
bool ChromeMetricsServiceClient::IsReportingPolicyManaged() {
return IsMetricsReportingPolicyManaged();
}
metrics::MetricsServiceClient::EnableMetricsDefault
ChromeMetricsServiceClient::GetDefaultOptIn() {
return GetMetricsReportingDefaultOptIn(g_browser_process->local_state());
}
void ChromeMetricsServiceClient::Initialize() {
// Clear metrics reports if it is the first time cellular upload logic should
// apply to avoid sudden bulk uploads. It needs to be done before initializing
// metrics service so that metrics log manager is initialized correctly.
if (ShouldClearSavedMetrics()) {
PrefService* local_state = g_browser_process->local_state();
local_state->ClearPref(metrics::prefs::kMetricsInitialLogs);
local_state->ClearPref(metrics::prefs::kMetricsOngoingLogs);
}
metrics_service_.reset(new metrics::MetricsService(
metrics_state_manager_, this, g_browser_process->local_state()));
// Gets access to persistent metrics shared by sub-processes.
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(new SubprocessMetricsProvider()));
// Register metrics providers.
#if defined(ENABLE_EXTENSIONS)
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(
new ExtensionsMetricsProvider(metrics_state_manager_)));
#endif
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(new metrics::NetworkMetricsProvider(
content::BrowserThread::GetBlockingPool())));
// Currently, we configure OmniboxMetricsProvider to not log events to UMA
// if there is a single incognito session visible. In the future, it may
// be worth revisiting this to still log events from non-incognito sessions.
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(new OmniboxMetricsProvider(
base::Bind(&chrome::IsOffTheRecordSessionActive))));
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(new ChromeStabilityMetricsProvider(
g_browser_process->local_state())));
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(new metrics::GPUMetricsProvider));
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(
new metrics::ScreenInfoMetricsProvider));
RegisterInstallerFileMetricsProvider(metrics_service_.get());
drive_metrics_provider_ = new metrics::DriveMetricsProvider(
content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::FILE),
chrome::FILE_LOCAL_STATE);
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(drive_metrics_provider_));
profiler_metrics_provider_ =
new metrics::ProfilerMetricsProvider(base::Bind(&IsCellularLogicEnabled));
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(profiler_metrics_provider_));
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(
new metrics::CallStackProfileMetricsProvider));
#if BUILDFLAG(ANDROID_JAVA_UI)
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(
new AndroidMetricsProvider(g_browser_process->local_state())));
#endif // BUILDFLAG(ANDROID_JAVA_UI)
#if defined(OS_WIN)
google_update_metrics_provider_ = new GoogleUpdateMetricsProviderWin;
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(google_update_metrics_provider_));
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(
new browser_watcher::WatcherMetricsProviderWin(
chrome::kBrowserExitCodesRegistryPath,
content::BrowserThread::GetBlockingPool())));
#endif // defined(OS_WIN)
#if defined(ENABLE_PLUGINS)
plugin_metrics_provider_ =
new PluginMetricsProvider(g_browser_process->local_state());
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(plugin_metrics_provider_));
#endif // defined(ENABLE_PLUGINS)
#if defined(OS_CHROMEOS)
ChromeOSMetricsProvider* chromeos_metrics_provider =
new ChromeOSMetricsProvider;
chromeos_metrics_provider_ = chromeos_metrics_provider;
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(chromeos_metrics_provider));
SigninStatusMetricsProviderChromeOS* signin_metrics_provider_cros =
new SigninStatusMetricsProviderChromeOS;
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(signin_metrics_provider_cros));
#endif // defined(OS_CHROMEOS)
#if !defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(
SigninStatusMetricsProvider::CreateInstance(
make_scoped_ptr(new ChromeSigninStatusMetricsProviderDelegate))));
#endif // !defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
scoped_ptr<metrics::MetricsProvider>(
new sync_driver::DeviceCountMetricsProvider(base::Bind(
&browser_sync::ChromeSyncClient::GetDeviceInfoTrackers))));
// Clear stability metrics if it is the first time cellular upload logic
// should apply to avoid sudden bulk uploads. It needs to be done after all
// providers are registered.
if (ShouldClearSavedMetrics())
metrics_service_->ClearSavedStabilityMetrics();
}
void ChromeMetricsServiceClient::OnInitTaskGotHardwareClass() {
const base::Closure got_bluetooth_adapter_callback =
base::Bind(&ChromeMetricsServiceClient::OnInitTaskGotBluetoothAdapter,
weak_ptr_factory_.GetWeakPtr());
#if defined(OS_CHROMEOS)
chromeos_metrics_provider_->InitTaskGetBluetoothAdapter(
got_bluetooth_adapter_callback);
#else
got_bluetooth_adapter_callback.Run();
#endif // defined(OS_CHROMEOS)
}
void ChromeMetricsServiceClient::OnInitTaskGotBluetoothAdapter() {
const base::Closure got_plugin_info_callback =
base::Bind(&ChromeMetricsServiceClient::OnInitTaskGotPluginInfo,
weak_ptr_factory_.GetWeakPtr());
#if defined(ENABLE_PLUGINS)
plugin_metrics_provider_->GetPluginInformation(got_plugin_info_callback);
#else
got_plugin_info_callback.Run();
#endif // defined(ENABLE_PLUGINS)
}
void ChromeMetricsServiceClient::OnInitTaskGotPluginInfo() {
const base::Closure got_metrics_callback =
base::Bind(&ChromeMetricsServiceClient::OnInitTaskGotGoogleUpdateData,
weak_ptr_factory_.GetWeakPtr());
#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
google_update_metrics_provider_->GetGoogleUpdateData(got_metrics_callback);
#else
got_metrics_callback.Run();
#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
}
void ChromeMetricsServiceClient::OnInitTaskGotGoogleUpdateData() {
drive_metrics_provider_->GetDriveMetrics(
base::Bind(&ChromeMetricsServiceClient::OnInitTaskGotDriveMetrics,
weak_ptr_factory_.GetWeakPtr()));
}
void ChromeMetricsServiceClient::OnInitTaskGotDriveMetrics() {
finished_init_task_callback_.Run();
}
bool ChromeMetricsServiceClient::ShouldIncludeProfilerDataInLog() {
// Upload profiler data at most once per session.
if (has_uploaded_profiler_data_)
return false;
// For each log, flip a fair coin. Thus, profiler data is sent with the first
// log with probability 50%, with the second log with probability 25%, and so
// on. As a result, uploaded data is biased toward earlier logs.
// TODO(isherman): Explore other possible algorithms, and choose one that
// might be more appropriate. For example, it might be reasonable to include
// profiler data with some fixed probability, so that a given client might
// upload profiler data more than once; but on average, clients won't upload
// too much data.
if (base::RandDouble() < 0.5)
return false;
has_uploaded_profiler_data_ = true;
return true;
}
void ChromeMetricsServiceClient::ReceivedProfilerData(
const metrics::ProfilerDataAttributes& attributes,
const tracked_objects::ProcessDataPhaseSnapshot& process_data_phase,
const metrics::ProfilerEvents& past_events) {
profiler_metrics_provider_->RecordProfilerData(
process_data_phase, attributes.process_id, attributes.process_type,
attributes.profiling_phase, attributes.phase_start - start_time_,
attributes.phase_finish - start_time_, past_events);
}
void ChromeMetricsServiceClient::FinishedReceivingProfilerData() {
CollectFinalHistograms();
}
void ChromeMetricsServiceClient::CollectFinalHistograms() {
DCHECK(thread_checker_.CalledOnValidThread());
// Begin the multi-step process of collecting memory usage histograms:
// First spawn a task to collect the memory details; when that task is
// finished, it will call OnMemoryDetailCollectionDone. That will in turn
// call HistogramSynchronization to collect histograms from all renderers and
// then call OnHistogramSynchronizationDone to continue processing.
DCHECK(!waiting_for_collect_final_metrics_step_);
waiting_for_collect_final_metrics_step_ = true;
base::Closure callback =
base::Bind(&ChromeMetricsServiceClient::OnMemoryDetailCollectionDone,
weak_ptr_factory_.GetWeakPtr());
scoped_refptr<MetricsMemoryDetails> details(
new MetricsMemoryDetails(callback, &memory_growth_tracker_));
details->StartFetch(MemoryDetails::FROM_CHROME_ONLY);
}
void ChromeMetricsServiceClient::OnMemoryDetailCollectionDone() {
DCHECK(thread_checker_.CalledOnValidThread());
// This function should only be called as the callback from an ansynchronous
// step.
DCHECK(waiting_for_collect_final_metrics_step_);
// Create a callback_task for OnHistogramSynchronizationDone.
base::Closure callback = base::Bind(
&ChromeMetricsServiceClient::OnHistogramSynchronizationDone,
weak_ptr_factory_.GetWeakPtr());
base::TimeDelta timeout =
base::TimeDelta::FromMilliseconds(kMaxHistogramGatheringWaitDuration);
DCHECK_EQ(num_async_histogram_fetches_in_progress_, 0);
#if !defined(ENABLE_PRINT_PREVIEW)
num_async_histogram_fetches_in_progress_ = 1;
#else // !ENABLE_PRINT_PREVIEW
num_async_histogram_fetches_in_progress_ = 2;
// Run requests to service and content in parallel.
if (!ServiceProcessControl::GetInstance()->GetHistograms(callback, timeout)) {
// Assume |num_async_histogram_fetches_in_progress_| is not changed by
// |GetHistograms()|.
DCHECK_EQ(num_async_histogram_fetches_in_progress_, 2);
// Assign |num_async_histogram_fetches_in_progress_| above and decrement it
// here to make code work even if |GetHistograms()| fired |callback|.
--num_async_histogram_fetches_in_progress_;
}
#endif // !ENABLE_PRINT_PREVIEW
// Set up the callback task to call after we receive histograms from all
// child processes. |timeout| specifies how long to wait before absolutely
// calling us back on the task.
content::FetchHistogramsAsynchronously(base::MessageLoop::current(), callback,
timeout);
}
void ChromeMetricsServiceClient::OnHistogramSynchronizationDone() {
DCHECK(thread_checker_.CalledOnValidThread());
// This function should only be called as the callback from an ansynchronous
// step.
DCHECK(waiting_for_collect_final_metrics_step_);
DCHECK_GT(num_async_histogram_fetches_in_progress_, 0);
// Check if all expected requests finished.
if (--num_async_histogram_fetches_in_progress_ > 0)
return;
waiting_for_collect_final_metrics_step_ = false;
collect_final_metrics_done_callback_.Run();
}
void ChromeMetricsServiceClient::RecordCommandLineMetrics() {
// Get stats on use of command line.
const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess());
size_t common_commands = 0;
if (command_line->HasSwitch(switches::kUserDataDir)) {
++common_commands;
UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
}
if (command_line->HasSwitch(switches::kApp)) {
++common_commands;
UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
}
// TODO(rohitrao): Should these be logged on iOS as well?
// http://crbug.com/375794
size_t switch_count = command_line->GetSwitches().size();
UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount", switch_count);
UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
switch_count - common_commands);
}
void ChromeMetricsServiceClient::RegisterForNotifications() {
registrar_.Add(this, chrome::NOTIFICATION_BROWSER_OPENED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, chrome::NOTIFICATION_BROWSER_CLOSED,
content::NotificationService::AllSources());
registrar_.Add(this, chrome::NOTIFICATION_TAB_PARENTED,
content::NotificationService::AllSources());
registrar_.Add(this, chrome::NOTIFICATION_TAB_CLOSING,
content::NotificationService::AllSources());
registrar_.Add(this, content::NOTIFICATION_LOAD_START,
content::NotificationService::AllSources());
registrar_.Add(this, content::NOTIFICATION_LOAD_STOP,
content::NotificationService::AllSources());
registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
content::NotificationService::AllSources());
registrar_.Add(this, content::NOTIFICATION_RENDER_WIDGET_HOST_HANG,
content::NotificationService::AllSources());
omnibox_url_opened_subscription_ =
OmniboxEventGlobalTracker::GetInstance()->RegisterCallback(
base::Bind(&ChromeMetricsServiceClient::OnURLOpenedFromOmnibox,
base::Unretained(this)));
}
void ChromeMetricsServiceClient::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK(thread_checker_.CalledOnValidThread());
switch (type) {
case chrome::NOTIFICATION_BROWSER_OPENED:
case chrome::NOTIFICATION_BROWSER_CLOSED:
case chrome::NOTIFICATION_TAB_PARENTED:
case chrome::NOTIFICATION_TAB_CLOSING:
case content::NOTIFICATION_LOAD_STOP:
case content::NOTIFICATION_LOAD_START:
case content::NOTIFICATION_RENDERER_PROCESS_CLOSED:
case content::NOTIFICATION_RENDER_WIDGET_HOST_HANG:
metrics_service_->OnApplicationNotIdle();
break;
default:
NOTREACHED();
}
}
void ChromeMetricsServiceClient::OnURLOpenedFromOmnibox(OmniboxLog* log) {
metrics_service_->OnApplicationNotIdle();
}
bool ChromeMetricsServiceClient::IsUMACellularUploadLogicEnabled() {
return IsCellularLogicEnabled();
}
| bsd-3-clause |
OPL/opl3-collector | src/Opl/Collector/LoaderInterface.php | 793 | <?php
/*
* OPEN POWER LIBS <http://www.invenzzia.org>
*
* This file is subject to the new BSD license that is bundled
* with this package in the file LICENSE. It is also available through
* WWW at this URL: <http://www.invenzzia.org/license/new-bsd>
*
* Copyright (c) Invenzzia Group <http://www.invenzzia.org>
* and other contributors. See website for details.
*/
namespace Opl\Collector;
/**
* Loaders load the data to the collector.
*
* @author Tomasz Jędrzejewski
* @copyright Invenzzia Group <http://www.invenzzia.org/> and contributors.
* @license http://www.invenzzia.org/license/new-bsd New BSD License
*/
interface LoaderInterface
{
/**
* Returns the imported data in a form of an array.
* @return array
*/
public function import();
} // end LoaderInterface; | bsd-3-clause |
char0n/ramda-adjunct | src/delayP.js | 1336 | import { curry, propOr, partial, nth } from 'ramda';
import isNonNegative from './isNonNegative';
import isInteger from './isInteger';
/**
* Creates a promise which resolves/rejects after the specified milliseconds.
*
* @func delayP
* @memberOf RA
* @category Function
* @sig Number -> Promise Undefined
* @sig {timeout: Number, value: a} -> Promise a
* @param {number|Object} milliseconds number of milliseconds or options object
* @return {Promise} A Promise that is resolved/rejected with the given value (if provided) after the specified delay
* @example
*
* RA.delayP(200); //=> Promise(undefined)
* RA.delayP({ timeout: 1000, value: 'hello world' }); //=> Promise('hello world')
* RA.delayP.reject(100); //=> Promise(undefined)
* RA.delayP.reject({ timeout: 100, value: new Error('error') }); //=> Promise(Error('error'))
*/
const makeDelay = curry((settleFnPicker, opts) => {
let timeout;
let value;
if (isInteger(opts) && isNonNegative(opts)) {
timeout = opts;
} else {
timeout = propOr(0, 'timeout', opts);
value = propOr(value, 'value', opts);
}
return new Promise((...args) => {
const settleFn = settleFnPicker(args);
setTimeout(partial(settleFn, [value]), timeout);
});
});
const delayP = makeDelay(nth(0));
delayP.reject = makeDelay(nth(1));
export default delayP;
| bsd-3-clause |
jvoorhis/ssh-public-key | test/public_key_test.rb | 4607 | require 'test/unit'
require 'ssh_public_key'
class SSHPublicKeyTest < Test::Unit::TestCase
RSAKEY = <<RSA.chomp
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAwVlYiHtFfcoME7krIar/caT5+CUqpLJd3yj4mT6AXAVGSKe/GmjQGax1xD33BlEGrdQ+G7km+grYMTOaz7OlPbq7HG4o66mN+RqWje1NOkOKRTSjR+HMy6GOJlo17lwekDFOz90c7F8rRYnwLc5Mt2H3Filzyu3nipVsXG6TFfoHUJo1v9UHy1y3f9yK9DCIcAPcuF1eN6kmnilfqTY3j8GlOaLOIkvEYE/yTXutcTV8oOybbbG+5XTGNPJckpCX0iKaZb1gQ30dhmzH4xXgatTbf3rEKs6mgbvIS/PNJjcU9hrWOwLcR+Jw5X59seEJDCkalKvRKkX2Tpi4onw6mw== rsa@test
RSA
RSAKEY_E = 35
RSAKEY_M = 24408050930543034452386051466409879414684067520374285355132796961550729899129155364455677362325669150754359670615102940636118877195794580288375112737903765406417456067918529441478974512856013752695538161076129916446792082695022285118897782926181788843870329152103326287034929518386586682765955587604566425854760108209605868926768563786723546070598260713182060944576006708526466255017829176199001772236324586516457885565540500685884542118915944069571482986612965710054757483168377567236174578824727328357759950476887210832906341740372630703544695151269012770162054529948633965153810896218465947323359740231748794727067
RSAKEY_COMMENT = "rsa@test"
DSAKEY = <<DSA.chomp
ssh-dss AAAAB3NzaC1kc3MAAACBAOxST6PN0e3Ry/4Ks7Dhqw7c0isgbXUSXcdi9vk+9HTWlk1zIcU31lcuED+A8ZPxEZ74G2nP23L1VGRYquvFIjSADnJSD7mVp8fak/Lxsrk9k/b8DEMKy+Y2hyzR1wqeAoCCJRkKHQOm3nginHsff14MHi/Y0yQdQQ4HD1jQycBBAAAAFQCWjSFdIbl3F5e4F5Mx6x7W5osUmwAAAIEArEe+Fg2Sa4xS0RieZ4OmmdtKl4zGcmKqjt80x0rBSpioZ7Q1Z99nJ6USYN9iTX6OYHAahXRN15QWES+N8A0XxsqwtbGdYYYhAkim3xWFlkHbMZGwbPfURN56E/hp6BYzP1VADmKQLR1HuJeMYgkZ457+vLS60UNg1dRkv+PomIIAAACAU2dHn1IK+n0vmJXRAYGPRRU8OY/fRXUFjsb/hkshfqNlnHVemPITJ/i4Kj1/EG9EgyG0IHiOnz4k0Ye3xPQWPJQo4jV77sYaqR4CS9Iqeh5HAakB8WLp4Jg2m9aFsGBr8z0oCHbMRPryq4hMVS+jvZXLtISdAxJSid3fVT2vuzA= dsa@test
DSA
DSAKEY_P = 165950620304887594884135609168463435456975030032167489524497850318194612792761362778018433743240760339575503027641394260574970055390605825840800874395623852661763134421827522256823036810841966996496533797334568474233455519295649871982835925662246744416420207654868373530423342780942185276251990645140269678657
DSAKEY_Q = 859495927093092132489021088086156249337313301659
DSAKEY_G = 120979301692404393273868117223565538404375798196259387100318771085866992172061990518837332418127252702458312741391664776201274497267406391122833354561436140439474680868904068235236089129980638892504547055285487884710265926302915559650739333104897349348589001086952911228829682594220717175440335338768026867842
DSAKEY_Y = 58567884936005064871798078338950198157960353960239817665887577731752594469778397657411784034121541953043231563718348937388900185863651451122212554930418668265333665678558476629598005155001156340620679704050209200086098295350016791427054485372747467098906953590833533792856297022284628315267194401081344899888
DSAKEY_COMMENT = "dsa@test"
def test_algorithm
key = SSHPublicKey.parse(RSAKEY)
assert_equal 'RSA', key.algorithm
end
def test_parameters_rsa
key = SSHPublicKey.parse(RSAKEY)
assert_equal RSAKEY_E, key.e
assert_equal RSAKEY_M, key.m
end
def test_comment_rsa
key = SSHPublicKey.parse(RSAKEY)
assert_equal 'rsa@test', key.comment
end
def test_round_trip_rsa
key = SSHPublicKey::RSAPublicKey.new(
:e => RSAKEY_E,
:m => RSAKEY_M,
:comment => RSAKEY_COMMENT)
rtkey = SSHPublicKey.parse(key.to_s)
assert_equal RSAKEY, key.to_s
assert_equal key.algorithm, rtkey.algorithm
assert_equal key.e, rtkey.e
assert_equal key.m, rtkey.m
assert_equal key.comment, rtkey.comment
end
def test_algorithm_dsa
key = SSHPublicKey.parse(DSAKEY)
assert_equal 'DSA', key.algorithm
end
def test_parameters_dsa
key = SSHPublicKey.parse(DSAKEY)
assert_equal DSAKEY_P, key.p
assert_equal DSAKEY_Q, key.q
assert_equal DSAKEY_G, key.g
assert_equal DSAKEY_Y, key.y
end
def test_comment_dsa
key = SSHPublicKey.parse(DSAKEY)
assert_equal 'dsa@test', key.comment
end
def test_round_trip_dsa
key = SSHPublicKey::DSAPublicKey.new(
:p => DSAKEY_P,
:q => DSAKEY_Q,
:g => DSAKEY_G,
:y => DSAKEY_Y,
:comment => DSAKEY_COMMENT)
rtkey = SSHPublicKey.parse(key.to_s)
assert_equal DSAKEY, key.to_s
assert_equal key.algorithm, rtkey.algorithm
assert_equal key.p, rtkey.p
assert_equal key.q, rtkey.q
assert_equal key.g, rtkey.g
assert_equal key.y, rtkey.y
assert_equal key.comment, rtkey.comment
end
end
| bsd-3-clause |
littlesmilelove/NLog | tests/NLog.UnitTests/Internal/NetworkSenders/TcpNetworkSenderTests.cs | 14480 | //
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Internal.NetworkSenders
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using NLog.Internal.NetworkSenders;
using Xunit;
public class TcpNetworkSenderTests : NLogTestBase
{
[Fact]
public void TcpHappyPathTest()
{
foreach (bool async in new[] { false, true })
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
Async = async,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new List<Exception>();
for (int i = 1; i < 8; i *= 2)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions) exceptions.Add(ex);
});
}
var mre = new ManualResetEvent(false);
sender.FlushAsync(ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
}
mre.Set();
});
mre.WaitOne();
var actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1);
mre.Reset();
for (int i = 1; i < 8; i *= 2)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions) exceptions.Add(ex);
});
}
sender.Close(ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
}
mre.Set();
});
mre.WaitOne();
actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1);
Assert.True(actual.IndexOf("close") != -1);
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
}
}
[Fact]
public void TcpProxyTest()
{
var sender = new TcpNetworkSender("tcp://foo:1234", AddressFamily.Unspecified);
var socket = sender.CreateSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Assert.IsType(typeof(SocketProxy), socket);
}
[Fact]
public void TcpConnectFailureTest()
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
ConnectFailure = 1,
Async = true,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new List<Exception>();
var allSent = new ManualResetEvent(false);
for (int i = 1; i < 8; i++)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (exceptions.Count == 7)
{
allSent.Set();
}
}
});
}
Assert.True(allSent.WaitOne(3000, false));
var mre = new ManualResetEvent(false);
sender.FlushAsync(ex => mre.Set());
mre.WaitOne(3000, false);
var actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("failed") != -1);
foreach (var ex in exceptions)
{
Assert.NotNull(ex);
}
}
[Fact]
public void TcpSendFailureTest()
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
SendFailureIn = 3, // will cause failure on 3rd send
Async = true,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new Exception[9];
var writeFinished = new ManualResetEvent(false);
int remaining = exceptions.Length;
for (int i = 1; i < 10; i++)
{
int pos = i - 1;
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions)
{
exceptions[pos] = ex;
if (--remaining == 0)
{
writeFinished.Set();
}
}
});
}
var mre = new ManualResetEvent(false);
writeFinished.WaitOne();
sender.Close(ex => mre.Set());
mre.WaitOne();
var actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 3 'qui'") != -1);
Assert.True(actual.IndexOf("failed") != -1);
Assert.True(actual.IndexOf("close") != -1);
for (int i = 0; i < exceptions.Length; ++i)
{
if (i < 2)
{
Assert.Null(exceptions[i]);
}
else
{
Assert.NotNull(exceptions[i]);
}
}
}
internal class MyTcpNetworkSender : TcpNetworkSender
{
public StringWriter Log { get; set; }
public MyTcpNetworkSender(string url, AddressFamily addressFamily)
: base(url, addressFamily)
{
this.Log = new StringWriter();
}
protected internal override ISocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
return new MockSocket(addressFamily, socketType, protocolType, this);
}
protected override EndPoint ParseEndpointAddress(Uri uri, AddressFamily addressFamily)
{
this.Log.WriteLine("Parse endpoint address {0} {1}", uri, addressFamily);
return new MockEndPoint(uri);
}
public int ConnectFailure { get; set; }
public bool Async { get; set; }
public int SendFailureIn { get; set; }
}
internal class MockSocket : ISocket
{
private readonly MyTcpNetworkSender sender;
private readonly StringWriter log;
private bool faulted = false;
public MockSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, MyTcpNetworkSender sender)
{
this.sender = sender;
this.log = sender.Log;
this.log.WriteLine("create socket {0} {1} {2}", addressFamily, socketType, protocolType);
}
public bool ConnectAsync(SocketAsyncEventArgs args)
{
this.log.WriteLine("connect async to {0}", args.RemoteEndPoint);
lock (this)
{
if (this.sender.ConnectFailure > 0)
{
this.sender.ConnectFailure--;
this.faulted = true;
args.SocketError = SocketError.SocketError;
this.log.WriteLine("failed");
}
}
return InvokeCallback(args);
}
private bool InvokeCallback(SocketAsyncEventArgs args)
{
lock (this)
{
var args2 = args as TcpNetworkSender.MySocketAsyncEventArgs;
if (this.sender.Async)
{
ThreadPool.QueueUserWorkItem(s =>
{
Thread.Sleep(10);
args2.RaiseCompleted();
});
return true;
}
else
{
return false;
}
}
}
public void Close()
{
lock (this)
{
this.log.WriteLine("close");
}
}
public bool SendAsync(SocketAsyncEventArgs args)
{
lock (this)
{
this.log.WriteLine("send async {0} {1} '{2}'", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count));
if (this.sender.SendFailureIn > 0)
{
this.sender.SendFailureIn--;
if (this.sender.SendFailureIn == 0)
{
this.faulted = true;
}
}
if (this.faulted)
{
this.log.WriteLine("failed");
args.SocketError = SocketError.SocketError;
}
}
return InvokeCallback(args);
}
public bool SendToAsync(SocketAsyncEventArgs args)
{
lock (this)
{
this.log.WriteLine("sendto async {0} {1} '{2}' {3}", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count), args.RemoteEndPoint);
return InvokeCallback(args);
}
}
}
internal class MockEndPoint : EndPoint
{
private readonly Uri uri;
public MockEndPoint(Uri uri)
{
this.uri = uri;
}
public override AddressFamily AddressFamily
{
get
{
return (System.Net.Sockets.AddressFamily)10000;
}
}
public override string ToString()
{
return "{mock end point: " + this.uri + "}";
}
}
}
}
| bsd-3-clause |
mhrivnak/ObservingReports | views/main_page.py | 567 | import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class MainPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
url = users.create_logout_url(self.request.uri)
else:
url = ''
context = {
'logout_url' : url,
}
path = os.path.join(os.path.dirname(__file__) + '/../templates/', 'index.html')
self.response.out.write(template.render(path, context))
| bsd-3-clause |
coupling/spree_mailchimp | lib/spree_mailchimp.rb | 103 | require 'spree_core'
require 'spree_mailchimp/engine'
require 'spree/mail_chimp_sync'
require 'hominid' | bsd-3-clause |
cfcastillol/sigym | views/tipodocumento/_form.php | 657 | <?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Tipodocumento */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="tipodocumento-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'abreviatura')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'tipodocumento')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Crear' : 'Actualizar', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| bsd-3-clause |
jannon/sorl-thumbnail | docs/conf.py | 7517 | # -*- coding: utf-8 -*-
#
# sorl-thumbnail documentation build configuration file, created by
# sphinx-quickstart on Fri Nov 12 00:51:21 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
import sphinx
import sys
sys.path.insert(0, os.path.pardir)
import sorl
for j in xrange(0, len(sphinx.__version__)):
try:
version = float(sphinx.__version__[:-j])
break
except ValueError:
pass
version = 0
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
if version < 1.0:
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage']
else:
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'sorl-thumbnail'
copyright = u'2010, Mikko Hellsing'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = sorl.__version__
# The full version, including alpha/beta/rc tags.
release = sorl.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = ['_theme']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'sorlthumbnaildoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
# latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
# latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'sorlthumbnail.tex', u'sorl-thumbnail Documentation',
u'Mikko Hellsing', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Additional stuff for the LaTeX preamble.
# latex_preamble = ''
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'sorlthumbnail', u'sorl-thumbnail Documentation',
[u'Mikko Hellsing'], 1)
]
| bsd-3-clause |
uthando-cms/uthando-theme-manager | src/UthandoThemeManager/Event/ConfigListener.php | 2325 | <?php declare(strict_types=1);
/**
* Uthando CMS (http://www.shaunfreeman.co.uk/)
*
* @author Shaun Freeman <shaun@shaunfreeman.co.uk>
* @link https://github.com/uthando-cms for the canonical source repository
* @copyright Copyright (c) 19/09/17 Shaun Freeman. (http://www.shaunfreeman.co.uk)
* @license see LICENSE
*/
namespace UthandoThemeManager\Event;
use AssetManager\Cache\FilePathCache;
use UthandoThemeManager\Filter\CssMinFilter;
use UthandoThemeManager\Filter\JsMinFilter;
use UthandoThemeManager\Options\ThemeOptions;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\EventManager\ListenerAggregateTrait;
use Zend\ModuleManager\ModuleEvent;
use Zend\Stdlib\ArrayUtils;
class ConfigListener implements ListenerAggregateInterface
{
use ListenerAggregateTrait;
public function attach(EventManagerInterface $events)
{
$this->listeners[] = $events->attach(ModuleEvent::EVENT_MERGE_CONFIG, [$this, 'onMergeConfig'], 1);
}
public function onMergeConfig(ModuleEvent $event): ConfigListener
{
$configListener = $event->getConfigListener();
$config = $configListener->getMergedConfig(false);
$options = new ThemeOptions($config['uthando_theme_manager'] ?? []);
$assetManager = [];
if ($options->getCache()) {
$assetManager['asset_manager']['caching']['default'] = [
'cache' => FilePathCache::class,
'options' => [
'dir' => $options->getPublicDir(),
],
];
}
if ($options->isCompressCss()) {
$assetManager['asset_manager']['filters']['css'][] = [
'filter' => CssMinFilter::class,
];
}
if ($options->isCompressCss()) {
$assetManager['asset_manager']['filters']['js'][] = [
'filter' => JSMinFilter::class,
];
}
if ($options->getThemePath()) {
$assetManager['asset_manager']['resolver_configs']['paths']['ThemeManager'] = $options->getThemePath();
}
$config = ArrayUtils::merge($config, $assetManager);
$configListener->setMergedConfig($config);
return $this;
}
}
| bsd-3-clause |
happykejie/github_yii2buildcuxiaodadiaochaproject | models/WexinApi.php | 3882 | <?php
namespace app\models;
use Yii;
/**
* This is the model class for table "{{%msg}}".
*
* @property integer $id
* @property integer $fid
* @property integer $tid
* @property string $title
* @property string $content
* @property integer $status
* @property integer $send_time
* @property integer $replay
*/
class WeixinLogin extends \yii\db\ActiveRecord
{
private $WX_APPID = WX_APPID; ///张杰开发测试账号wxf861f60fbb144cb9 //李朝先wxe474c6e60ea8f0c8
private $WX_APPSECRET = WX_APPSECRET; //张杰开发测试账号2da66bd2cf0dccf0fb8d5db1e3ca6122 //李朝先33b1241f97a2803440b34bf30c33d57e
private $_openid ,$_access_token,$_wxuser,$_user,$_users;
public $accesstoken,$js_tiket;
public function getWxUserOpenId()
{
$appid = WX_APPID;
$secret = WX_APPSECRET;
$code = $_GET["code"];
//第一步:取得openid
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$oauth2 = $this->getJson($oauth2Url);
return $oauth2['openid'];
}
/*
* 获取微信accesstoken
*/
public function getWxAccessToken()
{
$appid = WX_APPID;
$secret = WX_APPSECRET;
$id ='accesstoken';
$value=Yii::app()->cache->get($id);
if($value===false)
{
$oauth2Url = "https://api.weixin.qq.com/cgi-bin/token?appid=$appid&secret=$secret&grant_type=client_credential";
$oauth2 = $this->getJson($oauth2Url);
$accesstoken =$oauth2["access_token"];
Yii::app()->cache->set($id, $accesstoken, 7200);
}
return $value;
}
public function getSingwx()
{
// 签名,将jsapi_ticket、noncestr、timestamp、分享的url按字母顺序连接起来,进行sha1签名。
// noncestr是你设置的任意字符串。
// timestamp为时间戳。
$timestamp = time();
$wxnonceStr = "2nDgiWM7gCxhL8v0";//与js wx.comfig 配置文件一致。
$wxticket = getJsapi_ticket();
$wxOri = sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s",
$wxticket, $wxnonceStr, $timestamp,
'http://kejie.wipc.net/wxjssdk'
);
$signature = sha1($wxOri);
return $signature;
}
/*
* 获取微信jsapi_ticket
*/
public function getJsapi_ticket()
{
$a_token = getWxAccessToken(); ///得到accesstoken
$id ='js_ticket';
$value=Yii::app()->cache->get($id);
if($value===false)
{
$jsticket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$a_token&type=jsapi";
$json_jsticket = $this->getJson($jsticket);
if($json_jsticket["errmsg"]=='ok')
{
$jstiket =$json_jsticket["ticket"];
Yii::app()->cache->set($id, $jstiket, 7200);
}
}
return $value;
}
public function getWxUserinfo($_access_token,$_openid){
$get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$_access_token."&openid=".$_openid."&lang=zh_CN ";
$wxuserinfo =$this->getJson($get_user_info_url);
return $wxuserinfo;
}
public function getJson($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}
}
| bsd-3-clause |
axefrog/Grasshopper | src/core-engine/Grasshopper.Procedural/Properties/AssemblyInfo.cs | 1381 | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Grasshopper.Procedural")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Grasshopper.Procedural")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("093e8aaa-8f3b-4671-a2a6-6ca4678fc8b1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| bsd-3-clause |
endlessm/chromium-browser | chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerProperties.java | 3274 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.signin.account_picker;
import androidx.annotation.IntDef;
import org.chromium.base.Callback;
import org.chromium.chrome.browser.signin.DisplayableProfileData;
import org.chromium.ui.modelutil.PropertyKey;
import org.chromium.ui.modelutil.PropertyModel;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Properties for account picker.
*/
class AccountPickerProperties {
private AccountPickerProperties() {}
/**
* Properties for "add account" row in account picker.
*/
static class AddAccountRowProperties {
static final PropertyModel.ReadableObjectPropertyKey<Runnable> ON_CLICK_LISTENER =
new PropertyModel.ReadableObjectPropertyKey<>("on_click_listener");
static final PropertyKey[] ALL_KEYS = new PropertyKey[] {ON_CLICK_LISTENER};
private AddAccountRowProperties() {}
static PropertyModel createModel(Runnable runnableAddAccount) {
return new PropertyModel.Builder(ALL_KEYS)
.with(ON_CLICK_LISTENER, runnableAddAccount)
.build();
}
}
/**
* Properties for account row in account picker.
*/
static class ExistingAccountRowProperties {
static final PropertyModel.ReadableObjectPropertyKey<DisplayableProfileData> PROFILE_DATA =
new PropertyModel.ReadableObjectPropertyKey<>("profile_data");
static final PropertyModel.WritableBooleanPropertyKey IS_SELECTED_ACCOUNT =
new PropertyModel.WritableBooleanPropertyKey("is_selected_account");
static final PropertyModel
.ReadableObjectPropertyKey<Callback<DisplayableProfileData>> ON_CLICK_LISTENER =
new PropertyModel.ReadableObjectPropertyKey<>("on_click_listener");
static final PropertyKey[] ALL_KEYS =
new PropertyKey[] {PROFILE_DATA, IS_SELECTED_ACCOUNT, ON_CLICK_LISTENER};
private ExistingAccountRowProperties() {}
static PropertyModel createModel(DisplayableProfileData profileData,
Callback<DisplayableProfileData> listener, boolean isSelectedAccount) {
return new PropertyModel.Builder(ALL_KEYS)
.with(PROFILE_DATA, profileData)
.with(IS_SELECTED_ACCOUNT, isSelectedAccount)
.with(ON_CLICK_LISTENER, listener)
.build();
}
}
/**
* Item types of account picker.
*/
@IntDef({ItemType.EXISTING_ACCOUNT_ROW, ItemType.ADD_ACCOUNT_ROW})
@Retention(RetentionPolicy.SOURCE)
@interface ItemType {
/**
* Item type for models created with {@link ExistingAccountRowProperties#createModel} and
* use {@link ExistingAccountRowViewBinder} for view setup.
*/
int EXISTING_ACCOUNT_ROW = 1;
/**
* Item type for models created with {@link AddAccountRowProperties#createModel} and
* use {@link AddAccountRowViewBinder} for view setup.
*/
int ADD_ACCOUNT_ROW = 2;
}
}
| bsd-3-clause |
Nerufa/Nerufio | src/Nerufio/Mvc/Manager.php | 5311 | <?php
/**
* Nerufio PHP Framework
* @link http://nerufa.ru/nerufio
* @copyright 2012-2015 Nerufa
* @license New BSD License
*/
namespace Nerufio\Mvc;
use Nerufio\Core\Autoloader;
use Nerufio\Core\Exception\Emergency;
use Nerufio\Helpers\Arrays;
use Nerufio\Helpers\Text;
use Nerufio\Mvc\Interfaces\Controller;
use Nerufio\Mvc\Model\Interfaces\Component;
/**
* Class Manager
*
* Usage Settings:
*
* Nerufio[Mvc][Routing]
*
* @package Nerufio\Mvc
* @author Ilya Krasheninnikov
*/
final class Manager
{
/**
* The name of current controller
* @static
* @var string
*/
private static $_call;
/**
* The name of the controller by default
* @static
* @var string
*/
private static $_default = 'Controllers\Index';
/**
* Load the controller
* @static
* @param string $name <p>The name of the controller</p>
* @param array $params [optional] <p>The passed params (request uri)</p>
* @param string $content [optional] <p>The content</p>
* @throws Emergency a class must implements interface
* @return null|object
*/
public static function LoadController($name, array $params = array(), $content = null)
{
$name = trim($name, '\\');
self::$_call = $name;
$controller = Autoloader::GetNewInstance($name, array($params, $content));
if (!is_subclass_of($controller, 'Nerufio\Mvc\Controller\Actions')) {
throw new Emergency(sprintf('Class \'%s\' must extended of \'Nerufio\Mvc\Controller\Actions\'',
$name));
}
return $controller;
}
/**
* Checking whether is it a module
* @param string $name <p>The name of the controller</p>
* @return bool
* @since 3.0.2
*/
public static function IsModule($name)
{
return (bool)preg_match('/^Modules/i', $name);
}
/**
* Set the default controller
* @static
* @param string $name <p>The name of the controller</p>
* @throws Emergency class not exists
* @return void
*/
public static function SetDefaultController($name)
{
if (!class_exists($name)) {
throw new Emergency(sprintf('Class \'%s\' isn\'t exists', $name));
}
self::$_default = $name;
}
/**
* Get the name controller by default
* @static
* @return string
*/
public static function GetDefaultController()
{
return self::$_default;
}
/**
* Checking whether there is a controller
* @static
* @param Controller $controller
* @param bool $namespace [optional] <p>Flag used for return namespace of the controller</p>
* @return bool
*/
public static function ExistController(Controller &$controller, $namespace = false)
{
$controller_name = Text::UpFirstSymbol($controller->GetParam(0));
$ns = Text::NsToArray($controller->GetName());
if (self::IsModule($controller->GetName())) {
$ns_controller = 'Modules\\' . Arrays::Get(1, $ns) . '\Controllers\\' . $controller_name;
} else {
$ns_controller = 'Controllers\\' . $controller_name;
}
try {
$exists = class_exists($ns_controller);
} catch (\Exception $e) {
$exists = false;
}
return ($namespace) ? (($exists) ? $ns_controller : '') : $exists;
}
/**
* Get the name of the current controller
* @static
* @return string
*/
public static function GetCall()
{
return self::$_call;
}
/**
* Called action in passed object
* @static
* @param object $object <p>An object</p>
* @param string $action <p>The name of the action</p>
* @param array $args [optional] <p>Passed arguments</p>
* @return bool
*/
public static function CallAction(&$object, $action, array $args = array())
{
$action = 'action' . ucfirst($action);
if (is_object($object)) {
$class = new \ReflectionClass($object);
if ($class->hasMethod($action)) {
$method = $class->getMethod($action);
$method->setAccessible(true);
$method->invokeArgs($object, $args);
return true;
}
}
return false;
}
/**
* Called action in passed object of the model
* @static
* @param Component $object
* @param string $action [optional] <p>The name of the action</p>
* @param array $args [optional] <p>Passed arguments</p>
* @return int new status of model
*/
public static function CallActionModel(
Component &$object,
$action,
array $args = array()
) {
$action_model = $object->GetModelAction();
$status = $action_model->GetStatus();
$result = self::CallAction($object, $action, $args);
if ($result === false) {
$result = self::CallAction($object, 'Default', $args);
$status = $action_model::STATUS_DEFAULT;
}
if ($result === false) {
$object->GetModelAction()->SetStatusFalse();
$status = $action_model::STATUS_FALSE;
}
return $status;
}
}
| bsd-3-clause |
tartakynov/enso | enso/platform/win32/taskbar/__init__.py | 21 | from taskbar import * | bsd-3-clause |
lordadamson/opentoonz | toonz/sources/tnztools/brushtool.cpp | 80232 |
#include "brushtool.h"
#include <map>
// TnzTools includes
#include "tools/toolhandle.h"
#include "tools/toolutils.h"
#include "tools/tooloptions.h"
#include "bluredbrush.h"
// TnzQt includes
#include "toonzqt/dvdialog.h"
#include "toonzqt/imageutils.h"
// TnzLib includes
#include "toonz/tobjecthandle.h"
#include "toonz/txsheethandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/tframehandle.h"
#include "toonz/tcolumnhandle.h"
#include "toonz/txsheet.h"
#include "toonz/tstageobject.h"
#include "toonz/tstageobjectspline.h"
#include "toonz/rasterstrokegenerator.h"
#include "toonz/ttileset.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/toonzimageutils.h"
#include "toonz/palettecontroller.h"
#include "toonz/tpalettehandle.h"
#include "toonz/stage2.h"
#include "toonz/animationautocomplete.h"
// TnzCore includes
#include "tstream.h"
#include "tcolorstyles.h"
#include "tvectorimage.h"
#include "tenv.h"
#include "tregion.h"
#include "tstroke.h"
#include "tvectorimage.h"
#include "tgl.h"
#include "trop.h"
#include "drawutil.h"
#include "tvectorbrushstyle.h"
// Qt includes
#include <QPainter>
using namespace ToolUtils;
TEnv::DoubleVar VectorBrushMinSize("InknpaintVectorBrushMinSize", 1);
TEnv::DoubleVar VectorBrushMaxSize("InknpaintVectorBrushMaxSize", 5);
TEnv::IntVar VectorCapStyle("InknpaintVectorCapStyle", 1);
TEnv::IntVar VectorJoinStyle("InknpaintVectorJoinStyle", 1);
TEnv::IntVar VectorMiterValue("InknpaintVectorMiterValue", 4);
TEnv::DoubleVar RasterBrushMinSize("InknpaintRasterBrushMinSize", 1);
TEnv::DoubleVar RasterBrushMaxSize("InknpaintRasterBrushMaxSize", 5);
TEnv::DoubleVar BrushAccuracy("InknpaintBrushAccuracy", 20);
TEnv::DoubleVar BrushSmooth("InknpaintBrushSmooth", 0);
TEnv::IntVar BrushSelective("InknpaintBrushSelective", 0);
TEnv::IntVar BrushBreakSharpAngles("InknpaintBrushBreakSharpAngles", 0);
TEnv::IntVar RasterBrushPencilMode("InknpaintRasterBrushPencilMode", 0);
TEnv::IntVar BrushPressureSensitivity("InknpaintBrushPressureSensitivity", 1);
TEnv::DoubleVar RasterBrushHardness("RasterBrushHardness", 100);
//-------------------------------------------------------------------
#define ROUNDC_WSTR L"round_cap"
#define BUTT_WSTR L"butt_cap"
#define PROJECTING_WSTR L"projecting_cap"
#define ROUNDJ_WSTR L"round_join"
#define BEVEL_WSTR L"bevel_join"
#define MITER_WSTR L"miter_join"
#define CUSTOM_WSTR L"<custom>"
//-------------------------------------------------------------------
//
// (Da mettere in libreria) : funzioni che spezzano una stroke
// nei suoi punti angolosi. Lo facciamo specialmente per limitare
// i problemi di fill.
//
//-------------------------------------------------------------------
//
// Split a stroke in n+1 parts, according to n parameter values
// Input:
// stroke = stroke to split
// parameterValues[] = vector of parameters where I want to split the
// stroke
// assert: 0<a[0]<a[1]<...<a[n-1]<1
// Output:
// strokes[] = the split strokes
//
// note: stroke is unchanged
//
static void split(TStroke *stroke, const std::vector<double> ¶meterValues,
std::vector<TStroke *> &strokes) {
TThickPoint p2;
std::vector<TThickPoint> points;
TThickPoint lastPoint = stroke->getControlPoint(0);
int n = parameterValues.size();
int chunk;
double t;
int last_chunk = -1, startPoint = 0;
double lastLocT = 0;
for (int i = 0; i < n; i++) {
points.push_back(lastPoint); // Add first point of the stroke
double w =
parameterValues[i]; // Global parameter. along the stroke 0<=w<=1
stroke->getChunkAndT(w, chunk,
t); // t: local parameter in the chunk-th quadratic
if (i == 0)
startPoint = 1;
else {
int indexAfterLastT =
stroke->getControlPointIndexAfterParameter(parameterValues[i - 1]);
startPoint = indexAfterLastT;
if ((indexAfterLastT & 1) && lastLocT != 1) startPoint++;
}
int endPoint = 2 * chunk + 1;
if (lastLocT != 1 && i > 0) {
if (last_chunk != chunk || t == 1)
points.push_back(p2); // If the last local t is not an extreme
// add the point p2
}
for (int j = startPoint; j < endPoint; j++)
points.push_back(stroke->getControlPoint(j));
TThickPoint p, A, B, C;
p = stroke->getPoint(w);
C = stroke->getControlPoint(2 * chunk + 2);
B = stroke->getControlPoint(2 * chunk + 1);
A = stroke->getControlPoint(2 * chunk);
p.thick = A.thick;
if (last_chunk != chunk) {
TThickPoint p1 = (1 - t) * A + t * B;
points.push_back(p1);
p.thick = p1.thick;
} else {
if (t != 1) {
// If the i-th cut point belong to the same chunk of the (i-1)-th cut
// point.
double tInters = lastLocT / t;
TThickPoint p11 = (1 - t) * A + t * B;
TThickPoint p1 = (1 - tInters) * p11 + tInters * p;
points.push_back(p1);
p.thick = p1.thick;
}
}
points.push_back(p);
if (t != 1) p2 = (1 - t) * B + t * C;
assert(points.size() & 1);
// Add new stroke
TStroke *strokeAdd = new TStroke(points);
strokeAdd->setStyle(stroke->getStyle());
strokeAdd->outlineOptions() = stroke->outlineOptions();
strokes.push_back(strokeAdd);
lastPoint = p;
last_chunk = chunk;
lastLocT = t;
points.clear();
}
// Add end stroke
points.push_back(lastPoint);
if (lastLocT != 1) points.push_back(p2);
startPoint =
stroke->getControlPointIndexAfterParameter(parameterValues[n - 1]);
if ((stroke->getControlPointIndexAfterParameter(parameterValues[n - 1]) &
1) &&
lastLocT != 1)
startPoint++;
for (int j = startPoint; j < stroke->getControlPointCount(); j++)
points.push_back(stroke->getControlPoint(j));
assert(points.size() & 1);
TStroke *strokeAdd = new TStroke(points);
strokeAdd->setStyle(stroke->getStyle());
strokeAdd->outlineOptions() = stroke->outlineOptions();
strokes.push_back(strokeAdd);
points.clear();
}
// Compute Parametric Curve Curvature
// By Formula:
// k(t)=(|p'(t) x p''(t)|)/Norm2(p')^3
// p(t) is parametric curve
// Input:
// dp = First Derivate.
// ddp = Second Derivate
// Output:
// return curvature value.
// Note: if the curve is a single point (that's dp=0) or it is a straight
// line (that's ddp=0) return 0
static double curvature(TPointD dp, TPointD ddp) {
if (dp == TPointD(0, 0))
return 0;
else
return fabs(cross(dp, ddp) / pow(norm2(dp), 1.5));
}
// Find the max curvature points of a stroke.
// Input:
// stroke.
// angoloLim = Value (radians) of the Corner between two tangent vector.
// Up this value the two corner can be considered angular.
// curvMaxLim = Value of the max curvature.
// Up this value the point can be considered a max curvature
// point.
// Output:
// parameterValues = vector of max curvature parameter points
static void findMaxCurvPoints(TStroke *stroke, const float &angoloLim,
const float &curvMaxLim,
std::vector<double> ¶meterValues) {
TPointD tg1, tg2; // Tangent vectors
TPointD dp, ddp; // First and Second derivate.
parameterValues.clear();
int cpn = stroke ? stroke->getControlPointCount() : 0;
for (int j = 2; j < cpn; j += 2) {
TPointD p0 = stroke->getControlPoint(j - 2);
TPointD p1 = stroke->getControlPoint(j - 1);
TPointD p2 = stroke->getControlPoint(j);
TPointD q = p1 - (p0 + p2) * 0.5;
// Search corner point
if (j > 2) {
tg2 = -p0 + p2 + 2 * q; // Tangent vector to this chunk at t=0
double prod_scal =
tg2 * tg1; // Inner product between tangent vectors at t=0.
assert(tg1 != TPointD(0, 0) || tg2 != TPointD(0, 0));
// Compute corner between two tangent vectors
double angolo =
acos(prod_scal / (pow(norm2(tg2), 0.5) * pow(norm2(tg1), 0.5)));
// Add corner point
if (angolo > angoloLim) {
double w = getWfromChunkAndT(stroke, (UINT)(0.5 * (j - 2)),
0); // transform lacal t to global t
parameterValues.push_back(w);
}
}
tg1 = -p0 + p2 - 2 * q; // Tangent vector to this chunk at t=1
// End search corner point
// Search max curvature point
// Value of t where the curvature function has got an extreme.
// (Point where first derivate is null)
double estremo_int = 0;
double t = -1;
if (q != TPointD(0, 0)) {
t = 0.25 * (2 * q.x * q.x + 2 * q.y * q.y - q.x * p0.x + q.x * p2.x -
q.y * p0.y + q.y * p2.y) /
(q.x * q.x + q.y * q.y);
dp = -p0 + p2 + 2 * q - 4 * t * q; // First derivate of the curve
ddp = -4 * q; // Second derivate of the curve
estremo_int = curvature(dp, ddp);
double h = 0.01;
dp = -p0 + p2 + 2 * q - 4 * (t + h) * q;
double c_dx = curvature(dp, ddp);
dp = -p0 + p2 + 2 * q - 4 * (t - h) * q;
double c_sx = curvature(dp, ddp);
// Check the point is a max and not a minimum
if (estremo_int < c_dx && estremo_int < c_sx) {
estremo_int = 0;
}
}
double curv_max = estremo_int;
// Compute curvature at the extreme of interval [0,1]
// Compute curvature at t=0 (Left extreme)
dp = -p0 + p2 + 2 * q;
double estremo_sx = curvature(dp, ddp);
// Compute curvature at t=1 (Right extreme)
dp = -p0 + p2 - 2 * q;
double estremo_dx = curvature(dp, ddp);
// Compare curvature at the extreme of interval [0,1] with the internal
// value
double t_ext;
if (estremo_sx >= estremo_dx)
t_ext = 0;
else
t_ext = 1;
double maxEstremi = std::max(estremo_dx, estremo_sx);
if (maxEstremi > estremo_int) {
t = t_ext;
curv_max = maxEstremi;
}
// Add max curvature point
if (t >= 0 && t <= 1 && curv_max > curvMaxLim) {
double w = getWfromChunkAndT(stroke, (UINT)(0.5 * (j - 2)),
t); // transform local t to global t
parameterValues.push_back(w);
}
// End search max curvature point
}
// Delete duplicate of parameterValues
// Because some max cuvature point can coincide with the corner point
if ((int)parameterValues.size() > 1) {
std::sort(parameterValues.begin(), parameterValues.end());
parameterValues.erase(
std::unique(parameterValues.begin(), parameterValues.end()),
parameterValues.end());
}
}
static void addStroke(TTool::Application *application, const TVectorImageP &vi,
TStroke *stroke, bool breakAngles, bool frameCreated,
bool levelCreated) {
QMutexLocker lock(vi->getMutex());
if (application->getCurrentObject()->isSpline()) {
application->getCurrentXsheet()->notifyXsheetChanged();
return;
}
std::vector<double> corners;
std::vector<TStroke *> strokes;
const float angoloLim =
1; // Value (radians) of the Corner between two tangent vector.
// Up this value the two corner can be considered angular.
const float curvMaxLim = 0.8; // Value of the max curvature.
// Up this value the point can be considered a max curvature point.
findMaxCurvPoints(stroke, angoloLim, curvMaxLim, corners);
TXshSimpleLevel *sl = application->getCurrentLevel()->getSimpleLevel();
TFrameId id = application->getCurrentTool()->getTool()->getCurrentFid();
if (!corners.empty()) {
if (breakAngles)
split(stroke, corners, strokes);
else
strokes.push_back(new TStroke(*stroke));
int n = strokes.size();
TUndoManager::manager()->beginBlock();
for (int i = 0; i < n; i++) {
std::vector<TFilledRegionInf> *fillInformation =
new std::vector<TFilledRegionInf>;
ImageUtils::getFillingInformationOverlappingArea(vi, *fillInformation,
stroke->getBBox());
TStroke *str = new TStroke(*strokes[i]);
vi->addStroke(str);
TUndoManager::manager()->add(new UndoPencil(str, fillInformation, sl, id,
frameCreated, levelCreated));
}
TUndoManager::manager()->endBlock();
} else {
std::vector<TFilledRegionInf> *fillInformation =
new std::vector<TFilledRegionInf>;
ImageUtils::getFillingInformationOverlappingArea(vi, *fillInformation,
stroke->getBBox());
TStroke *str = new TStroke(*stroke);
vi->addStroke(str);
TUndoManager::manager()->add(new UndoPencil(str, fillInformation, sl, id,
frameCreated, levelCreated));
}
// Update regions. It will call roundStroke() in
// TVectorImage::Imp::findIntersections().
// roundStroke() will slightly modify all the stroke positions.
// It is needed to update information for Fill Check.
vi->findRegions();
for (int k = 0; k < (int)strokes.size(); k++) delete strokes[k];
strokes.clear();
application->getCurrentTool()->getTool()->notifyImageChanged();
}
//-------------------------------------------------------------------
//
// Gennaro: end
//
//-------------------------------------------------------------------
//===================================================================
//
// Helper functions and classes
//
//-------------------------------------------------------------------
namespace {
//-------------------------------------------------------------------
void addStrokeToImage(TTool::Application *application, const TVectorImageP &vi,
TStroke *stroke, bool breakAngles, bool frameCreated,
bool levelCreated) {
QMutexLocker lock(vi->getMutex());
addStroke(application, vi.getPointer(), stroke, breakAngles, frameCreated,
levelCreated);
// la notifica viene gia fatta da addStroke!
// getApplication()->getCurrentTool()->getTool()->notifyImageChanged();
}
//=========================================================================================================
class RasterBrushUndo final : public TRasterUndo {
std::vector<TThickPoint> m_points;
int m_styleId;
bool m_selective;
bool m_isPencil;
public:
RasterBrushUndo(TTileSetCM32 *tileSet, const std::vector<TThickPoint> &points,
int styleId, bool selective, TXshSimpleLevel *level,
const TFrameId &frameId, bool isPencil, bool isFrameCreated,
bool isLevelCreated)
: TRasterUndo(tileSet, level, frameId, isFrameCreated, isLevelCreated, 0)
, m_points(points)
, m_styleId(styleId)
, m_selective(selective)
, m_isPencil(isPencil) {}
void redo() const override {
insertLevelAndFrameIfNeeded();
TToonzImageP image = getImage();
TRasterCM32P ras = image->getRaster();
RasterStrokeGenerator m_rasterTrack(
ras, BRUSH, NONE, m_styleId, m_points[0], m_selective, 0, !m_isPencil);
m_rasterTrack.setPointsSequence(m_points);
m_rasterTrack.generateStroke(m_isPencil);
image->setSavebox(image->getSavebox() +
m_rasterTrack.getBBox(m_rasterTrack.getPointsSequence()));
ToolUtils::updateSaveBox();
TTool::getApplication()->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
int getSize() const override {
return sizeof(*this) + TRasterUndo::getSize();
}
QString getToolName() override { return QString("Brush Tool"); }
int getHistoryType() override { return HistoryType::BrushTool; }
};
//=========================================================================================================
class RasterBluredBrushUndo final : public TRasterUndo {
std::vector<TThickPoint> m_points;
int m_styleId;
bool m_selective;
int m_maxThick;
double m_hardness;
public:
RasterBluredBrushUndo(TTileSetCM32 *tileSet,
const std::vector<TThickPoint> &points, int styleId,
bool selective, TXshSimpleLevel *level,
const TFrameId &frameId, int maxThick, double hardness,
bool isFrameCreated, bool isLevelCreated)
: TRasterUndo(tileSet, level, frameId, isFrameCreated, isLevelCreated, 0)
, m_points(points)
, m_styleId(styleId)
, m_selective(selective)
, m_maxThick(maxThick)
, m_hardness(hardness) {}
void redo() const override {
if (m_points.size() == 0) return;
insertLevelAndFrameIfNeeded();
TToonzImageP image = getImage();
TRasterCM32P ras = image->getRaster();
TRasterCM32P backupRas = ras->clone();
TRaster32P workRaster(ras->getSize());
QRadialGradient brushPad = ToolUtils::getBrushPad(m_maxThick, m_hardness);
workRaster->clear();
BluredBrush brush(workRaster, m_maxThick, brushPad, false);
std::vector<TThickPoint> points;
points.push_back(m_points[0]);
TRect bbox = brush.getBoundFromPoints(points);
brush.addPoint(m_points[0], 1);
brush.updateDrawing(ras, ras, bbox, m_styleId, m_selective);
if (m_points.size() > 1) {
points.clear();
points.push_back(m_points[0]);
points.push_back(m_points[1]);
bbox = brush.getBoundFromPoints(points);
brush.addArc(m_points[0], (m_points[1] + m_points[0]) * 0.5, m_points[1],
1, 1);
brush.updateDrawing(ras, backupRas, bbox, m_styleId, m_selective);
int i;
for (i = 1; i + 2 < (int)m_points.size(); i = i + 2) {
points.clear();
points.push_back(m_points[i]);
points.push_back(m_points[i + 1]);
points.push_back(m_points[i + 2]);
bbox = brush.getBoundFromPoints(points);
brush.addArc(m_points[i], m_points[i + 1], m_points[i + 2], 1, 1);
brush.updateDrawing(ras, backupRas, bbox, m_styleId, m_selective);
}
}
ToolUtils::updateSaveBox();
TTool::getApplication()->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
int getSize() const override {
return sizeof(*this) + TRasterUndo::getSize();
}
QString getToolName() override { return QString("Brush Tool"); }
int getHistoryType() override { return HistoryType::BrushTool; }
};
//=========================================================================================================
double computeThickness(int pressure, const TDoublePairProperty &property,
bool isPath) {
if (isPath) return 0.0;
double p = pressure / 255.0;
double t = p * p * p;
double thick0 = property.getValue().first;
double thick1 = property.getValue().second;
if (thick1 < 0.0001) thick0 = thick1 = 0.0;
return (thick0 + (thick1 - thick0) * t) * 0.5;
}
//---------------------------------------------------------------------------------------------------------
int computeThickness(int pressure, const TIntPairProperty &property,
bool isPath) {
if (isPath) return 0.0;
double p = pressure / 255.0;
double t = p * p * p;
int thick0 = property.getValue().first;
int thick1 = property.getValue().second;
return tround(thick0 + (thick1 - thick0) * t);
}
} // namespace
//--------------------------------------------------------------------------------------------------
static void CatmullRomInterpolate(const TThickPoint &P0, const TThickPoint &P1,
const TThickPoint &P2, const TThickPoint &P3,
int samples,
std::vector<TThickPoint> &points) {
double x0 = P1.x;
double x1 = (-P0.x + P2.x) * 0.5f;
double x2 = P0.x - 2.5f * P1.x + 2.0f * P2.x - 0.5f * P3.x;
double x3 = -0.5f * P0.x + 1.5f * P1.x - 1.5f * P2.x + 0.5f * P3.x;
double y0 = P1.y;
double y1 = (-P0.y + P2.y) * 0.5f;
double y2 = P0.y - 2.5f * P1.y + 2.0f * P2.y - 0.5f * P3.y;
double y3 = -0.5f * P0.y + 1.5f * P1.y - 1.5f * P2.y + 0.5f * P3.y;
double z0 = P1.thick;
double z1 = (-P0.thick + P2.thick) * 0.5f;
double z2 = P0.thick - 2.5f * P1.thick + 2.0f * P2.thick - 0.5f * P3.thick;
double z3 =
-0.5f * P0.thick + 1.5f * P1.thick - 1.5f * P2.thick + 0.5f * P3.thick;
for (int i = 1; i <= samples; ++i) {
double t = i / (double)(samples + 1);
double t2 = t * t;
double t3 = t2 * t;
TThickPoint p;
p.x = x0 + x1 * t + x2 * t2 + x3 * t3;
p.y = y0 + y1 * t + y2 * t2 + y3 * t3;
p.thick = z0 + z1 * t + z2 * t2 + z3 * t3;
points.push_back(p);
}
}
//--------------------------------------------------------------------------------------------------
static void Smooth(std::vector<TThickPoint> &points, int radius) {
int n = (int)points.size();
if (radius < 1 || n < 3) {
return;
}
std::vector<TThickPoint> result;
float d = 1.0f / (radius * 2 + 1);
for (int i = 1; i < n - 1; ++i) {
int lower = i - radius;
int upper = i + radius;
TThickPoint total;
total.x = 0;
total.y = 0;
total.thick = 0;
for (int j = lower; j <= upper; ++j) {
int idx = j;
if (idx < 0) {
idx = 0;
} else if (idx >= n) {
idx = n - 1;
}
total.x += points[idx].x;
total.y += points[idx].y;
total.thick += points[idx].thick;
}
total.x *= d;
total.y *= d;
total.thick *= d;
result.push_back(total);
}
for (int i = 1; i < n - 1; ++i) {
points[i].x = result[i - 1].x;
points[i].y = result[i - 1].y;
points[i].thick = result[i - 1].thick;
}
if (points.size() >= 3) {
std::vector<TThickPoint> pts;
CatmullRomInterpolate(points[0], points[0], points[1], points[2], 10, pts);
std::vector<TThickPoint>::iterator it = points.begin();
points.insert(it, pts.begin(), pts.end());
pts.clear();
CatmullRomInterpolate(points[n - 3], points[n - 2], points[n - 1],
points[n - 1], 10, pts);
it = points.begin();
it += n - 1;
points.insert(it, pts.begin(), pts.end());
}
}
//--------------------------------------------------------------------------------------------------
void SmoothStroke::beginStroke(int smooth) {
m_smooth = smooth;
m_outputIndex = 0;
m_readIndex = -1;
m_rawPoints.clear();
m_outputPoints.clear();
}
//--------------------------------------------------------------------------------------------------
void SmoothStroke::addPoint(const TThickPoint &point) {
if (m_rawPoints.size() > 0 && m_rawPoints.back().x == point.x &&
m_rawPoints.back().y == point.y) {
return;
}
m_rawPoints.push_back(point);
generatePoints();
}
//--------------------------------------------------------------------------------------------------
void SmoothStroke::endStroke() {
generatePoints();
// force enable the output all segments
m_outputIndex = m_outputPoints.size() - 1;
}
//--------------------------------------------------------------------------------------------------
void SmoothStroke::getSmoothPoints(std::vector<TThickPoint> &smoothPoints) {
int n = m_outputPoints.size();
for (int i = m_readIndex + 1; i <= m_outputIndex && i < n; ++i) {
smoothPoints.push_back(m_outputPoints[i]);
}
m_readIndex = m_outputIndex;
}
//--------------------------------------------------------------------------------------------------
void SmoothStroke::generatePoints() {
int n = (int)m_rawPoints.size();
if (n == 0) {
return;
}
std::vector<TThickPoint> smoothedPoints;
// Add more stroke samples before applying the smoothing
// This is because the raw inputs points are too few to support smooth result,
// especially on stroke ends
smoothedPoints.push_back(m_rawPoints.front());
for (int i = 1; i < n; ++i) {
const TThickPoint &p1 = m_rawPoints[i - 1];
const TThickPoint &p2 = m_rawPoints[i];
const TThickPoint &p0 = i - 2 >= 0 ? m_rawPoints[i - 2] : p1;
const TThickPoint &p3 = i + 1 < n ? m_rawPoints[i + 1] : p2;
int samples = 8;
CatmullRomInterpolate(p0, p1, p2, p3, samples, smoothedPoints);
smoothedPoints.push_back(p2);
}
// Apply the 1D box filter
// Multiple passes result in better quality and fix the stroke ends break
// issue
for (int i = 0; i < 3; ++i) {
Smooth(smoothedPoints, m_smooth);
}
// Compare the new smoothed stroke with old one
// Enable the output for unchanged parts
int outputNum = (int)m_outputPoints.size();
for (int i = m_outputIndex; i < outputNum; ++i) {
if (m_outputPoints[i] != smoothedPoints[i]) {
break;
}
++m_outputIndex;
}
m_outputPoints = smoothedPoints;
}
//===================================================================
//
// BrushTool
//
//-----------------------------------------------------------------------------
BrushTool::BrushTool(std::string name, int targetType)
: TTool(name)
, m_thickness("Size", 0, 100, 0, 5)
, m_rasThickness("Size", 1, 100, 1, 5)
, m_accuracy("Accuracy:", 1, 100, 20)
, m_smooth("Smooth:", 0, 50, 0)
, m_hardness("Hardness:", 0, 100, 100)
, m_preset("Preset:")
, m_selective("Selective", false)
, m_breakAngles("Break", true)
, m_pencil("Pencil", false)
, m_pressure("Pressure", true)
, m_capStyle("Cap")
, m_joinStyle("Join")
, m_miterJoinLimit("Miter:", 0, 100, 4)
, m_rasterTrack(0)
, m_styleId(0)
, m_modifiedRegion()
, m_bluredBrush(0)
, m_active(false)
, m_enabled(false)
, m_isPrompting(false)
, m_firstTime(true)
, m_presetsLoaded(false)
, m_workingFrameId(TFrameId()) {
bind(targetType);
if (targetType & TTool::Vectors) {
m_prop[0].bind(m_thickness);
m_prop[0].bind(m_accuracy);
m_prop[0].bind(m_smooth);
m_prop[0].bind(m_breakAngles);
m_breakAngles.setId("BreakSharpAngles");
}
if (targetType & TTool::ToonzImage) {
m_prop[0].bind(m_rasThickness);
m_prop[0].bind(m_hardness);
m_prop[0].bind(m_smooth);
m_prop[0].bind(m_selective);
m_prop[0].bind(m_pencil);
m_pencil.setId("PencilMode");
m_selective.setId("Selective");
}
m_prop[0].bind(m_pressure);
m_prop[0].bind(m_preset);
m_preset.setId("BrushPreset");
m_preset.addValue(CUSTOM_WSTR);
m_pressure.setId("PressureSensitivity");
m_capStyle.addValue(BUTT_WSTR);
m_capStyle.addValue(ROUNDC_WSTR);
m_capStyle.addValue(PROJECTING_WSTR);
m_capStyle.setId("Cap");
m_joinStyle.addValue(MITER_WSTR);
m_joinStyle.addValue(ROUNDJ_WSTR);
m_joinStyle.addValue(BEVEL_WSTR);
m_joinStyle.setId("Join");
m_miterJoinLimit.setId("Miter");
if (targetType & TTool::Vectors) {
m_prop[1].bind(m_capStyle);
m_prop[1].bind(m_joinStyle);
m_prop[1].bind(m_miterJoinLimit);
}
m_animationAutoComplete = new AnimationAutoComplete();
}
//-------------------------------------------------------------------------------------------------------
ToolOptionsBox *BrushTool::createOptionsBox() {
TPaletteHandle *currPalette =
TTool::getApplication()->getPaletteController()->getCurrentLevelPalette();
ToolHandle *currTool = TTool::getApplication()->getCurrentTool();
return new BrushToolOptionsBox(0, this, currPalette, currTool);
}
//-------------------------------------------------------------------------------------------------------
void BrushTool::drawLine(const TPointD &point, const TPointD ¢re,
bool horizontal, bool isDecimal) {
if (!isDecimal) {
if (horizontal) {
tglDrawSegment(TPointD(point.x - 1.5, point.y + 0.5) + centre,
TPointD(point.x - 0.5, point.y + 0.5) + centre);
tglDrawSegment(TPointD(point.y - 0.5, -point.x + 1.5) + centre,
TPointD(point.y - 0.5, -point.x + 0.5) + centre);
tglDrawSegment(TPointD(-point.x + 0.5, -point.y + 0.5) + centre,
TPointD(-point.x - 0.5, -point.y + 0.5) + centre);
tglDrawSegment(TPointD(-point.y - 0.5, point.x - 0.5) + centre,
TPointD(-point.y - 0.5, point.x + 0.5) + centre);
tglDrawSegment(TPointD(point.y - 0.5, point.x + 0.5) + centre,
TPointD(point.y - 0.5, point.x - 0.5) + centre);
tglDrawSegment(TPointD(point.x - 0.5, -point.y + 0.5) + centre,
TPointD(point.x - 1.5, -point.y + 0.5) + centre);
tglDrawSegment(TPointD(-point.y - 0.5, -point.x + 0.5) + centre,
TPointD(-point.y - 0.5, -point.x + 1.5) + centre);
tglDrawSegment(TPointD(-point.x - 0.5, point.y + 0.5) + centre,
TPointD(-point.x + 0.5, point.y + 0.5) + centre);
} else {
tglDrawSegment(TPointD(point.x - 1.5, point.y + 1.5) + centre,
TPointD(point.x - 1.5, point.y + 0.5) + centre);
tglDrawSegment(TPointD(point.x - 1.5, point.y + 0.5) + centre,
TPointD(point.x - 0.5, point.y + 0.5) + centre);
tglDrawSegment(TPointD(point.y + 0.5, -point.x + 1.5) + centre,
TPointD(point.y - 0.5, -point.x + 1.5) + centre);
tglDrawSegment(TPointD(point.y - 0.5, -point.x + 1.5) + centre,
TPointD(point.y - 0.5, -point.x + 0.5) + centre);
tglDrawSegment(TPointD(-point.x + 0.5, -point.y - 0.5) + centre,
TPointD(-point.x + 0.5, -point.y + 0.5) + centre);
tglDrawSegment(TPointD(-point.x + 0.5, -point.y + 0.5) + centre,
TPointD(-point.x - 0.5, -point.y + 0.5) + centre);
tglDrawSegment(TPointD(-point.y - 1.5, point.x - 0.5) + centre,
TPointD(-point.y - 0.5, point.x - 0.5) + centre);
tglDrawSegment(TPointD(-point.y - 0.5, point.x - 0.5) + centre,
TPointD(-point.y - 0.5, point.x + 0.5) + centre);
tglDrawSegment(TPointD(point.y + 0.5, point.x - 0.5) + centre,
TPointD(point.y - 0.5, point.x - 0.5) + centre);
tglDrawSegment(TPointD(point.y - 0.5, point.x - 0.5) + centre,
TPointD(point.y - 0.5, point.x + 0.5) + centre);
tglDrawSegment(TPointD(point.x - 1.5, -point.y - 0.5) + centre,
TPointD(point.x - 1.5, -point.y + 0.5) + centre);
tglDrawSegment(TPointD(point.x - 1.5, -point.y + 0.5) + centre,
TPointD(point.x - 0.5, -point.y + 0.5) + centre);
tglDrawSegment(TPointD(-point.y - 1.5, -point.x + 1.5) + centre,
TPointD(-point.y - 0.5, -point.x + 1.5) + centre);
tglDrawSegment(TPointD(-point.y - 0.5, -point.x + 1.5) + centre,
TPointD(-point.y - 0.5, -point.x + 0.5) + centre);
tglDrawSegment(TPointD(-point.x + 0.5, point.y + 1.5) + centre,
TPointD(-point.x + 0.5, point.y + 0.5) + centre);
tglDrawSegment(TPointD(-point.x + 0.5, point.y + 0.5) + centre,
TPointD(-point.x - 0.5, point.y + 0.5) + centre);
}
} else {
if (horizontal) {
tglDrawSegment(TPointD(point.x - 0.5, point.y + 0.5) + centre,
TPointD(point.x + 0.5, point.y + 0.5) + centre);
tglDrawSegment(TPointD(point.y + 0.5, point.x - 0.5) + centre,
TPointD(point.y + 0.5, point.x + 0.5) + centre);
tglDrawSegment(TPointD(point.y + 0.5, -point.x + 0.5) + centre,
TPointD(point.y + 0.5, -point.x - 0.5) + centre);
tglDrawSegment(TPointD(point.x + 0.5, -point.y - 0.5) + centre,
TPointD(point.x - 0.5, -point.y - 0.5) + centre);
tglDrawSegment(TPointD(-point.x - 0.5, -point.y - 0.5) + centre,
TPointD(-point.x + 0.5, -point.y - 0.5) + centre);
tglDrawSegment(TPointD(-point.y - 0.5, -point.x + 0.5) + centre,
TPointD(-point.y - 0.5, -point.x - 0.5) + centre);
tglDrawSegment(TPointD(-point.y - 0.5, point.x - 0.5) + centre,
TPointD(-point.y - 0.5, point.x + 0.5) + centre);
tglDrawSegment(TPointD(-point.x + 0.5, point.y + 0.5) + centre,
TPointD(-point.x - 0.5, point.y + 0.5) + centre);
} else {
tglDrawSegment(TPointD(point.x - 0.5, point.y + 1.5) + centre,
TPointD(point.x - 0.5, point.y + 0.5) + centre);
tglDrawSegment(TPointD(point.x - 0.5, point.y + 0.5) + centre,
TPointD(point.x + 0.5, point.y + 0.5) + centre);
tglDrawSegment(TPointD(point.y + 1.5, point.x - 0.5) + centre,
TPointD(point.y + 0.5, point.x - 0.5) + centre);
tglDrawSegment(TPointD(point.y + 0.5, point.x - 0.5) + centre,
TPointD(point.y + 0.5, point.x + 0.5) + centre);
tglDrawSegment(TPointD(point.y + 1.5, -point.x + 0.5) + centre,
TPointD(point.y + 0.5, -point.x + 0.5) + centre);
tglDrawSegment(TPointD(point.y + 0.5, -point.x + 0.5) + centre,
TPointD(point.y + 0.5, -point.x - 0.5) + centre);
tglDrawSegment(TPointD(point.x - 0.5, -point.y - 1.5) + centre,
TPointD(point.x - 0.5, -point.y - 0.5) + centre);
tglDrawSegment(TPointD(point.x - 0.5, -point.y - 0.5) + centre,
TPointD(point.x + 0.5, -point.y - 0.5) + centre);
tglDrawSegment(TPointD(-point.x + 0.5, -point.y - 1.5) + centre,
TPointD(-point.x + 0.5, -point.y - 0.5) + centre);
tglDrawSegment(TPointD(-point.x + 0.5, -point.y - 0.5) + centre,
TPointD(-point.x - 0.5, -point.y - 0.5) + centre);
tglDrawSegment(TPointD(-point.y - 1.5, -point.x + 0.5) + centre,
TPointD(-point.y - 0.5, -point.x + 0.5) + centre);
tglDrawSegment(TPointD(-point.y - 0.5, -point.x + 0.5) + centre,
TPointD(-point.y - 0.5, -point.x - 0.5) + centre);
tglDrawSegment(TPointD(-point.y - 1.5, point.x - 0.5) + centre,
TPointD(-point.y - 0.5, point.x - 0.5) + centre);
tglDrawSegment(TPointD(-point.y - 0.5, point.x - 0.5) + centre,
TPointD(-point.y - 0.5, point.x + 0.5) + centre);
tglDrawSegment(TPointD(-point.x + 0.5, point.y + 1.5) + centre,
TPointD(-point.x + 0.5, point.y + 0.5) + centre);
tglDrawSegment(TPointD(-point.x + 0.5, point.y + 0.5) + centre,
TPointD(-point.x - 0.5, point.y + 0.5) + centre);
}
}
}
//-------------------------------------------------------------------------------------------------------
void BrushTool::drawEmptyCircle(TPointD pos, int thick, bool isLxEven,
bool isLyEven, bool isPencil) {
if (isLxEven) pos.x += 0.5;
if (isLyEven) pos.y += 0.5;
if (!isPencil)
tglDrawCircle(pos, (thick + 1) * 0.5);
else {
int x = 0, y = tround((thick * 0.5) - 0.5);
int d = 3 - 2 * (int)(thick * 0.5);
bool horizontal = true, isDecimal = thick % 2 != 0;
drawLine(TPointD(x, y), pos, horizontal, isDecimal);
while (y > x) {
if (d < 0) {
d = d + 4 * x + 6;
horizontal = true;
} else {
d = d + 4 * (x - y) + 10;
horizontal = false;
y--;
}
x++;
drawLine(TPointD(x, y), pos, horizontal, isDecimal);
}
}
}
//-------------------------------------------------------------------------------------------------------
void BrushTool::updateTranslation() {
m_thickness.setQStringName(tr("Size"));
m_rasThickness.setQStringName(tr("Size"));
m_hardness.setQStringName(tr("Hardness:"));
m_accuracy.setQStringName(tr("Accuracy:"));
m_smooth.setQStringName(tr("Smooth:"));
m_selective.setQStringName(tr("Selective"));
// m_filled.setQStringName(tr("Filled"));
m_preset.setQStringName(tr("Preset:"));
m_breakAngles.setQStringName(tr("Break"));
m_pencil.setQStringName(tr("Pencil"));
m_pressure.setQStringName(tr("Pressure"));
m_capStyle.setQStringName(tr("Cap"));
m_joinStyle.setQStringName(tr("Join"));
m_miterJoinLimit.setQStringName(tr("Miter:"));
}
//---------------------------------------------------------------------------------------------------
void BrushTool::updateWorkAndBackupRasters(const TRect &rect) {
TToonzImageP ti = TImageP(getImage(false, 1));
if (!ti) return;
TRasterCM32P ras = ti->getRaster();
TRect _rect = rect * ras->getBounds();
TRect _lastRect = m_lastRect * ras->getBounds();
if (_rect.isEmpty()) return;
if (m_lastRect.isEmpty()) {
m_workRas->extract(_rect)->clear();
m_backupRas->extract(_rect)->copy(ras->extract(_rect));
return;
}
QList<TRect> rects = ToolUtils::splitRect(_rect, _lastRect);
for (int i = 0; i < rects.size(); i++) {
m_workRas->extract(rects[i])->clear();
m_backupRas->extract(rects[i])->copy(ras->extract(rects[i]));
}
}
//---------------------------------------------------------------------------------------------------
void BrushTool::onActivate() {
if (m_firstTime) {
m_thickness.setValue(
TDoublePairProperty::Value(VectorBrushMinSize, VectorBrushMaxSize));
m_rasThickness.setValue(
TDoublePairProperty::Value(RasterBrushMinSize, RasterBrushMaxSize));
m_capStyle.setIndex(VectorCapStyle);
m_joinStyle.setIndex(VectorJoinStyle);
m_miterJoinLimit.setValue(VectorMiterValue);
m_selective.setValue(BrushSelective ? 1 : 0);
m_breakAngles.setValue(BrushBreakSharpAngles ? 1 : 0);
m_pencil.setValue(RasterBrushPencilMode ? 1 : 0);
m_pressure.setValue(BrushPressureSensitivity ? 1 : 0);
m_firstTime = false;
m_accuracy.setValue(BrushAccuracy);
m_smooth.setValue(BrushSmooth);
m_hardness.setValue(RasterBrushHardness);
}
if (m_targetType & TTool::ToonzImage) {
m_brushPad = ToolUtils::getBrushPad(m_rasThickness.getValue().second,
m_hardness.getValue() * 0.01);
setWorkAndBackupImages();
}
// TODO:app->editImageOrSpline();
}
//--------------------------------------------------------------------------------------------------
void BrushTool::onDeactivate() {
/*---
* ドラッグ中にツールが切り替わった場合に備え、onDeactivateにもMouseReleaseと同じ処理を行う
* ---*/
if (m_tileSaver && !m_isPath) {
bool isValid = m_enabled && m_active;
m_enabled = false;
if (isValid) {
TImageP image = getImage(true);
if (TToonzImageP ti = image)
finishRasterBrush(m_mousePos,
1); /*-- 最後のストロークの筆圧は1とする --*/
}
}
m_workRas = TRaster32P();
m_backupRas = TRasterCM32P();
}
//--------------------------------------------------------------------------------------------------
bool BrushTool::preLeftButtonDown() {
touchImage();
if (m_isFrameCreated) setWorkAndBackupImages();
return true;
}
//--------------------------------------------------------------------------------------------------
void BrushTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {
TTool::Application *app = TTool::getApplication();
if (!app) return;
int col = app->getCurrentColumn()->getColumnIndex();
m_isPath = app->getCurrentObject()->isSpline();
m_enabled = col >= 0 || m_isPath;
// : gestire autoenable
if (!m_enabled) return;
if (!m_isPath) {
m_currentColor = TPixel32::Black;
m_active = !!getImage(true);
if (!m_active) {
m_active = !!touchImage();
}
if (!m_active) return;
if (m_active) {
// nel caso che il colore corrente sia un cleanup/studiopalette color
// oppure il colore di un colorfield
m_styleId = app->getCurrentLevelStyleIndex();
TColorStyle *cs = app->getCurrentLevelStyle();
if (cs) {
TRasterStyleFx *rfx = cs ? cs->getRasterStyleFx() : 0;
m_active =
cs != 0 && (cs->isStrokeStyle() || (rfx && rfx->isInkStyle()));
m_currentColor = cs->getAverageColor();
m_currentColor.m = 255;
} else {
m_styleId = 1;
m_currentColor = TPixel32::Black;
}
}
} else {
m_currentColor = TPixel32::Red;
m_active = true;
}
// assert(0<=m_styleId && m_styleId<2);
TImageP img = getImage(true);
TToonzImageP ri(img);
if (ri) {
TRasterCM32P ras = ri->getRaster();
if (ras) {
TPointD rasCenter = ras->getCenterD();
m_tileSet = new TTileSetCM32(ras->getSize());
m_tileSaver = new TTileSaverCM32(ras, m_tileSet);
double maxThick = m_rasThickness.getValue().second;
double thickness =
(m_pressure.getValue() || m_isPath)
? computeThickness(e.m_pressure, m_rasThickness, m_isPath) * 2
: maxThick;
/*--- ストロークの最初にMaxサイズの円が描かれてしまう不具合を防止する
* ---*/
if (m_pressure.getValue() && e.m_pressure == 255)
thickness = m_rasThickness.getValue().first;
TPointD halfThick(maxThick * 0.5, maxThick * 0.5);
TRectD invalidateRect(pos - halfThick, pos + halfThick);
if (m_hardness.getValue() == 100 || m_pencil.getValue()) {
/*-- Pencilモードでなく、Hardness=100 の場合のブラシサイズを1段階下げる
* --*/
if (!m_pencil.getValue()) thickness -= 1.0;
TThickPoint thickPoint(pos + convert(ras->getCenter()), thickness);
m_rasterTrack = new RasterStrokeGenerator(
ras, BRUSH, NONE, m_styleId, thickPoint, m_selective.getValue(), 0,
!m_pencil.getValue());
m_tileSaver->save(m_rasterTrack->getLastRect());
m_rasterTrack->generateLastPieceOfStroke(m_pencil.getValue());
m_smoothStroke.beginStroke(m_smooth.getValue());
m_smoothStroke.addPoint(thickPoint);
std::vector<TThickPoint> pts;
m_smoothStroke.getSmoothPoints(
pts); // skip first point because it has been outputted
} else {
m_points.clear();
TThickPoint point(pos + rasCenter, thickness);
m_points.push_back(point);
m_bluredBrush = new BluredBrush(m_workRas, maxThick, m_brushPad, false);
m_strokeRect = m_bluredBrush->getBoundFromPoints(m_points);
updateWorkAndBackupRasters(m_strokeRect);
m_tileSaver->save(m_strokeRect);
m_bluredBrush->addPoint(point, 1);
m_bluredBrush->updateDrawing(ri->getRaster(), m_backupRas, m_strokeRect,
m_styleId, m_selective.getValue());
m_lastRect = m_strokeRect;
m_smoothStroke.beginStroke(m_smooth.getValue());
m_smoothStroke.addPoint(point);
std::vector<TThickPoint> pts;
m_smoothStroke.getSmoothPoints(
pts); // skip first point because it has been outputted
}
/*-- 作業中のFidを登録 --*/
m_workingFrameId = getFrameId();
invalidate(invalidateRect);
}
} else {
m_track.clear();
double thickness =
(m_pressure.getValue() || m_isPath)
? computeThickness(e.m_pressure, m_thickness, m_isPath)
: m_thickness.getValue().second * 0.5;
/*--- ストロークの最初にMaxサイズの円が描かれてしまう不具合を防止する ---*/
if (m_pressure.getValue() && e.m_pressure == 255)
thickness = m_rasThickness.getValue().first;
m_smoothStroke.beginStroke(m_smooth.getValue());
addTrackPoint(TThickPoint(pos, thickness), getPixelSize() * getPixelSize());
}
}
//-------------------------------------------------------------------------------------------------------------
void BrushTool::leftButtonDrag(const TPointD &pos, const TMouseEvent &e) {
m_brushPos = m_mousePos = pos;
if (!m_enabled || !m_active) return;
bool isAdded;
if (TToonzImageP ti = TImageP(getImage(true))) {
TPointD rasCenter = ti->getRaster()->getCenterD();
int maxThickness = m_rasThickness.getValue().second;
double thickness =
(m_pressure.getValue() || m_isPath)
? computeThickness(e.m_pressure, m_rasThickness, m_isPath) * 2
: maxThickness;
TRectD invalidateRect;
if (m_rasterTrack &&
(m_hardness.getValue() == 100 || m_pencil.getValue())) {
/*-- Pencilモードでなく、Hardness=100 の場合のブラシサイズを1段階下げる
* --*/
if (!m_pencil.getValue()) thickness -= 1.0;
TThickPoint thickPoint(pos + rasCenter, thickness);
m_smoothStroke.addPoint(thickPoint);
std::vector<TThickPoint> pts;
m_smoothStroke.getSmoothPoints(pts);
for (size_t i = 0; i < pts.size(); ++i) {
const TThickPoint &thickPoint = pts[i];
isAdded = m_rasterTrack->add(thickPoint);
if (isAdded) {
m_tileSaver->save(m_rasterTrack->getLastRect());
m_rasterTrack->generateLastPieceOfStroke(m_pencil.getValue());
std::vector<TThickPoint> brushPoints =
m_rasterTrack->getPointsSequence();
int m = (int)brushPoints.size();
std::vector<TThickPoint> points;
if (m == 3) {
points.push_back(brushPoints[0]);
points.push_back(brushPoints[1]);
} else {
points.push_back(brushPoints[m - 4]);
points.push_back(brushPoints[m - 3]);
points.push_back(brushPoints[m - 2]);
}
if (i == 0) {
invalidateRect =
ToolUtils::getBounds(points, maxThickness) - rasCenter;
} else {
invalidateRect +=
ToolUtils::getBounds(points, maxThickness) - rasCenter;
}
}
}
} else {
// antialiased brush
assert(m_workRas.getPointer() && m_backupRas.getPointer());
TThickPoint thickPoint(pos + rasCenter, thickness);
m_smoothStroke.addPoint(thickPoint);
std::vector<TThickPoint> pts;
m_smoothStroke.getSmoothPoints(pts);
bool rectUpdated = false;
for (size_t i = 0; i < pts.size(); ++i) {
TThickPoint old = m_points.back();
if (norm2(pos - old) < 4) continue;
const TThickPoint &point = pts[i];
TThickPoint mid((old + point) * 0.5, (point.thick + old.thick) * 0.5);
m_points.push_back(mid);
m_points.push_back(point);
TRect bbox;
int m = (int)m_points.size();
std::vector<TThickPoint> points;
if (m == 3) {
// ho appena cominciato. devo disegnare un segmento
TThickPoint pa = m_points.front();
points.push_back(pa);
points.push_back(mid);
bbox = m_bluredBrush->getBoundFromPoints(points);
updateWorkAndBackupRasters(bbox + m_lastRect);
m_tileSaver->save(bbox);
m_bluredBrush->addArc(pa, (mid + pa) * 0.5, mid, 1, 1);
m_lastRect += bbox;
} else {
points.push_back(m_points[m - 4]);
points.push_back(old);
points.push_back(mid);
bbox = m_bluredBrush->getBoundFromPoints(points);
updateWorkAndBackupRasters(bbox + m_lastRect);
m_tileSaver->save(bbox);
m_bluredBrush->addArc(m_points[m - 4], old, mid, 1, 1);
m_lastRect += bbox;
}
if (!rectUpdated) {
invalidateRect =
ToolUtils::getBounds(points, maxThickness) - rasCenter;
rectUpdated = true;
} else {
invalidateRect +=
ToolUtils::getBounds(points, maxThickness) - rasCenter;
}
m_bluredBrush->updateDrawing(ti->getRaster(), m_backupRas, bbox,
m_styleId, m_selective.getValue());
m_strokeRect += bbox;
}
}
invalidate(invalidateRect.enlarge(2));
} else {
double thickness =
(m_pressure.getValue() || m_isPath)
? computeThickness(e.m_pressure, m_thickness, m_isPath)
: m_thickness.getValue().second * 0.5;
addTrackPoint(TThickPoint(pos, thickness), getPixelSize() * getPixelSize());
invalidate();
}
}
//---------------------------------------------------------------------------------------------------------------
void BrushTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {
bool isValid = m_enabled && m_active;
m_enabled = false;
if (!isValid) return;
if (m_isPath) {
double error = 20.0 * getPixelSize();
flushTrackPoint();
TStroke *stroke = m_track.makeStroke(error);
int points = stroke->getControlPointCount();
if (TVectorImageP vi = getImage(true)) {
struct Cleanup {
BrushTool *m_this;
~Cleanup() { m_this->m_track.clear(), m_this->invalidate(); }
} cleanup = {this};
if (!isJustCreatedSpline(vi.getPointer())) {
m_isPrompting = true;
QString question("Are you sure you want to replace the motion path?");
int ret =
DVGui::MsgBox(question, QObject::tr("Yes"), QObject::tr("No"), 0);
m_isPrompting = false;
if (ret == 2 || ret == 0) return;
}
QMutexLocker lock(vi->getMutex());
TUndo *undo =
new UndoPath(getXsheet()->getStageObject(getObjectId())->getSpline());
while (vi->getStrokeCount() > 0) vi->deleteStroke(0);
vi->addStroke(stroke, false);
notifyImageChanged();
TUndoManager::manager()->add(undo);
}
return;
}
TImageP image = getImage(true);
if (TVectorImageP vi = image) {
if (m_track.isEmpty()) {
m_styleId = 0;
m_track.clear();
return;
}
m_track.filterPoints();
double error = 30.0 / (1 + 0.5 * m_accuracy.getValue());
error *= getPixelSize();
flushTrackPoint();
TStroke *stroke = m_track.makeStroke(error);
stroke->setStyle(m_styleId);
{
TStroke::OutlineOptions &options = stroke->outlineOptions();
options.m_capStyle = m_capStyle.getIndex();
options.m_joinStyle = m_joinStyle.getIndex();
options.m_miterUpper = m_miterJoinLimit.getValue();
}
m_styleId = 0;
QMutexLocker lock(vi->getMutex());
if (stroke->getControlPointCount() == 3 &&
stroke->getControlPoint(0) !=
stroke->getControlPoint(2)) // gli stroke con solo 1 chunk vengono
// fatti dal tape tool...e devono venir
// riconosciuti come speciali di
// autoclose proprio dal fatto che
// hanno 1 solo chunk.
stroke->insertControlPoints(0.5);
m_animationAutoComplete->addStroke(stroke);
while(bullshitStrokes)
{
// I don't know why -2 but it works
vi.getPointer()->deleteStroke(vi.getPointer()->getStrokeCount() - 2);
bullshitStrokes--;
}
synthesizedStrokes = m_animationAutoComplete->getSynthesizedStrokes();
// draws synthesized strokes
for (auto stroke : synthesizedStrokes)
{
stroke->stroke->setStyle(3);
addStrokeToImage(getApplication(), vi, stroke->stroke, m_breakAngles.getValue(),
m_isFrameCreated, m_isLevelCreated);
bullshitStrokes++;
}
#ifdef DEBUGGING
#ifdef SHOW_MATCHING_STROKE
if (m_animationAutoComplete->matchedStroke)
{
m_animationAutoComplete->matchedStroke->stroke->setStyle(2);
addStrokeToImage(getApplication(), vi, m_animationAutoComplete->matchedStroke->stroke, m_breakAngles.getValue(),
m_isFrameCreated, m_isLevelCreated);
bullshitStrokes++;
}
#endif
#ifdef SHOW_PAIR_LINES
std::vector<TStroke*> similarPairLines = m_animationAutoComplete->m_similarPairLines;
// draw lines between similar pair strokes
for (auto stroke : similarPairLines)
{
stroke->setStyle(2);
addStrokeToImage(getApplication(), vi, stroke, m_breakAngles.getValue(),
m_isFrameCreated, m_isLevelCreated);
bullshitStrokes++;
if (!bullshitStrokes)
assert(bullshitStrokes);
}
#endif // show matching stroke
#ifdef SHOW_PAIR_STROKES
std::vector<TStroke*> pairStrokes = m_animationAutoComplete->pairStrokes;
for (auto stroke : pairStrokes)
{
stroke->setStyle(2);
addStrokeToImage(getApplication(), vi, stroke, m_breakAngles.getValue(),
m_isFrameCreated, m_isLevelCreated);
bullshitStrokes++;
}
#endif
//TODO: remove at production
#ifdef SHOW_SPACE_VICINITY
std::vector<TStroke*> spaceVicinities = m_animationAutoComplete->drawSpaceVicinity(stroke);
for (auto i : spaceVicinities)
{
addStrokeToImage(getApplication(), vi, i, m_breakAngles.getValue(),
m_isFrameCreated, m_isLevelCreated);
bullshitStrokes++;
}
#endif
#ifdef SHOW_NORMALS
std::vector<TStroke*> normal = m_animationAutoComplete->drawNormalStrokes(stroke);
for (auto stroke : normal)
{
addStrokeToImage(getApplication(), vi, stroke, m_breakAngles.getValue(),
m_isFrameCreated, m_isLevelCreated);
bullshitStrokes++;
}
#endif
#endif // debugging
addStrokeToImage(getApplication(), vi, stroke, m_breakAngles.getValue(),
m_isFrameCreated, m_isLevelCreated);
TRectD bbox = stroke->getBBox().enlarge(2) + m_track.getModifiedRegion();
invalidate();
assert(stroke);
m_track.clear();
} else if (TToonzImageP ti = image) {
finishRasterBrush(pos, e.m_pressure);
}
}
//--------------------------------------------------------------------------------------------------
void BrushTool::addTrackPoint(const TThickPoint &point, double pixelSize2) {
m_smoothStroke.addPoint(point);
std::vector<TThickPoint> pts;
m_smoothStroke.getSmoothPoints(pts);
for (size_t i = 0; i < pts.size(); ++i) {
m_track.add(pts[i], pixelSize2);
}
}
//--------------------------------------------------------------------------------------------------
void BrushTool::flushTrackPoint() {
m_smoothStroke.endStroke();
std::vector<TThickPoint> pts;
m_smoothStroke.getSmoothPoints(pts);
double pixelSize2 = getPixelSize() * getPixelSize();
for (size_t i = 0; i < pts.size(); ++i) {
m_track.add(pts[i], pixelSize2);
}
}
//---------------------------------------------------------------------------------------------------------------
/*!
* ドラッグ中にツールが切り替わった場合に備え、onDeactivate時とMouseRelease時にと同じ終了処理を行う
*/
void BrushTool::finishRasterBrush(const TPointD &pos, int pressureVal) {
TImageP image = getImage(true);
TToonzImageP ti = image;
if (!ti) return;
TPointD rasCenter = ti->getRaster()->getCenterD();
TTool::Application *app = TTool::getApplication();
TXshLevel *level = app->getCurrentLevel()->getLevel();
TXshSimpleLevelP simLevel = level->getSimpleLevel();
/*--
* 描画中にカレントフレームが変わっても、描画開始時のFidに対してUndoを記録する
* --*/
TFrameId frameId =
m_workingFrameId.isEmptyFrame() ? getCurrentFid() : m_workingFrameId;
if (m_rasterTrack && (m_hardness.getValue() == 100 || m_pencil.getValue())) {
double thickness =
m_pressure.getValue()
? computeThickness(pressureVal, m_rasThickness, m_isPath)
: m_rasThickness.getValue().second;
/*--- ストロークの最初にMaxサイズの円が描かれてしまう不具合を防止する ---*/
if (m_pressure.getValue() && pressureVal == 255)
thickness = m_rasThickness.getValue().first;
/*-- Pencilモードでなく、Hardness=100 の場合のブラシサイズを1段階下げる --*/
if (!m_pencil.getValue()) thickness -= 1.0;
TRectD invalidateRect;
TThickPoint thickPoint(pos + rasCenter, thickness);
m_smoothStroke.addPoint(thickPoint);
m_smoothStroke.endStroke();
std::vector<TThickPoint> pts;
m_smoothStroke.getSmoothPoints(pts);
for (size_t i = 0; i < pts.size(); ++i) {
const TThickPoint &thickPoint = pts[i];
bool isAdded = m_rasterTrack->add(thickPoint);
if (isAdded) {
m_tileSaver->save(m_rasterTrack->getLastRect());
m_rasterTrack->generateLastPieceOfStroke(m_pencil.getValue(), true);
std::vector<TThickPoint> brushPoints =
m_rasterTrack->getPointsSequence();
int m = (int)brushPoints.size();
std::vector<TThickPoint> points;
if (m == 3) {
points.push_back(brushPoints[0]);
points.push_back(brushPoints[1]);
} else {
points.push_back(brushPoints[m - 4]);
points.push_back(brushPoints[m - 3]);
points.push_back(brushPoints[m - 2]);
}
int maxThickness = m_rasThickness.getValue().second;
if (i == 0) {
invalidateRect =
ToolUtils::getBounds(points, maxThickness) - rasCenter;
} else {
invalidateRect +=
ToolUtils::getBounds(points, maxThickness) - rasCenter;
}
}
}
invalidate(invalidateRect.enlarge(2));
if (m_tileSet->getTileCount() > 0) {
TUndoManager::manager()->add(new RasterBrushUndo(
m_tileSet, m_rasterTrack->getPointsSequence(),
m_rasterTrack->getStyleId(), m_rasterTrack->isSelective(),
simLevel.getPointer(), frameId, m_pencil.getValue(), m_isFrameCreated,
m_isLevelCreated));
}
delete m_rasterTrack;
m_rasterTrack = 0;
} else {
if (m_points.size() != 1) {
double maxThickness = m_rasThickness.getValue().second;
double thickness =
(m_pressure.getValue() || m_isPath)
? computeThickness(pressureVal, m_rasThickness, m_isPath)
: maxThickness;
TPointD rasCenter = ti->getRaster()->getCenterD();
TRectD invalidateRect;
bool rectUpdated = false;
TThickPoint thickPoint(pos + rasCenter, thickness);
m_smoothStroke.addPoint(thickPoint);
m_smoothStroke.endStroke();
std::vector<TThickPoint> pts;
m_smoothStroke.getSmoothPoints(pts);
for (size_t i = 0; i < pts.size() - 1; ++i) {
TThickPoint old = m_points.back();
if (norm2(pos - old) < 4) continue;
const TThickPoint &point = pts[i];
TThickPoint mid((old + point) * 0.5, (point.thick + old.thick) * 0.5);
m_points.push_back(mid);
m_points.push_back(point);
TRect bbox;
int m = (int)m_points.size();
std::vector<TThickPoint> points;
if (m == 3) {
// ho appena cominciato. devo disegnare un segmento
TThickPoint pa = m_points.front();
points.push_back(pa);
points.push_back(mid);
bbox = m_bluredBrush->getBoundFromPoints(points);
updateWorkAndBackupRasters(bbox + m_lastRect);
m_tileSaver->save(bbox);
m_bluredBrush->addArc(pa, (mid + pa) * 0.5, mid, 1, 1);
m_lastRect += bbox;
} else {
points.push_back(m_points[m - 4]);
points.push_back(old);
points.push_back(mid);
bbox = m_bluredBrush->getBoundFromPoints(points);
updateWorkAndBackupRasters(bbox + m_lastRect);
m_tileSaver->save(bbox);
m_bluredBrush->addArc(m_points[m - 4], old, mid, 1, 1);
m_lastRect += bbox;
}
if (!rectUpdated) {
invalidateRect =
ToolUtils::getBounds(points, maxThickness) - rasCenter;
rectUpdated = true;
} else {
invalidateRect +=
ToolUtils::getBounds(points, maxThickness) - rasCenter;
}
m_bluredBrush->updateDrawing(ti->getRaster(), m_backupRas, bbox,
m_styleId, m_selective.getValue());
m_strokeRect += bbox;
}
if (pts.size() > 0) {
TThickPoint point = pts.back();
m_points.push_back(point);
int m = m_points.size();
std::vector<TThickPoint> points;
points.push_back(m_points[m - 3]);
points.push_back(m_points[m - 2]);
points.push_back(m_points[m - 1]);
TRect bbox = m_bluredBrush->getBoundFromPoints(points);
updateWorkAndBackupRasters(bbox);
m_tileSaver->save(bbox);
m_bluredBrush->addArc(points[0], points[1], points[2], 1, 1);
m_bluredBrush->updateDrawing(ti->getRaster(), m_backupRas, bbox,
m_styleId, m_selective.getValue());
if (!rectUpdated) {
invalidateRect =
ToolUtils::getBounds(points, maxThickness) - rasCenter;
} else {
invalidateRect +=
ToolUtils::getBounds(points, maxThickness) - rasCenter;
}
m_lastRect += bbox;
m_strokeRect += bbox;
}
invalidate(invalidateRect.enlarge(2));
m_lastRect.empty();
}
delete m_bluredBrush;
m_bluredBrush = 0;
if (m_tileSet->getTileCount() > 0) {
TUndoManager::manager()->add(new RasterBluredBrushUndo(
m_tileSet, m_points, m_styleId, m_selective.getValue(),
simLevel.getPointer(), frameId, m_rasThickness.getValue().second,
m_hardness.getValue() * 0.01, m_isFrameCreated, m_isLevelCreated));
}
}
delete m_tileSaver;
m_tileSaver = 0;
/*-- FIdを指定して、描画中にフレームが動いても、
描画開始時のFidのサムネイルが更新されるようにする。--*/
notifyImageChanged(frameId);
m_strokeRect.empty();
ToolUtils::updateSaveBox();
/*-- 作業中のフレームをリセット --*/
m_workingFrameId = TFrameId();
}
//---------------------------------------------------------------------------------------------------------------
void BrushTool::mouseMove(const TPointD &pos, const TMouseEvent &e) {
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
struct Locals {
BrushTool *m_this;
void setValue(TDoublePairProperty &prop,
const TDoublePairProperty::Value &value) {
prop.setValue(value);
m_this->onPropertyChanged(prop.getName());
TTool::getApplication()->getCurrentTool()->notifyToolChanged();
}
void addMinMax(TDoublePairProperty &prop, double add) {
if (add == 0.0) return;
const TDoublePairProperty::Range &range = prop.getRange();
TDoublePairProperty::Value value = prop.getValue();
value.first = tcrop(value.first + add, range.first, range.second);
value.second = tcrop(value.second + add, range.first, range.second);
setValue(prop, value);
}
void addMinMaxSeparate(TDoublePairProperty &prop, double min, double max) {
if (min == 0.0 && max == 0.0) return;
const TDoublePairProperty::Range &range = prop.getRange();
TDoublePairProperty::Value value = prop.getValue();
value.first += min;
value.second += max;
if (value.first > value.second) value.first = value.second;
value.first = tcrop(value.first, range.first, range.second);
value.second = tcrop(value.second, range.first, range.second);
setValue(prop, value);
}
} locals = {this};
// if (e.isAltPressed() && !e.isCtrlPressed()) {
// const TPointD &diff = pos - m_mousePos;
// double add = (fabs(diff.x) > fabs(diff.y)) ? diff.x : diff.y;
// locals.addMinMax(
// TToonzImageP(getImage(false, 1)) ? m_rasThickness : m_thickness, add);
//} else
if (e.isCtrlPressed() && e.isAltPressed()) {
const TPointD &diff = pos - m_mousePos;
double max = diff.x / 2;
double min = diff.y / 2;
locals.addMinMaxSeparate(
(m_targetType & TTool::ToonzImage) ? m_rasThickness : m_thickness, min,
max);
} else {
m_brushPos = pos;
}
m_mousePos = pos;
invalidate();
if (m_minThick == 0 && m_maxThick == 0) {
if (m_targetType & TTool::ToonzImage) {
m_minThick = m_rasThickness.getValue().first;
m_maxThick = m_rasThickness.getValue().second;
} else {
m_minThick = m_thickness.getValue().first;
m_maxThick = m_thickness.getValue().second;
}
}
}
//-------------------------------------------------------------------------------------------------------------
void BrushTool::draw() {
/*--ショートカットでのツール切り替え時に赤点が描かれるのを防止する--*/
if (m_minThick == 0 && m_maxThick == 0) return;
TImageP img = getImage(false, 1);
// Draw track
tglColor(m_isPrompting ? TPixel32::Green : m_currentColor);
m_track.drawAllFragments();
if (getApplication()->getCurrentObject()->isSpline()) return;
// Draw the brush outline - change color when the Ink / Paint check is
// activated
if ((ToonzCheck::instance()->getChecks() & ToonzCheck::eInk) ||
(ToonzCheck::instance()->getChecks() & ToonzCheck::ePaint) ||
(ToonzCheck::instance()->getChecks() & ToonzCheck::eInk1))
glColor3d(0.5, 0.8, 0.8);
// normally draw in red
else
glColor3d(1.0, 0.0, 0.0);
if (TToonzImageP ti = img) {
TRasterP ras = ti->getRaster();
int lx = ras->getLx();
int ly = ras->getLy();
drawEmptyCircle(m_brushPos, tround(m_minThick), lx % 2 == 0, ly % 2 == 0,
m_pencil.getValue());
drawEmptyCircle(m_brushPos, tround(m_maxThick), lx % 2 == 0, ly % 2 == 0,
m_pencil.getValue());
} else {
tglDrawCircle(m_brushPos, 0.5 * m_minThick);
tglDrawCircle(m_brushPos, 0.5 * m_maxThick);
}
}
//--------------------------------------------------------------------------------------------------------------
void BrushTool::onEnter() {
TImageP img = getImage(false);
if (TToonzImageP(img)) {
m_minThick = m_rasThickness.getValue().first;
m_maxThick = m_rasThickness.getValue().second;
} else {
m_minThick = m_thickness.getValue().first;
m_maxThick = m_thickness.getValue().second;
}
Application *app = getApplication();
m_styleId = app->getCurrentLevelStyleIndex();
TColorStyle *cs = app->getCurrentLevelStyle();
if (cs) {
TRasterStyleFx *rfx = cs->getRasterStyleFx();
m_active = cs->isStrokeStyle() || (rfx && rfx->isInkStyle());
m_currentColor = cs->getAverageColor();
m_currentColor.m = 255;
} else {
m_currentColor = TPixel32::Black;
}
m_active = img;
}
//----------------------------------------------------------------------------------------------------------
void BrushTool::onLeave() {
m_minThick = 0;
m_maxThick = 0;
}
//----------------------------------------------------------------------------------------------------------
TPropertyGroup *BrushTool::getProperties(int idx) {
if (!m_presetsLoaded) initPresets();
return &m_prop[idx];
}
//----------------------------------------------------------------------------------------------------------
void BrushTool::onImageChanged() {
TToonzImageP ti = (TToonzImageP)getImage(false, 1);
if (!ti || !isEnabled()) return;
setWorkAndBackupImages();
}
//----------------------------------------------------------------------------------------------------------
void BrushTool::setWorkAndBackupImages() {
TToonzImageP ti = (TToonzImageP)getImage(false, 1);
if (!ti) return;
TRasterP ras = ti->getRaster();
TDimension dim = ras->getSize();
double hardness = m_hardness.getValue() * 0.01;
if (hardness == 1.0 && ras->getPixelSize() == 4) {
m_workRas = TRaster32P();
m_backupRas = TRasterCM32P();
} else {
if (!m_workRas || m_workRas->getLx() > dim.lx ||
m_workRas->getLy() > dim.ly)
m_workRas = TRaster32P(dim);
if (!m_backupRas || m_backupRas->getLx() > dim.lx ||
m_backupRas->getLy() > dim.ly)
m_backupRas = TRasterCM32P(dim);
m_strokeRect.empty();
m_lastRect.empty();
}
}
//------------------------------------------------------------------
bool BrushTool::onPropertyChanged(std::string propertyName) {
// Set the following to true whenever a different piece of interface must
// be refreshed - done once at the end.
bool notifyTool = false;
/*--- 変更されたPropertyに合わせて処理を分ける ---*/
/*--- m_thicknessとm_rasThicknessは同じName(="Size:")なので、
扱っている画像がラスタかどうかで区別する---*/
if (propertyName == m_thickness.getName()) {
TImageP img = getImage(false);
if (TToonzImageP(img)) // raster
{
RasterBrushMinSize = m_rasThickness.getValue().first;
RasterBrushMaxSize = m_rasThickness.getValue().second;
m_minThick = m_rasThickness.getValue().first;
m_maxThick = m_rasThickness.getValue().second;
} else // vector
{
VectorBrushMinSize = m_thickness.getValue().first;
VectorBrushMaxSize = m_thickness.getValue().second;
m_minThick = m_thickness.getValue().first;
m_maxThick = m_thickness.getValue().second;
}
} else if (propertyName == m_accuracy.getName()) {
BrushAccuracy = m_accuracy.getValue();
} else if (propertyName == m_smooth.getName()) {
BrushSmooth = m_smooth.getValue();
} else if (propertyName == m_preset.getName()) {
loadPreset();
notifyTool = true;
} else if (propertyName == m_selective.getName()) {
BrushSelective = m_selective.getValue();
} else if (propertyName == m_breakAngles.getName()) {
BrushBreakSharpAngles = m_breakAngles.getValue();
} else if (propertyName == m_pencil.getName()) {
RasterBrushPencilMode = m_pencil.getValue();
} else if (propertyName == m_pressure.getName()) {
BrushPressureSensitivity = m_pressure.getValue();
} else if (propertyName == m_capStyle.getName()) {
VectorCapStyle = m_capStyle.getIndex();
} else if (propertyName == m_joinStyle.getName()) {
VectorJoinStyle = m_joinStyle.getIndex();
} else if (propertyName == m_miterJoinLimit.getName()) {
VectorMiterValue = m_miterJoinLimit.getValue();
}
if (m_targetType & TTool::Vectors) {
if (propertyName == m_joinStyle.getName()) notifyTool = true;
}
if (m_targetType & TTool::ToonzImage) {
if (propertyName == m_hardness.getName()) setWorkAndBackupImages();
if (propertyName == m_hardness.getName() ||
propertyName == m_thickness.getName()) {
m_brushPad = getBrushPad(m_rasThickness.getValue().second,
m_hardness.getValue() * 0.01);
TRectD rect(m_mousePos - TPointD(m_maxThick + 2, m_maxThick + 2),
m_mousePos + TPointD(m_maxThick + 2, m_maxThick + 2));
invalidate(rect);
}
}
if (propertyName != m_preset.getName() &&
m_preset.getValue() != CUSTOM_WSTR) {
m_preset.setValue(CUSTOM_WSTR);
notifyTool = true;
}
if (notifyTool) getApplication()->getCurrentTool()->notifyToolChanged();
return true;
}
//------------------------------------------------------------------
void BrushTool::initPresets() {
if (!m_presetsLoaded) {
// If necessary, load the presets from file
m_presetsLoaded = true;
if (getTargetType() & TTool::Vectors)
m_presetsManager.load(TEnv::getConfigDir() + "brush_vector.txt");
else
m_presetsManager.load(TEnv::getConfigDir() + "brush_toonzraster.txt");
}
// Rebuild the presets property entries
const std::set<BrushData> &presets = m_presetsManager.presets();
m_preset.deleteAllValues();
m_preset.addValue(CUSTOM_WSTR);
std::set<BrushData>::const_iterator it, end = presets.end();
for (it = presets.begin(); it != end; ++it) m_preset.addValue(it->m_name);
}
//----------------------------------------------------------------------------------------------------------
void BrushTool::loadPreset() {
const std::set<BrushData> &presets = m_presetsManager.presets();
std::set<BrushData>::const_iterator it;
it = presets.find(BrushData(m_preset.getValue()));
if (it == presets.end()) return;
const BrushData &preset = *it;
try // Don't bother with RangeErrors
{
if (getTargetType() & TTool::Vectors) {
m_thickness.setValue(
TDoublePairProperty::Value(preset.m_min, preset.m_max));
m_accuracy.setValue(preset.m_acc, true);
m_smooth.setValue(preset.m_smooth, true);
m_breakAngles.setValue(preset.m_breakAngles);
m_pressure.setValue(preset.m_pressure);
m_capStyle.setIndex(preset.m_cap);
m_joinStyle.setIndex(preset.m_join);
m_miterJoinLimit.setValue(preset.m_miter);
} else {
m_rasThickness.setValue(TDoublePairProperty::Value(
std::max(preset.m_min, 1.0), preset.m_max));
m_brushPad =
ToolUtils::getBrushPad(preset.m_max, preset.m_hardness * 0.01);
m_smooth.setValue(preset.m_smooth, true);
m_hardness.setValue(preset.m_hardness, true);
m_selective.setValue(preset.m_selective);
m_pencil.setValue(preset.m_pencil);
m_pressure.setValue(preset.m_pressure);
}
} catch (...) {
}
}
//------------------------------------------------------------------
void BrushTool::addPreset(QString name) {
// Build the preset
BrushData preset(name.toStdWString());
if (getTargetType() & TTool::Vectors) {
preset.m_min = m_thickness.getValue().first;
preset.m_max = m_thickness.getValue().second;
} else {
preset.m_min = m_rasThickness.getValue().first;
preset.m_max = m_rasThickness.getValue().second;
}
preset.m_acc = m_accuracy.getValue();
preset.m_smooth = m_smooth.getValue();
preset.m_hardness = m_hardness.getValue();
preset.m_selective = m_selective.getValue();
preset.m_pencil = m_pencil.getValue();
preset.m_breakAngles = m_breakAngles.getValue();
preset.m_pressure = m_pressure.getValue();
preset.m_cap = m_capStyle.getIndex();
preset.m_join = m_joinStyle.getIndex();
preset.m_miter = m_miterJoinLimit.getValue();
// Pass the preset to the manager
m_presetsManager.addPreset(preset);
// Reinitialize the associated preset enum
initPresets();
// Set the value to the specified one
m_preset.setValue(preset.m_name);
}
//------------------------------------------------------------------
void BrushTool::removePreset() {
std::wstring name(m_preset.getValue());
if (name == CUSTOM_WSTR) return;
m_presetsManager.removePreset(name);
initPresets();
// No parameter change, and set the preset value to custom
m_preset.setValue(CUSTOM_WSTR);
}
//------------------------------------------------------------------
/*! Brush、PaintBrush、EraserToolがPencilModeのときにTrueを返す
*/
bool BrushTool::isPencilModeActive() {
return getTargetType() == TTool::ToonzImage && m_pencil.getValue();
}
//==========================================================================================================
// Tools instantiation
BrushTool vectorPencil("T_Brush", TTool::Vectors | TTool::EmptyTarget);
BrushTool toonzPencil("T_Brush", TTool::ToonzImage | TTool::EmptyTarget);
//*******************************************************************************
// Brush Data implementation
//*******************************************************************************
BrushData::BrushData()
: m_name()
, m_min(0.0)
, m_max(0.0)
, m_acc(0.0)
, m_smooth(0.0)
, m_hardness(0.0)
, m_opacityMin(0.0)
, m_opacityMax(0.0)
, m_selective(false)
, m_pencil(false)
, m_breakAngles(false)
, m_pressure(false)
, m_cap(0)
, m_join(0)
, m_miter(0) {}
//----------------------------------------------------------------------------------------------------------
BrushData::BrushData(const std::wstring &name)
: m_name(name)
, m_min(0.0)
, m_max(0.0)
, m_acc(0.0)
, m_smooth(0.0)
, m_hardness(0.0)
, m_opacityMin(0.0)
, m_opacityMax(0.0)
, m_selective(false)
, m_pencil(false)
, m_breakAngles(false)
, m_pressure(false)
, m_cap(0)
, m_join(0)
, m_miter(0) {}
//----------------------------------------------------------------------------------------------------------
void BrushData::saveData(TOStream &os) {
os.openChild("Name");
os << m_name;
os.closeChild();
os.openChild("Thickness");
os << m_min << m_max;
os.closeChild();
os.openChild("Accuracy");
os << m_acc;
os.closeChild();
os.openChild("Smooth");
os << m_smooth;
os.closeChild();
os.openChild("Hardness");
os << m_hardness;
os.closeChild();
os.openChild("Opacity");
os << m_opacityMin << m_opacityMax;
os.closeChild();
os.openChild("Selective");
os << (int)m_selective;
os.closeChild();
os.openChild("Pencil");
os << (int)m_pencil;
os.closeChild();
os.openChild("Break_Sharp_Angles");
os << (int)m_breakAngles;
os.closeChild();
os.openChild("Pressure_Sensitivity");
os << (int)m_pressure;
os.closeChild();
os.openChild("Cap");
os << m_cap;
os.closeChild();
os.openChild("Join");
os << m_join;
os.closeChild();
os.openChild("Miter");
os << m_miter;
os.closeChild();
}
//----------------------------------------------------------------------------------------------------------
void BrushData::loadData(TIStream &is) {
std::string tagName;
int val;
while (is.matchTag(tagName)) {
if (tagName == "Name")
is >> m_name, is.matchEndTag();
else if (tagName == "Thickness")
is >> m_min >> m_max, is.matchEndTag();
else if (tagName == "Accuracy")
is >> m_acc, is.matchEndTag();
else if (tagName == "Smooth")
is >> m_smooth, is.matchEndTag();
else if (tagName == "Hardness")
is >> m_hardness, is.matchEndTag();
else if (tagName == "Opacity")
is >> m_opacityMin >> m_opacityMax, is.matchEndTag();
else if (tagName == "Selective")
is >> val, m_selective = val, is.matchEndTag();
else if (tagName == "Pencil")
is >> val, m_pencil = val, is.matchEndTag();
else if (tagName == "Break_Sharp_Angles")
is >> val, m_breakAngles = val, is.matchEndTag();
else if (tagName == "Pressure_Sensitivity")
is >> val, m_pressure = val, is.matchEndTag();
else if (tagName == "Cap")
is >> m_cap, is.matchEndTag();
else if (tagName == "Join")
is >> m_join, is.matchEndTag();
else if (tagName == "Miter")
is >> m_miter, is.matchEndTag();
else
is.skipCurrentTag();
}
}
//----------------------------------------------------------------------------------------------------------
PERSIST_IDENTIFIER(BrushData, "BrushData");
//*******************************************************************************
// Brush Preset Manager implementation
//*******************************************************************************
void BrushPresetManager::load(const TFilePath &fp) {
m_fp = fp;
std::string tagName;
BrushData data;
TIStream is(m_fp);
try {
while (is.matchTag(tagName)) {
if (tagName == "version") {
VersionNumber version;
is >> version.first >> version.second;
is.setVersion(version);
is.matchEndTag();
} else if (tagName == "brushes") {
while (is.matchTag(tagName)) {
if (tagName == "brush") {
is >> data, m_presets.insert(data);
is.matchEndTag();
} else
is.skipCurrentTag();
}
is.matchEndTag();
} else
is.skipCurrentTag();
}
} catch (...) {
}
}
//------------------------------------------------------------------
void BrushPresetManager::save() {
TOStream os(m_fp);
os.openChild("version");
os << 1 << 19;
os.closeChild();
os.openChild("brushes");
std::set<BrushData>::iterator it, end = m_presets.end();
for (it = m_presets.begin(); it != end; ++it) {
os.openChild("brush");
os << (TPersist &)*it;
os.closeChild();
}
os.closeChild();
}
//------------------------------------------------------------------
void BrushPresetManager::addPreset(const BrushData &data) {
m_presets.erase(data); // Overwriting insertion
m_presets.insert(data);
save();
}
//------------------------------------------------------------------
void BrushPresetManager::removePreset(const std::wstring &name) {
m_presets.erase(BrushData(name));
save();
}
| bsd-3-clause |
sunlightlabs/thezombies | thezombies/tasks/urls.py | 7934 | from __future__ import absolute_import
from django.db import transaction
from django.conf import settings
from django_atomic_celery import task
import requests
from requests.exceptions import InvalidURL
from .utils import (ResultDict, logger, response_to_dict, InsecureHttpAdapter)
from thezombies.models import URLInspection, Probe
try:
from urllib.parse import urlparse, urlunparse
except ImportError:
from urlparse import urlparse, urlunparse
REQUEST_TIMEOUT = getattr(settings, 'REQUEST_TIMEOUT', 60)
session = requests.Session()
session.mount('https://www.sba.gov/', InsecureHttpAdapter())
def open_streaming_response(method, url):
"""
Open a URL for streaming, making sure to indidate a non-gzip response
Returns a requests.Response.
The file-like object will be available under resp.raw.
**Don't forget to close the response object!**
http://docs.python-requests.org/en/latest/user/advanced/#body-content-workflow
"""
try:
req_headers = {'Accept-Encoding': 'identity'}
resp = session.request(method.upper(), url, headers=req_headers, stream=True,
allow_redirects=True, timeout=REQUEST_TIMEOUT, verify=False)
except Exception as e:
logger.exception(e)
return None
return resp
def remove_url_fragments(url):
scheme, netloc, path, params, query, fragments = urlparse(url)
return urlunparse((scheme, netloc, path, params, query, None))
@task
def check_and_correct_url(url, method='GET', keep_fragments=False):
"""Check a url for issues, record exceptions, and attempt to correct the url.
:param url: URL to check and correct
:param method: http method to use, as a string. Default is 'GET'
"""
returnval = ResultDict({'initial_url': url})
try:
logger.info('Checking URL: {0}'.format(url))
scheme, netloc, path, params, query, fragments = urlparse(str(url))
if scheme is '':
# Maybe it is an http url without the scheme?
scheme, netloc, path, params, query, fragments = urlparse("http://{0}".format(str(url)))
elif not (scheme.startswith('http') or scheme.startswith('sftp') or scheme.startswith('ftp')):
# Not a typical 'web' scheme
raise InvalidURL('Invalid scheme (not http(s) or (s)ftp)')
if netloc is '':
raise InvalidURL('Invalid network location')
corrected_url = urlunparse((scheme, netloc, path, params, query, fragments if keep_fragments else None))
returnval['valid_url'] = True
returnval['corrected_url'] = corrected_url
except Exception as e:
logger.warn("Error validating url '{url}'".format(url=url))
returnval.add_error(e)
returnval['valid_url'] = False
return returnval
@task
def request_url(url, method='GET'):
"""Task to request a url, a GET request by default. Tracks and returns errors.
Will not raise an Exception, but may return None for response
:param url: URL to request
:param method: http method to use, as a string. Default is 'GET'
"""
resp = None
logger.info('Preparing request for URL: {0}'.format(url))
checker_result = check_and_correct_url(url)
corrected_url = checker_result.get('corrected_url', None)
returnval = ResultDict(checker_result)
returnval['url_request_attempted'] = False
if corrected_url:
try:
logger.info('Requesting URL: {0}'.format(url))
resp = session.request(method.upper(), corrected_url,
allow_redirects=True, timeout=REQUEST_TIMEOUT, verify=False)
except requests.exceptions.Timeout as e:
logger.warn('Requesting URL: {0}'.format(url))
returnval.add_error(e)
returnval['timeout'] = True
except Exception as e:
returnval.add_error(e)
returnval['url_request_attempted'] = True
# a non-None requests.Response will evaluate to False if it carries an HTTPError value
if resp is not None:
try:
resp.raise_for_status()
except Exception as e:
returnval.add_error(e)
if isinstance(resp, requests.Response):
returnval['response'] = response_to_dict(resp)
else:
logger.error('session.request did not return a valid Response object')
logger.info('Returning from request_url')
return returnval
@task
def inspect_url(taskarg):
"""Task to check a URL and store some information about it. Tracks and returns errors.
:param taskarg: A dictionary containing a url, and optionally a audit_id
"""
returnval = ResultDict(taskarg)
url = taskarg.get('url', None)
url_type = taskarg.get('url_type', None)
audit_id = taskarg.get('audit_id', None)
prev_probe_id = taskarg.get('prev_probe_id', None)
probe = None
with transaction.atomic():
probe = Probe.objects.create(probe_type=Probe.URL_PROBE,
initial={'url': url, 'url_type': url_type},
previous_id=prev_probe_id, audit_id=audit_id)
if url:
result = request_url(url, 'HEAD')
response = result.pop('response', None)
returnval.errors.extend(result.errors)
probe.errors.extend(result.errors)
with transaction.atomic():
if response is not None:
inspection = URLInspection.objects.create_from_response(response, save_content=False)
if audit_id:
inspection.audit_id = audit_id
inspection.probe = probe
inspection.save()
returnval['inspection_id'] = inspection.id
else:
timeout = result.get('timeout', False)
probe.result['timeout'] = timeout
inspection = URLInspection.objects.create(requested_url=url, timeout=timeout)
inspection.probe = probe
if audit_id:
inspection.audit_id = audit_id
inspection.save()
returnval['inspection_id'] = inspection.id
probe.result.update(result)
probe.result['initial_url'] = url
probe.result['inspection_id'] = returnval['inspection_id']
probe.save()
return returnval
@task
def get_or_create_inspection(url, with_content=False):
"""Task to get the lastest URLInspection or create a new one if none exists.
:param url: The url to retrieve.
"""
latest_dates = URLInspection.objects.datetimes('created_at', 'minute')
recent_inspections = None
fetch_val = None
if latest_dates:
latest_date = latest_dates.latest()
recent_inspections = URLInspection.objects.filter(requested_url=url,
created_at__day=latest_date.day,
parent_id__isnull=True,
content__isnull=(not with_content))
inspection = None
if recent_inspections and recent_inspections.count() > 0:
inspection = recent_inspections.latest()
else:
logger.info('No stored inspection, fetch url')
fetch_val = request_url(url)
response = fetch_val.get('response', None)
with transaction.atomic():
if response is not None:
inspection = URLInspection.objects.create_from_response(response)
inspection.save()
else:
timeout = fetch_val.get('timeout', False)
inspection = URLInspection.objects.create(requested_url=url, timeout=timeout)
inspection.save()
returnval = ResultDict(fetch_val or {})
returnval['inspection_id'] = getattr(inspection, 'id', None)
return returnval
| bsd-3-clause |
imerr/LibM2 | game/SShopTable.hpp | 909 | /* This file belongs to the LibM2 library (http://github.com/imermcmaps/LibM2)
* Copyright (c) 2013, iMer (www.imer.cc)
* All rights reserved.
* Licensed under the BSD 3-clause license (http://opensource.org/licenses/BSD-3-Clause)
*/
#ifndef __LIBM2_GAME_SSHOPTABLE_HPP
#define __LIBM2_GAME_SSHOPTABLE_HPP
#include "stdInclude.hpp"
namespace libm2 {
#ifdef __GNUC__
#pragma pack(push,1)
#endif
struct SShopItemTable {
DWORD vnum;
BYTE count;
BYTE pos;
DWORD price;
BYTE display_pos;
}
#ifndef __GNUC__
__attribute__((packed))
#endif
typedef TShopItemTable;
struct SShopTable {
DWORD dwVnum;
DWORD dwNPCVnum;
BYTE byItemCount;
TShopItemTable items[40];
}
#ifndef __GNUC__
__attribute__((packed))
#endif
typedef TShopTable;
#ifdef __GNUC__
#pragma pack(pop)
#endif
}
#endif // __LIBM2_GAME_SSHOPTABLE_HPP
| bsd-3-clause |
shongpon/a6 | frontend/views/report/index.php | 18007 | <?php
use yii\helpers\Html;
use yii\grid\GridView;
use miloschuman\highcharts\Highcharts;
use app\models\RepChildDevR6;
/* @var $this yii\web\View */
/* @var $searchModel app\models\CampaignSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Report';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="container">
<h3>ร้อยละของเด็กที่มีพัฒนาการสมวัยตามช่วงอายุ 0-5 ปี เขตบริการสุขภาพที่ 6</h1>
<?php
$sql = "
SELECT
ROUND(IFNULL(SUM(if(r.areacode LIKE '11%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '11%', r.total_targer, 0)) ,0),2) AS p11,
ROUND(IFNULL(SUM(if(r.areacode LIKE '20%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '20%', r.total_targer, 0)) ,0),2) AS p20,
ROUND(IFNULL(SUM(if(r.areacode LIKE '21%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '21%', r.total_targer, 0)) ,0),2) AS p21,
ROUND(IFNULL(SUM(if(r.areacode LIKE '22%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '22%', r.total_targer, 0)) ,0),2) AS p22,
ROUND(IFNULL(SUM(if(r.areacode LIKE '23%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '23%', r.total_targer, 0)) ,0),2) AS p23,
ROUND(IFNULL(SUM(if(r.areacode LIKE '24%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '24%', r.total_targer, 0)) ,0),2) AS p24,
ROUND(IFNULL(SUM(if(r.areacode LIKE '25%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '25%', r.total_targer, 0)) ,0),2) AS p25,
ROUND(IFNULL(SUM(if(r.areacode LIKE '27%', r.total_result, 0)) * 100 / SUM(if(r.areacode LIKE '27%', r.total_targer, 0)) ,0),2) AS สระแก้ว
FROM
rep_child_dev_r6 r
GROUP BY
r.age_month
ORDER BY
r.age_month
";
$rep = RepChildDevR6::findBySql($sql)->asArray()->all();
// echo '<br>'.implode(',', $rep[0]);
// echo '<br>'.implode(',', $rep[1]);
// echo '<br>'.implode(',', $rep[2]);
// echo '<br>'.implode(',', $rep[3]);
// $value=var_dump($rep[0]);
// echo print_r($value);
// $value=var_dump(array_map('intVal', array_values($rep[0])));
// echo print_r($value);
// $value=var_dump(array_map('floatval', array_values($rep[0])));
// echo print_r(array_keys($rep[0]));
echo Highcharts::widget([
'scripts' => array(
'highcharts-more', // enables supplementary chart types (gauge, arearange, columnrange, etc.)
'modules/exporting', // adds Exporting button/menu to chart
//'themes/grid-light' // applies global 'grid' theme to all charts
),
'options' => array(
'title' => array('text' => 'ร้อยละของเด็กที่มีพัฒนาการสมวัยตามช่วงอายุ 0-5 ปี เขตบริการสุขภาพที่ 6'),
'xAxis' => array(
'categories' => array_keys($rep[0])
),
'yAxis' => array(
'title' => array('text' => 'ร้อยละของเด็กที่มีพัฒนาการสมวัย')
),
'colors'=>array('#2D7EC8', '#21A7DA', '#29D1D9', '#2FD1A5'),
'gradient' => array('enabled'=> true),
'credits' => array('enabled' => false),
/*'exporting' => array('enabled' => false),*/ //to turn off exporting uncomment
'chart' => array(
'plotBackgroundColor' => '#ffffff',
'plotBorderWidth' => null,
'plotShadow' => false,
'height' => 400,
),
'title' => false,
'series' => array(
array('type'=>'column','name' => 'อายุ 9 เดือน', 'pointPadding'=>0, 'borderWidth'=>1, 'data' => array_map('floatval', array_values($rep[0])) ),
array('type'=>'column','name' => 'อายุ 18 เดือน', 'pointPadding'=>0, 'borderWidth'=>1, 'data' => array_map('floatval', array_values($rep[1])) ),
array('type'=>'column','name' => 'อายุ 30 เดือน', 'pointPadding'=>0, 'borderWidth'=>1, 'data' => array_map('floatval', array_values($rep[2])) ),
array('type'=>'column','name' => 'อายุ 42 เดือน', 'pointPadding'=>0, 'borderWidth'=>1, 'data' => array_map('floatval', array_values($rep[3])) ),
),
)
]);
?>
<!-- BEGIN SIDEBAR & CONTENT -->
<div class="row margin-bottom-40">
<!-- BEGIN CONTENT -->
<div class="col-md-12 col-sm-12">
<div class="content-page">
<div class="row">
<!-- BEGIN LEFT SIDEBAR -->
<div class="col-md-9 col-sm-9 blog-item">
<h2><a href="javascript:;">Corrupti quos dolores etquas</a></h2>
<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui sint blanditiis prae sentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non eleifend enim a feugiat. Pellentesque viverra vehicula sem ut volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing condimentum eleifend enim a feugiat.</p>
<blockquote>
<p>Pellentesque ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante Integer posuere erat a ante.</p>
<small>Someone famous <cite title="Source Title">Source Title</cite></small>
</blockquote>
<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut non libero consectetur adipiscing elit magna. Sed et quam lacus. Fusce condimentum eleifend enim a feugiat. Pellentesque viverra vehicula sem ut volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut non libero magna. Sed et quam lacus. Fusce condimentum eleifend enim a feugiat.</p>
<p>Culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut non libero consectetur adipiscing elit magna. Sed et quam lacus. Fusce condimentum eleifend enim a feugiat. Pellentesque viverra vehicula sem ut volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut non libero magna. Sed et quam lacus. Fusce condimentum eleifend enim a feugiat.</p>
<ul class="blog-info">
<li><i class="fa fa-user"></i> By admin</li>
<li><i class="fa fa-calendar"></i> 25/07/2013</li>
<li><i class="fa fa-comments"></i> 17</li>
<li><i class="fa fa-tags"></i> Metronic, Keenthemes, UI Design</li>
</ul>
<h2>Comments</h2>
<div class="comments">
<div class="media">
<a href="javascript:;" class="pull-left">
<img src="assets/frontend/pages/img/people/img1-small.jpg" alt="" class="media-object">
</a>
<div class="media-body">
<h4 class="media-heading">Media heading <span>5 hours ago / <a href="javascript:;">Reply</a></span></h4>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<!-- Nested media object -->
<div class="media">
<a href="javascript:;" class="pull-left">
<img src="assets/frontend/pages/img/people/img2-small.jpg" alt="" class="media-object">
</a>
<div class="media-body">
<h4 class="media-heading">Media heading <span>17 hours ago / <a href="javascript:;">Reply</a></span></h4>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
</div>
</div>
<!--end media-->
<div class="media">
<a href="javascript:;" class="pull-left">
<img src="assets/frontend/pages/img/people/img3-small.jpg" alt="" class="media-object">
</a>
<div class="media-body">
<h4 class="media-heading">Media heading <span>2 days ago / <a href="javascript:;">Reply</a></span></h4>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
</div>
</div>
<!--end media-->
</div>
</div>
<!--end media-->
<div class="media">
<a href="javascript:;" class="pull-left">
<img src="assets/frontend/pages/img/people/img4-small.jpg" alt="" class="media-object">
</a>
<div class="media-body">
<h4 class="media-heading">Media heading <span>July 25,2013 / <a href="javascript:;">Reply</a></span></h4>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
</div>
</div>
<!--end media-->
</div>
<div class="post-comment padding-top-40">
<h3>Leave a Comment</h3>
<form role="form">
<div class="form-group">
<label>Name</label>
<input class="form-control" type="text">
</div>
<div class="form-group">
<label>Email <span class="color-red">*</span></label>
<input class="form-control" type="text">
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control" rows="8"></textarea>
</div>
<p><button class="btn btn-primary" type="submit">Post a Comment</button></p>
</form>
</div>
</div>
<!-- END LEFT SIDEBAR -->
<!-- BEGIN RIGHT SIDEBAR -->
<div class="col-md-3 col-sm-3 blog-sidebar">
<!-- CATEGORIES START -->
<h2 class="no-top-space">Categories</h2>
<ul class="nav sidebar-categories margin-bottom-40">
<li><a href="javascript:;">London (18)</a></li>
<li><a href="javascript:;">Moscow (5)</a></li>
<li class="active"><a href="javascript:;">Paris (12)</a></li>
<li><a href="javascript:;">Berlin (7)</a></li>
<li><a href="javascript:;">Istanbul (3)</a></li>
</ul>
<!-- CATEGORIES END -->
<!-- BEGIN RECENT NEWS -->
<h2>Recent News</h2>
<div class="recent-news margin-bottom-10">
<div class="row margin-bottom-10">
<div class="col-md-3">
<img class="img-responsive" alt="" src="assets/frontend/pages/img/people/img2-large.jpg">
</div>
<div class="col-md-9 recent-news-inner">
<h3><a href="javascript:;">Letiusto gnissimos</a></h3>
<p>Decusamus tiusto odiodig nis simos ducimus qui sint</p>
</div>
</div>
<div class="row margin-bottom-10">
<div class="col-md-3">
<img class="img-responsive" alt="" src="assets/frontend/pages/img/people/img1-large.jpg">
</div>
<div class="col-md-9 recent-news-inner">
<h3><a href="javascript:;">Deiusto anissimos</a></h3>
<p>Decusamus tiusto odiodig nis simos ducimus qui sint</p>
</div>
</div>
<div class="row margin-bottom-10">
<div class="col-md-3">
<img class="img-responsive" alt="" src="assets/frontend/pages/img/people/img3-large.jpg">
</div>
<div class="col-md-9 recent-news-inner">
<h3><a href="javascript:;">Tesiusto baissimos</a></h3>
<p>Decusamus tiusto odiodig nis simos ducimus qui sint</p>
</div>
</div>
</div>
<!-- END RECENT NEWS -->
<!-- BEGIN BLOG TALKS -->
<div class="blog-talks margin-bottom-30">
<h2>Popular Talks</h2>
<div class="tab-style-1">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#tab-1">Multipurpose</a></li>
<li><a data-toggle="tab" href="#tab-2">Documented</a></li>
</ul>
<div class="tab-content">
<div id="tab-1" class="tab-pane row-fluid fade in active">
<p class="margin-bottom-10">Raw denim you probably haven't heard of them jean shorts Austin. eu banh mi, qui irure terry richardson ex squid Aliquip placeat salvia cillum iphone.</p>
<p><a class="more" href="javascript:;">Read more</a></p>
</div>
<div id="tab-2" class="tab-pane fade">
<p>Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. aliquip jean shorts ullamco ad vinyl aesthetic magna delectus mollit. Keytar helvetica VHS salvia..</p>
</div>
</div>
</div>
</div>
<!-- END BLOG TALKS -->
<!-- BEGIN BLOG PHOTOS STREAM -->
<div class="blog-photo-stream margin-bottom-20">
<h2>Photos Stream</h2>
<ul class="list-unstyled">
<li><a href="javascript:;"><img alt="" src="assets/frontend/pages/img/people/img5-small.jpg"></a></li>
<li><a href="javascript:;"><img alt="" src="assets/frontend/pages/img/works/img1.jpg"></a></li>
<li><a href="javascript:;"><img alt="" src="assets/frontend/pages/img/people/img4-large.jpg"></a></li>
<li><a href="javascript:;"><img alt="" src="assets/frontend/pages/img/works/img6.jpg"></a></li>
<li><a href="javascript:;"><img alt="" src="assets/frontend/pages/img/pics/img1-large.jpg"></a></li>
<li><a href="javascript:;"><img alt="" src="assets/frontend/pages/img/pics/img2-large.jpg"></a></li>
<li><a href="javascript:;"><img alt="" src="assets/frontend/pages/img/works/img3.jpg"></a></li>
<li><a href="javascript:;"><img alt="" src="assets/frontend/pages/img/people/img2-large.jpg"></a></li>
</ul>
</div>
<!-- END BLOG PHOTOS STREAM -->
<!-- BEGIN BLOG TAGS -->
<div class="blog-tags margin-bottom-20">
<h2>Tags</h2>
<ul>
<li><a href="javascript:;"><i class="fa fa-tags"></i>OS</a></li>
<li><a href="javascript:;"><i class="fa fa-tags"></i>Metronic</a></li>
<li><a href="javascript:;"><i class="fa fa-tags"></i>Dell</a></li>
<li><a href="javascript:;"><i class="fa fa-tags"></i>Conquer</a></li>
<li><a href="javascript:;"><i class="fa fa-tags"></i>MS</a></li>
<li><a href="javascript:;"><i class="fa fa-tags"></i>Google</a></li>
<li><a href="javascript:;"><i class="fa fa-tags"></i>Keenthemes</a></li>
<li><a href="javascript:;"><i class="fa fa-tags"></i>Twitter</a></li>
</ul>
</div>
<!-- END BLOG TAGS -->
</div>
<!-- END RIGHT SIDEBAR -->
</div>
</div>
</div>
<!-- END CONTENT -->
</div>
<!-- END SIDEBAR & CONTENT -->
</div>
</div>
</div>
| bsd-3-clause |
sakai135/htmlruby-firefox | data/scripts/processor.js | 6918 | 'use strict';
var prefs = self.options;
var observer;
function process() {
console.log('process() start');
var rubySelector = prefs.processInsertedContent ? 'ruby:not([hr-processed])' : 'ruby';
var rubies = document.body.querySelectorAll(rubySelector);
var rubyCount = rubies.length;
if (rubyCount < 1) {
console.log('process() end');
return;
}
stopObserver();
var isSegmented = !!document.body.querySelector(rubySelector + ' rt:nth-of-type(2)');
var isMulti = !!document.body.querySelector(rubySelector + ' rtc:nth-of-type(2)');
var dataset = [];
console.log('collect [isSegmented:' + isSegmented + ', isMulti:' + isMulti + ']');
for (let i = 0; i < rubyCount; i++) {
let ruby = rubies[i];
let rtElems = ruby.querySelectorAll('rt');
let rtCount = rtElems.length;
if (rtCount < 1) {
dataset.push(false);
continue;
}
let rt = rtElems[0];
if (!prefs.spaceRubyText && !isSegmented) {
dataset.push([0, 0, [0, 0, [[rt, 0]]]]);
continue;
}
let rpElems = ruby.querySelectorAll('rp');
let rbWidth = ruby.clientWidth;
let rubyChars = ruby.textContent.trim().length;
let groups = [];
let gElems = [[rt, 0]];
let gWidth = rt.clientWidth;
let gChars = rt.textContent.trim().length;
let rpChars = 0;
let rtChars = 0;
for (let j = 1, jMax = rtCount; j < jMax; j++) {
rt = rtElems[j];
let isFirstChild = rt.previousElementSibling === null;
let hasPrevText = false;
let isPrevElementRt = false;
let prevNode = rt.previousSibling;
let isParentRtc = rt.parentNode.nodeName.toLowerCase() === 'rtc';
let hasRp;
while (prevNode !== null) {
let nodeName = prevNode.nodeName.toLowerCase();
if (nodeName === 'rt') {
isPrevElementRt = true;
break;
}
if (nodeName === 'rb' || (nodeName === '#text' && prevNode.textContent.trim().length > 0)) {
hasPrevText = true;
break;
}
if (isParentRtc && prevNode.nodeType === Node.ELEMENT_NODE) {
break;
}
if (nodeName === 'rp') {
hasRp = true;
}
prevNode = prevNode.previousSibling;
}
if (isFirstChild || (!hasPrevText && hasRp && !isParentRtc && isPrevElementRt)) {
rtChars += gChars;
groups.push([gWidth, gChars, gElems, 0]);
gWidth = 0;
gChars = 0;
gElems = [];
}
gWidth += rt.clientWidth;
gChars += rt.textContent.trim().length;
gElems.push([rt, 0]);
}
rtChars += gChars;
groups.push([gWidth, gChars, gElems, 0]);
for (let j = 0, jMax = rpElems.length; j < jMax; j++) {
rpChars += rpElems[j].textContent.trim().length;
}
dataset.push([rbWidth, rubyChars - rtChars - rpChars, groups]);
}
if (prefs.spaceRubyText) {
console.log('space');
for (let i = 0; i < rubyCount; i++) {
let data = dataset[i];
if (!data) {
continue;
}
let ruby = rubies[i];
let rbWidth = data[0];
let rbChars = data[1];
let groups = data[2];
let maxWidth = rbWidth;
for (let j = 0, jMax = groups.length; j < jMax; j++) {
let group = groups[j];
if (group[0] > maxWidth) {
maxWidth = group[0];
}
}
if (maxWidth > rbWidth) {
ruby.style.width = maxWidth + 'px';
if (rbChars > 1) {
let perChar = (maxWidth - rbWidth) / rbChars;
ruby.style.letterSpacing = perChar + 'px';
ruby.style.textIndent = (perChar / 2) + 'px';
}
}
for (let j = 0, jMax = groups.length; j < jMax; j++) {
let group = groups[j];
let gWidth = group[0];
let gChars = group[1];
if (maxWidth > gWidth) {
let gElems = group[2];
if (gChars === 1) {
gElems[0][0].style.width = maxWidth + 'px';
} else {
let perChar = (maxWidth - gWidth) / gChars;
group[3] = perChar;
for (let k = 0, kMax = gElems.length; k < kMax; k++) {
let rt = gElems[k][0];
rt.style.letterSpacing = perChar + 'px';
rt.style.textIndent = (perChar / 2) + 'px';
}
}
}
}
}
}
if (isSegmented) {
console.log('position');
for (let i = 0; i < rubyCount; i++) {
let data = dataset[i];
let groups = data[2];
for (let j = 0, jMax = groups.length; j < jMax; j++) {
let group = groups[j];
let gElems = group[2];
let offset = 0;
let indent = group[3] / 2;
for (let k = 0, kMax = gElems.length; k < kMax; k++) {
let elem = gElems[k];
let eWidth = elem[0].clientWidth;
elem[1] = offset;
offset += eWidth - (eWidth === 0 ? 0 : indent);
}
}
}
for (let i = 0; i < rubyCount; i++) {
let data = dataset[i];
let groups = data[2];
for (let j = 0, jMax = groups.length; j < jMax; j++) {
let group = groups[j];
let gElems = group[2];
for (let k = 0, kMax = gElems.length; k < kMax; k++) {
let elem = gElems[k];
elem[0].style.marginLeft = elem[1] + 'px';
}
}
}
}
if (prefs.processInsertedContent) {
console.log('mark');
for (let i = 0; i < rubyCount; i++) {
rubies[i].setAttribute('hr-processed', 1);
}
}
startObserver();
console.log('process() end');
}
function register() {
console.log('register() start');
function checkNode(node) {
return node.nodeType === Node.ELEMENT_NODE &&
(node.nodeName.toLowerCase() === 'ruby' || node.querySelector('ruby')) &&
node.querySelector('rt');
}
function checkMutation(mutation) {
var i;
for (i = mutation.addedNodes.length; i--;) {
if (checkNode(mutation.addedNodes[i])) {
console.log('observer found inserted ruby');
return true;
}
}
return false;
}
function onMutations(mutations) {
var i, mutation;
for (i = mutations.length; i--;) {
mutation = mutations[i];
if (mutation.type === 'childList' && mutation.addedNodes && checkMutation(mutation)) {
process();
break;
}
}
}
observer = new MutationObserver(onMutations);
startObserver();
console.log('register() end');
}
function startObserver() {
if (observer) {
console.log('starting observer');
observer.observe(document.body, {
childList: true,
attributes: false,
characterData: false,
subtree: true
});
console.log('started observer');
}
}
function stopObserver() {
if (observer) {
console.log('stopping observer');
observer.disconnect();
console.log('stopped observer');
}
}
console.info(prefs);
process();
if (self.options.processInsertedContent) {
register();
}
| bsd-3-clause |
rob006/yii2 | framework/web/Session.php | 35472 | <?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\web;
use Yii;
use yii\base\Component;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
/**
* Session provides session data management and the related configurations.
*
* Session is a Web application component that can be accessed via `Yii::$app->session`.
*
* To start the session, call [[open()]]; To complete and send out session data, call [[close()]];
* To destroy the session, call [[destroy()]].
*
* Session can be used like an array to set and get session data. For example,
*
* ```php
* $session = new Session;
* $session->open();
* $value1 = $session['name1']; // get session variable 'name1'
* $value2 = $session['name2']; // get session variable 'name2'
* foreach ($session as $name => $value) // traverse all session variables
* $session['name3'] = $value3; // set session variable 'name3'
* ```
*
* Session can be extended to support customized session storage.
* To do so, override [[useCustomStorage]] so that it returns true, and
* override these methods with the actual logic about using custom storage:
* [[openSession()]], [[closeSession()]], [[readSession()]], [[writeSession()]],
* [[destroySession()]] and [[gcSession()]].
*
* Session also supports a special type of session data, called *flash messages*.
* A flash message is available only in the current request and the next request.
* After that, it will be deleted automatically. Flash messages are particularly
* useful for displaying confirmation messages. To use flash messages, simply
* call methods such as [[setFlash()]], [[getFlash()]].
*
* For more details and usage information on Session, see the [guide article on sessions](guide:runtime-sessions-cookies).
*
* @property array $allFlashes Flash messages (key => message or key => [message1, message2]). This property
* is read-only.
* @property string $cacheLimiter Current cache limiter. This property is read-only.
* @property array $cookieParams The session cookie parameters. This property is read-only.
* @property int $count The number of session variables. This property is read-only.
* @property string $flash The key identifying the flash message. Note that flash messages and normal session
* variables share the same name space. If you have a normal session variable using the same name, its value will
* be overwritten by this method. This property is write-only.
* @property float $gCProbability The probability (percentage) that the GC (garbage collection) process is
* started on every session initialization.
* @property bool $hasSessionId Whether the current request has sent the session ID.
* @property string $id The current session ID.
* @property bool $isActive Whether the session has started. This property is read-only.
* @property SessionIterator $iterator An iterator for traversing the session variables. This property is
* read-only.
* @property string $name The current session name.
* @property string $savePath The current session save path, defaults to '/tmp'.
* @property int $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up. The
* default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
* @property bool|null $useCookies The value indicating whether cookies should be used to store session IDs.
* @property bool $useCustomStorage Whether to use custom storage. This property is read-only.
* @property bool $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to
* false.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Countable
{
/**
* @var string the name of the session variable that stores the flash message data.
*/
public $flashParam = '__flash';
/**
* @var \SessionHandlerInterface|array an object implementing the SessionHandlerInterface or a configuration array. If set, will be used to provide persistency instead of build-in methods.
*/
public $handler;
/**
* @var array parameter-value pairs to override default session cookie parameters that are used for session_set_cookie_params() function
* Array may have the following possible keys: 'lifetime', 'path', 'domain', 'secure', 'httponly'
* @see https://secure.php.net/manual/en/function.session-set-cookie-params.php
*/
private $_cookieParams = ['httponly' => true];
/**
* @var $frozenSessionData array|null is used for saving session between recreations due to session parameters update.
*/
private $frozenSessionData;
/**
* Initializes the application component.
* This method is required by IApplicationComponent and is invoked by application.
*/
public function init()
{
parent::init();
register_shutdown_function([$this, 'close']);
if ($this->getIsActive()) {
Yii::warning('Session is already started', __METHOD__);
$this->updateFlashCounters();
}
}
/**
* Returns a value indicating whether to use custom session storage.
* This method should be overridden to return true by child classes that implement custom session storage.
* To implement custom session storage, override these methods: [[openSession()]], [[closeSession()]],
* [[readSession()]], [[writeSession()]], [[destroySession()]] and [[gcSession()]].
* @return bool whether to use custom storage.
*/
public function getUseCustomStorage()
{
return false;
}
/**
* Starts the session.
*/
public function open()
{
if ($this->getIsActive()) {
return;
}
$this->registerSessionHandler();
$this->setCookieParamsInternal();
YII_DEBUG ? session_start() : @session_start();
if ($this->getIsActive()) {
Yii::info('Session started', __METHOD__);
$this->updateFlashCounters();
} else {
$error = error_get_last();
$message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
Yii::error($message, __METHOD__);
}
}
/**
* Registers session handler.
* @throws \yii\base\InvalidConfigException
*/
protected function registerSessionHandler()
{
if ($this->handler !== null) {
if (!is_object($this->handler)) {
$this->handler = Yii::createObject($this->handler);
}
if (!$this->handler instanceof \SessionHandlerInterface) {
throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
}
YII_DEBUG ? session_set_save_handler($this->handler, false) : @session_set_save_handler($this->handler, false);
} elseif ($this->getUseCustomStorage()) {
if (YII_DEBUG) {
session_set_save_handler(
[$this, 'openSession'],
[$this, 'closeSession'],
[$this, 'readSession'],
[$this, 'writeSession'],
[$this, 'destroySession'],
[$this, 'gcSession']
);
} else {
@session_set_save_handler(
[$this, 'openSession'],
[$this, 'closeSession'],
[$this, 'readSession'],
[$this, 'writeSession'],
[$this, 'destroySession'],
[$this, 'gcSession']
);
}
}
}
/**
* Ends the current session and store session data.
*/
public function close()
{
if ($this->getIsActive()) {
YII_DEBUG ? session_write_close() : @session_write_close();
}
}
/**
* Frees all session variables and destroys all data registered to a session.
*
* This method has no effect when session is not [[getIsActive()|active]].
* Make sure to call [[open()]] before calling it.
* @see open()
* @see isActive
*/
public function destroy()
{
if ($this->getIsActive()) {
$sessionId = session_id();
$this->close();
$this->setId($sessionId);
$this->open();
session_unset();
session_destroy();
$this->setId($sessionId);
}
}
/**
* @return bool whether the session has started
*/
public function getIsActive()
{
return session_status() === PHP_SESSION_ACTIVE;
}
private $_hasSessionId;
/**
* Returns a value indicating whether the current request has sent the session ID.
* The default implementation will check cookie and $_GET using the session name.
* If you send session ID via other ways, you may need to override this method
* or call [[setHasSessionId()]] to explicitly set whether the session ID is sent.
* @return bool whether the current request has sent the session ID.
*/
public function getHasSessionId()
{
if ($this->_hasSessionId === null) {
$name = $this->getName();
$request = Yii::$app->getRequest();
if (!empty($_COOKIE[$name]) && ini_get('session.use_cookies')) {
$this->_hasSessionId = true;
} elseif (!ini_get('session.use_only_cookies') && ini_get('session.use_trans_sid')) {
$this->_hasSessionId = $request->get($name) != '';
} else {
$this->_hasSessionId = false;
}
}
return $this->_hasSessionId;
}
/**
* Sets the value indicating whether the current request has sent the session ID.
* This method is provided so that you can override the default way of determining
* whether the session ID is sent.
* @param bool $value whether the current request has sent the session ID.
*/
public function setHasSessionId($value)
{
$this->_hasSessionId = $value;
}
/**
* Gets the session ID.
* This is a wrapper for [PHP session_id()](https://secure.php.net/manual/en/function.session-id.php).
* @return string the current session ID
*/
public function getId()
{
return session_id();
}
/**
* Sets the session ID.
* This is a wrapper for [PHP session_id()](https://secure.php.net/manual/en/function.session-id.php).
* @param string $value the session ID for the current session
*/
public function setId($value)
{
session_id($value);
}
/**
* Updates the current session ID with a newly generated one.
*
* Please refer to <https://secure.php.net/session_regenerate_id> for more details.
*
* This method has no effect when session is not [[getIsActive()|active]].
* Make sure to call [[open()]] before calling it.
*
* @param bool $deleteOldSession Whether to delete the old associated session file or not.
* @see open()
* @see isActive
*/
public function regenerateID($deleteOldSession = false)
{
if ($this->getIsActive()) {
// add @ to inhibit possible warning due to race condition
// https://github.com/yiisoft/yii2/pull/1812
if (YII_DEBUG && !headers_sent()) {
session_regenerate_id($deleteOldSession);
} else {
@session_regenerate_id($deleteOldSession);
}
}
}
/**
* Gets the name of the current session.
* This is a wrapper for [PHP session_name()](https://secure.php.net/manual/en/function.session-name.php).
* @return string the current session name
*/
public function getName()
{
return session_name();
}
/**
* Sets the name for the current session.
* This is a wrapper for [PHP session_name()](https://secure.php.net/manual/en/function.session-name.php).
* @param string $value the session name for the current session, must be an alphanumeric string.
* It defaults to "PHPSESSID".
*/
public function setName($value)
{
$this->freeze();
session_name($value);
$this->unfreeze();
}
/**
* Gets the current session save path.
* This is a wrapper for [PHP session_save_path()](https://secure.php.net/manual/en/function.session-save-path.php).
* @return string the current session save path, defaults to '/tmp'.
*/
public function getSavePath()
{
return session_save_path();
}
/**
* Sets the current session save path.
* This is a wrapper for [PHP session_save_path()](https://secure.php.net/manual/en/function.session-save-path.php).
* @param string $value the current session save path. This can be either a directory name or a [path alias](guide:concept-aliases).
* @throws InvalidArgumentException if the path is not a valid directory
*/
public function setSavePath($value)
{
$path = Yii::getAlias($value);
if (is_dir($path)) {
session_save_path($path);
} else {
throw new InvalidArgumentException("Session save path is not a valid directory: $value");
}
}
/**
* @return array the session cookie parameters.
* @see https://secure.php.net/manual/en/function.session-get-cookie-params.php
*/
public function getCookieParams()
{
return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
}
/**
* Sets the session cookie parameters.
* The cookie parameters passed to this method will be merged with the result
* of `session_get_cookie_params()`.
* @param array $value cookie parameters, valid keys include: `lifetime`, `path`, `domain`, `secure` and `httponly`.
* Starting with Yii 2.0.21 `sameSite` is also supported. It requires PHP version 7.3.0 or higher.
* For securtiy, an exception will be thrown if `sameSite` is set while using an unsupported version of PHP.
* To use this feature across different PHP versions check the version first. E.g.
* ```php
* [
* 'sameSite' => PHP_VERSION_ID >= 70300 ? yii\web\Cookie::SAME_SITE_LAX : null,
* ]
* ```
* See https://www.owasp.org/index.php/SameSite for more information about `sameSite`.
*
* @throws InvalidArgumentException if the parameters are incomplete.
* @see https://secure.php.net/manual/en/function.session-set-cookie-params.php
*/
public function setCookieParams(array $value)
{
$this->_cookieParams = $value;
}
/**
* Sets the session cookie parameters.
* This method is called by [[open()]] when it is about to open the session.
* @throws InvalidArgumentException if the parameters are incomplete.
* @see https://secure.php.net/manual/en/function.session-set-cookie-params.php
*/
private function setCookieParamsInternal()
{
$data = $this->getCookieParams();
if (isset($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly'])) {
if (PHP_VERSION_ID >= 70300) {
session_set_cookie_params($data);
} else {
if (!empty($data['samesite'])) {
throw new InvalidConfigException('samesite cookie is not supported by PHP versions < 7.3.0 (set it to null in this environment)');
}
session_set_cookie_params($data['lifetime'], $data['path'], $data['domain'], $data['secure'], $data['httponly']);
}
} else {
throw new InvalidArgumentException('Please make sure cookieParams contains these elements: lifetime, path, domain, secure and httponly.');
}
}
/**
* Returns the value indicating whether cookies should be used to store session IDs.
* @return bool|null the value indicating whether cookies should be used to store session IDs.
* @see setUseCookies()
*/
public function getUseCookies()
{
if (ini_get('session.use_cookies') === '0') {
return false;
} elseif (ini_get('session.use_only_cookies') === '1') {
return true;
}
return null;
}
/**
* Sets the value indicating whether cookies should be used to store session IDs.
*
* Three states are possible:
*
* - true: cookies and only cookies will be used to store session IDs.
* - false: cookies will not be used to store session IDs.
* - null: if possible, cookies will be used to store session IDs; if not, other mechanisms will be used (e.g. GET parameter)
*
* @param bool|null $value the value indicating whether cookies should be used to store session IDs.
*/
public function setUseCookies($value)
{
$this->freeze();
if ($value === false) {
ini_set('session.use_cookies', '0');
ini_set('session.use_only_cookies', '0');
} elseif ($value === true) {
ini_set('session.use_cookies', '1');
ini_set('session.use_only_cookies', '1');
} else {
ini_set('session.use_cookies', '1');
ini_set('session.use_only_cookies', '0');
}
$this->unfreeze();
}
/**
* @return float the probability (percentage) that the GC (garbage collection) process is started on every session initialization.
*/
public function getGCProbability()
{
return (float) (ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
}
/**
* @param float $value the probability (percentage) that the GC (garbage collection) process is started on every session initialization.
* @throws InvalidArgumentException if the value is not between 0 and 100.
*/
public function setGCProbability($value)
{
$this->freeze();
if ($value >= 0 && $value <= 100) {
// percent * 21474837 / 2147483647 ≈ percent * 0.01
ini_set('session.gc_probability', floor($value * 21474836.47));
ini_set('session.gc_divisor', 2147483647);
} else {
throw new InvalidArgumentException('GCProbability must be a value between 0 and 100.');
}
$this->unfreeze();
}
/**
* @return bool whether transparent sid support is enabled or not, defaults to false.
*/
public function getUseTransparentSessionID()
{
return ini_get('session.use_trans_sid') == 1;
}
/**
* @param bool $value whether transparent sid support is enabled or not.
*/
public function setUseTransparentSessionID($value)
{
$this->freeze();
ini_set('session.use_trans_sid', $value ? '1' : '0');
$this->unfreeze();
}
/**
* @return int the number of seconds after which data will be seen as 'garbage' and cleaned up.
* The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).
*/
public function getTimeout()
{
return (int) ini_get('session.gc_maxlifetime');
}
/**
* @param int $value the number of seconds after which data will be seen as 'garbage' and cleaned up
*/
public function setTimeout($value)
{
$this->freeze();
ini_set('session.gc_maxlifetime', $value);
$this->unfreeze();
}
/**
* Session open handler.
* This method should be overridden if [[useCustomStorage]] returns true.
* @internal Do not call this method directly.
* @param string $savePath session save path
* @param string $sessionName session name
* @return bool whether session is opened successfully
*/
public function openSession($savePath, $sessionName)
{
return true;
}
/**
* Session close handler.
* This method should be overridden if [[useCustomStorage]] returns true.
* @internal Do not call this method directly.
* @return bool whether session is closed successfully
*/
public function closeSession()
{
return true;
}
/**
* Session read handler.
* This method should be overridden if [[useCustomStorage]] returns true.
* @internal Do not call this method directly.
* @param string $id session ID
* @return string the session data
*/
public function readSession($id)
{
return '';
}
/**
* Session write handler.
* This method should be overridden if [[useCustomStorage]] returns true.
* @internal Do not call this method directly.
* @param string $id session ID
* @param string $data session data
* @return bool whether session write is successful
*/
public function writeSession($id, $data)
{
return true;
}
/**
* Session destroy handler.
* This method should be overridden if [[useCustomStorage]] returns true.
* @internal Do not call this method directly.
* @param string $id session ID
* @return bool whether session is destroyed successfully
*/
public function destroySession($id)
{
return true;
}
/**
* Session GC (garbage collection) handler.
* This method should be overridden if [[useCustomStorage]] returns true.
* @internal Do not call this method directly.
* @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
* @return bool whether session is GCed successfully
*/
public function gcSession($maxLifetime)
{
return true;
}
/**
* Returns an iterator for traversing the session variables.
* This method is required by the interface [[\IteratorAggregate]].
* @return SessionIterator an iterator for traversing the session variables.
*/
public function getIterator()
{
$this->open();
return new SessionIterator();
}
/**
* Returns the number of items in the session.
* @return int the number of session variables
*/
public function getCount()
{
$this->open();
return count($_SESSION);
}
/**
* Returns the number of items in the session.
* This method is required by [[\Countable]] interface.
* @return int number of items in the session.
*/
public function count()
{
return $this->getCount();
}
/**
* Returns the session variable value with the session variable name.
* If the session variable does not exist, the `$defaultValue` will be returned.
* @param string $key the session variable name
* @param mixed $defaultValue the default value to be returned when the session variable does not exist.
* @return mixed the session variable value, or $defaultValue if the session variable does not exist.
*/
public function get($key, $defaultValue = null)
{
$this->open();
return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
}
/**
* Adds a session variable.
* If the specified name already exists, the old value will be overwritten.
* @param string $key session variable name
* @param mixed $value session variable value
*/
public function set($key, $value)
{
$this->open();
$_SESSION[$key] = $value;
}
/**
* Removes a session variable.
* @param string $key the name of the session variable to be removed
* @return mixed the removed value, null if no such session variable.
*/
public function remove($key)
{
$this->open();
if (isset($_SESSION[$key])) {
$value = $_SESSION[$key];
unset($_SESSION[$key]);
return $value;
}
return null;
}
/**
* Removes all session variables.
*/
public function removeAll()
{
$this->open();
foreach (array_keys($_SESSION) as $key) {
unset($_SESSION[$key]);
}
}
/**
* @param mixed $key session variable name
* @return bool whether there is the named session variable
*/
public function has($key)
{
$this->open();
return isset($_SESSION[$key]);
}
/**
* Updates the counters for flash messages and removes outdated flash messages.
* This method should only be called once in [[init()]].
*/
protected function updateFlashCounters()
{
$counters = $this->get($this->flashParam, []);
if (is_array($counters)) {
foreach ($counters as $key => $count) {
if ($count > 0) {
unset($counters[$key], $_SESSION[$key]);
} elseif ($count == 0) {
$counters[$key]++;
}
}
$_SESSION[$this->flashParam] = $counters;
} else {
// fix the unexpected problem that flashParam doesn't return an array
unset($_SESSION[$this->flashParam]);
}
}
/**
* Returns a flash message.
* @param string $key the key identifying the flash message
* @param mixed $defaultValue value to be returned if the flash message does not exist.
* @param bool $delete whether to delete this flash message right after this method is called.
* If false, the flash message will be automatically deleted in the next request.
* @return mixed the flash message or an array of messages if addFlash was used
* @see setFlash()
* @see addFlash()
* @see hasFlash()
* @see getAllFlashes()
* @see removeFlash()
*/
public function getFlash($key, $defaultValue = null, $delete = false)
{
$counters = $this->get($this->flashParam, []);
if (isset($counters[$key])) {
$value = $this->get($key, $defaultValue);
if ($delete) {
$this->removeFlash($key);
} elseif ($counters[$key] < 0) {
// mark for deletion in the next request
$counters[$key] = 1;
$_SESSION[$this->flashParam] = $counters;
}
return $value;
}
return $defaultValue;
}
/**
* Returns all flash messages.
*
* You may use this method to display all the flash messages in a view file:
*
* ```php
* <?php
* foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
* echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
* } ?>
* ```
*
* With the above code you can use the [bootstrap alert][] classes such as `success`, `info`, `danger`
* as the flash message key to influence the color of the div.
*
* Note that if you use [[addFlash()]], `$message` will be an array, and you will have to adjust the above code.
*
* [bootstrap alert]: http://getbootstrap.com/components/#alerts
*
* @param bool $delete whether to delete the flash messages right after this method is called.
* If false, the flash messages will be automatically deleted in the next request.
* @return array flash messages (key => message or key => [message1, message2]).
* @see setFlash()
* @see addFlash()
* @see getFlash()
* @see hasFlash()
* @see removeFlash()
*/
public function getAllFlashes($delete = false)
{
$counters = $this->get($this->flashParam, []);
$flashes = [];
foreach (array_keys($counters) as $key) {
if (array_key_exists($key, $_SESSION)) {
$flashes[$key] = $_SESSION[$key];
if ($delete) {
unset($counters[$key], $_SESSION[$key]);
} elseif ($counters[$key] < 0) {
// mark for deletion in the next request
$counters[$key] = 1;
}
} else {
unset($counters[$key]);
}
}
$_SESSION[$this->flashParam] = $counters;
return $flashes;
}
/**
* Sets a flash message.
* A flash message will be automatically deleted after it is accessed in a request and the deletion will happen
* in the next request.
* If there is already an existing flash message with the same key, it will be overwritten by the new one.
* @param string $key the key identifying the flash message. Note that flash messages
* and normal session variables share the same name space. If you have a normal
* session variable using the same name, its value will be overwritten by this method.
* @param mixed $value flash message
* @param bool $removeAfterAccess whether the flash message should be automatically removed only if
* it is accessed. If false, the flash message will be automatically removed after the next request,
* regardless if it is accessed or not. If true (default value), the flash message will remain until after
* it is accessed.
* @see getFlash()
* @see addFlash()
* @see removeFlash()
*/
public function setFlash($key, $value = true, $removeAfterAccess = true)
{
$counters = $this->get($this->flashParam, []);
$counters[$key] = $removeAfterAccess ? -1 : 0;
$_SESSION[$key] = $value;
$_SESSION[$this->flashParam] = $counters;
}
/**
* Adds a flash message.
* If there are existing flash messages with the same key, the new one will be appended to the existing message array.
* @param string $key the key identifying the flash message.
* @param mixed $value flash message
* @param bool $removeAfterAccess whether the flash message should be automatically removed only if
* it is accessed. If false, the flash message will be automatically removed after the next request,
* regardless if it is accessed or not. If true (default value), the flash message will remain until after
* it is accessed.
* @see getFlash()
* @see setFlash()
* @see removeFlash()
*/
public function addFlash($key, $value = true, $removeAfterAccess = true)
{
$counters = $this->get($this->flashParam, []);
$counters[$key] = $removeAfterAccess ? -1 : 0;
$_SESSION[$this->flashParam] = $counters;
if (empty($_SESSION[$key])) {
$_SESSION[$key] = [$value];
} elseif (is_array($_SESSION[$key])) {
$_SESSION[$key][] = $value;
} else {
$_SESSION[$key] = [$_SESSION[$key], $value];
}
}
/**
* Removes a flash message.
* @param string $key the key identifying the flash message. Note that flash messages
* and normal session variables share the same name space. If you have a normal
* session variable using the same name, it will be removed by this method.
* @return mixed the removed flash message. Null if the flash message does not exist.
* @see getFlash()
* @see setFlash()
* @see addFlash()
* @see removeAllFlashes()
*/
public function removeFlash($key)
{
$counters = $this->get($this->flashParam, []);
$value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null;
unset($counters[$key], $_SESSION[$key]);
$_SESSION[$this->flashParam] = $counters;
return $value;
}
/**
* Removes all flash messages.
* Note that flash messages and normal session variables share the same name space.
* If you have a normal session variable using the same name, it will be removed
* by this method.
* @see getFlash()
* @see setFlash()
* @see addFlash()
* @see removeFlash()
*/
public function removeAllFlashes()
{
$counters = $this->get($this->flashParam, []);
foreach (array_keys($counters) as $key) {
unset($_SESSION[$key]);
}
unset($_SESSION[$this->flashParam]);
}
/**
* Returns a value indicating whether there are flash messages associated with the specified key.
* @param string $key key identifying the flash message type
* @return bool whether any flash messages exist under specified key
*/
public function hasFlash($key)
{
return $this->getFlash($key) !== null;
}
/**
* This method is required by the interface [[\ArrayAccess]].
* @param mixed $offset the offset to check on
* @return bool
*/
public function offsetExists($offset)
{
$this->open();
return isset($_SESSION[$offset]);
}
/**
* This method is required by the interface [[\ArrayAccess]].
* @param int $offset the offset to retrieve element.
* @return mixed the element at the offset, null if no element is found at the offset
*/
public function offsetGet($offset)
{
$this->open();
return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
}
/**
* This method is required by the interface [[\ArrayAccess]].
* @param int $offset the offset to set element
* @param mixed $item the element value
*/
public function offsetSet($offset, $item)
{
$this->open();
$_SESSION[$offset] = $item;
}
/**
* This method is required by the interface [[\ArrayAccess]].
* @param mixed $offset the offset to unset element
*/
public function offsetUnset($offset)
{
$this->open();
unset($_SESSION[$offset]);
}
/**
* If session is started it's not possible to edit session ini settings. In PHP7.2+ it throws exception.
* This function saves session data to temporary variable and stop session.
* @since 2.0.14
*/
protected function freeze()
{
if ($this->getIsActive()) {
if (isset($_SESSION)) {
$this->frozenSessionData = $_SESSION;
}
$this->close();
Yii::info('Session frozen', __METHOD__);
}
}
/**
* Starts session and restores data from temporary variable
* @since 2.0.14
*/
protected function unfreeze()
{
if (null !== $this->frozenSessionData) {
YII_DEBUG ? session_start() : @session_start();
if ($this->getIsActive()) {
Yii::info('Session unfrozen', __METHOD__);
} else {
$error = error_get_last();
$message = isset($error['message']) ? $error['message'] : 'Failed to unfreeze session.';
Yii::error($message, __METHOD__);
}
$_SESSION = $this->frozenSessionData;
$this->frozenSessionData = null;
}
}
/**
* Set cache limiter
*
* @param string $cacheLimiter
* @since 2.0.14
*/
public function setCacheLimiter($cacheLimiter)
{
$this->freeze();
session_cache_limiter($cacheLimiter);
$this->unfreeze();
}
/**
* Returns current cache limiter
*
* @return string current cache limiter
* @since 2.0.14
*/
public function getCacheLimiter()
{
return session_cache_limiter();
}
}
| bsd-3-clause |
webchanger/abuzaid | frontend/models/PagedetailsSearch.php | 1835 | <?php
namespace frontend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\Pagedetails;
/**
* PagedetailsSearch represents the model behind the search form about `frontend\models\Pagedetails`.
*/
class PagedetailsSearch extends Pagedetails
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'page_id', 'sort_value'], 'integer'],
[['para_title', 'para_detail', 'created_at', 'updated_at'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Pagedetails::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'page_id' => $this->page_id,
'sort_value' => $this->sort_value,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'para_title', $this->para_title])
->andFilterWhere(['like', 'para_detail', $this->para_detail]);
return $dataProvider;
}
}
| bsd-3-clause |
Crystalnix/memorango | src/server/server_test.go | 13047 | package server
import (
"testing"
"net"
"fmt"
"time"
"bytes"
"os"
"bufio"
"log"
"tools/protocol"
)
var test_port = "60000"
var test_address = "127.0.0.1:" + test_port
func TestServerRunAndStop(t *testing.T){
fmt.Println("TestServerRunAndStop")
// var test_port = "60000"
// var test_address = "127.0.0.1:" + test_port
srv := NewServer(test_port, "", "", 1024, false, false, 2, 1024)
srv.RunServer()
defer srv.StopServer() // if test will be broken down before server will be closed.
time.Sleep(time.Millisecond * time.Duration(10)) // Let's wait a bit while goroutines will start
connection, err := net.Dial("tcp", test_address)
if err != nil {
t.Fatalf("Server wasn't run: %s", err)
}
var test_msg = []byte("Test1\r\n")
_, err = connection.Write(test_msg)
if err != nil {
t.Fatalf("Stream is unavailable to transmit data: ", err)
}
var response = make([]byte, 255)
fmt.Println("Trying to read response...")
_, err = connection.Read(response[0: ])
if err != nil {
t.Fatalf("Stream is unavailable to transmit data: ", err)
}
if len(response) == 0 {
t.Fatalf("Server doesn't response.")
}
fmt.Println("Response: ", string(response))
srv.StopServer()
connection.Close()
connection, err = net.Dial("tcp", test_address)
if err == nil {
t.Fatalf("Server is still running at %s", test_address)
}
}
func TestServerConsistenceAndConnections(t *testing.T){
fmt.Println("TestServerConsistenceAndConnections")
// var test_port = "60001"
// var test_address = "127.0.0.1:" + test_port
srv := NewServer(test_port, "", "", 1024, false, false, 2, 1024)
srv.RunServer()
time.Sleep(time.Millisecond * time.Duration(10))
defer srv.StopServer()
connection, err := net.Dial("tcp", test_address)
// notice, that connection can be opened in case of failure.
if err != nil {
t.Fatalf("Server wasn't run: %s", err)
}
if srv.tcp_port != test_port || srv.sockets == nil || len(srv.sockets) != 1 || srv.storage == nil {
t.Fatalf("Unexpected consistence: %s, %s, %s", srv.tcp_port, srv.sockets, srv.storage)
}
var test_msg = []byte("Test1\r\n")
_, err = connection.Write(test_msg)
if err != nil {
t.Fatalf("Stream is unavailable to transmit data: ", err)
}
remote_connection := srv.connections[connection.LocalAddr().String()]
if len(srv.connections) != 1 || remote_connection == nil {
t.Fatalf("Connection wasn't cached: ", len(srv.connections))
}
if remote_connection.LocalAddr().String() != connection.RemoteAddr().String() ||
remote_connection.RemoteAddr().String() != connection.LocalAddr().String() {
t.Fatalf("Connections mismatch")
}
connection.Close()
}
func TestServerResponseAndConnections(t *testing.T){
fmt.Println("TestServerResponseAndConnections")
// var test_port = "60002"
// var test_address = "127.0.0.1:" + test_port
srv := NewServer(test_port, "", "", 1024, false, false, 2, 1024)
srv.RunServer()
defer srv.StopServer()
time.Sleep(time.Millisecond * time.Duration(10))
connection, err := net.Dial("tcp", test_address)
var test_msg = []byte("Test1\r\n")
_, err = connection.Write(test_msg)
if err != nil {
t.Fatalf("Stream is unavailable to transmit data: ", err)
}
remote_connection := srv.connections[connection.LocalAddr().String()]
if !srv.makeResponse(remote_connection, []byte("TestResponse"), 12){
t.Fatalf("Server is unavailable to make response.")
}
var test_response = make([]byte, 12)
n, err := connection.Read(test_response[0 : ])
if n != 12 || err != nil {
t.Fatalf("Connection stream is empty: ", n, err)
}
if string(test_response) != "TestResponse" {
t.Fatalf("Unexpected response:< %s >", string(test_response))
}
if !srv.breakConnection(remote_connection){
t.Fatalf("Server is unavailable to break connection at %s", remote_connection.RemoteAddr().String())
}
if len(srv.connections) != 0 {
t.Fatalf("Connection is still alive: ", srv.connections)
}
connection.Close()
}
func TestServerReader1(t *testing.T){
var test_msg = []byte("TEST\r\nwith-\r\n-terminators\r\n")
var byteBuf = bytes.NewBuffer(test_msg)
reader := bufio.NewReader(byteBuf)
res, n, err := readRequest(reader, -1)
if err != nil {
t.Fatalf("Unexpected behaviour: ", err, res, n)
}
if string(res[0 : n - 2]) != "TEST" {
t.Fatalf("Unexpected response: %s", string(res))
}
res, n, err = readRequest(reader, 19)
if err != nil {
t.Fatalf("Unexpected behaviour: ", err, res, n)
}
if string(res[0 : n - 2]) != "with-\r\n-terminators" {
t.Fatalf("Unexpected response: %s", string(res))
}
}
func TestServerReader2(t *testing.T){
var test_msg = make([]byte, 300)
var byteBuf = bytes.NewBuffer(test_msg)
reader := bufio.NewReader(byteBuf)
res, n, err := readRequest(reader, -1)
if err == nil {
t.Fatalf("Unexpected behaviour: ", res, n)
}
byteBuf = bytes.NewBuffer(test_msg)
reader = bufio.NewReader(byteBuf)
res, n, err = readRequest(reader, 42)
if err == nil {
t.Fatalf("Unexpected behaviour: ", res, n)
}
test_msg[298] = '\r'
test_msg[299] = '\n'
byteBuf = bytes.NewBuffer(test_msg)
reader = bufio.NewReader(byteBuf)
res, n, err = readRequest(reader, 298)
if err != nil {
t.Fatalf("Unexpected behaviour: ", err, res, n)
}
}
//TODO: To figure out how to check consistence of std outputs, or at least last n symbols of it.
func testReadOsOutput(output *os.File, offset int) []byte{
var buf []byte
log.Println(output.Seek(int64(offset), 2))
log.Println(output.Read(buf))
return buf
}
func TestServerLoggerTestSuite1(t *testing.T){
logger0 := NewServerLogger(0)
if logger0.error.Flags() != log.Ldate | log.Ltime | log.Lshortfile ||
logger0.warning.Flags() != 0 || logger0.info.Flags() != 0 ||
logger0.syslogger.Flags() != log.Ldate | log.Ltime | log.Lshortfile {
t.Fatalf("Wrong flags of logger components:\nerr, warn, inf, sys\n%d, %d, %d, %d\n%d, %d, %d, %d\n",
logger0.error.Flags(), logger0.warning.Flags(), logger0.info.Flags(), logger0.syslogger.Flags(),
log.Ldate | log.Ltime | log.Lshortfile, 0, 0, log.Ldate | log.Ltime | log.Lshortfile)
}
// var buf []byte
// logger0.Error("TestError")
// buf = testReadOsOutput(os.Stderr, 9)
// if string(buf) != "TestError" {
// t.Fatalf("Unexpected message: %s ;", string(buf))
// }
// logger0.Warning("TestWarning")
// buf = testReadOsOutput(os.Stdout, 11)
// if string(buf) == "TestWarning" {
// t.Fatalf("Unexpected logger behavior: depth permission corrupted.")
// }
// logger0.Info("TestInfo")
// buf = testReadOsOutput(os.Stdout, 8)
// if string(buf) == "TestInfo" {
// t.Fatalf("Unexpected logger behavior: depth permission corrupted.")
// }
}
func TestServerLoggerTestSuite2(t *testing.T){
logger0 := NewServerLogger(1)
if logger0.error.Flags() != log.Ldate | log.Ltime | log.Lshortfile ||
logger0.warning.Flags() != log.Ldate | log.Ltime | log.Lshortfile || logger0.info.Flags() != 0 ||
logger0.syslogger.Flags() != log.Ldate | log.Ltime | log.Lshortfile {
t.Fatalf("Wrong flags of logger components:\nerr, warn, inf, sys\n%d, %d, %d, %d\n%d, %d, %d, %d\n",
logger0.error.Flags(), logger0.warning.Flags(), logger0.info.Flags(), logger0.syslogger.Flags(),
log.Ldate | log.Ltime | log.Lshortfile,
log.Ldate | log.Ltime | log.Lshortfile, 0, log.Ldate | log.Ltime | log.Lshortfile)
}
// var buf []byte
// logger0.Error("TestError")
// buf = testReadOsOutput(os.Stderr, 9)
// if string(buf) != "TestError" {
// t.Fatalf("Unexpected message: %s ;", string(buf))
// }
// logger0.Warning("TestWarning")
// buf = testReadOsOutput(os.Stdout, 11)
// if string(buf) != "TestWarning" {
// t.Fatalf("Unexpected logger behavior: depth permission corrupted.")
// }
// logger0.Info("TestInfo")
// buf = testReadOsOutput(os.Stdout, 8)
// if string(buf) == "TestInfo" {
// t.Fatalf("Unexpected logger behavior: depth permission corrupted.")
// }
}
func TestServerLoggerTestSuite3(t *testing.T){
logger0 := NewServerLogger(2)
if logger0.error.Flags() != log.Ldate | log.Ltime | log.Lshortfile ||
logger0.warning.Flags() != log.Ldate | log.Ltime | log.Lshortfile ||
logger0.info.Flags() != log.Ldate | log.Ltime ||
logger0.syslogger.Flags() != log.Ldate | log.Ltime | log.Lshortfile {
t.Fatalf("Wrong flags of logger components:\nerr, warn, inf, sys\n%d, %d, %d, %d\n%d, %d, %d, %d\n",
logger0.error.Flags(), logger0.warning.Flags(), logger0.info.Flags(), logger0.syslogger.Flags(),
log.Ldate | log.Ltime | log.Lshortfile,
log.Ldate | log.Ltime | log.Lshortfile, log.Ldate | log.Ltime, log.Ldate | log.Ltime | log.Lshortfile)
}
// var buf []byte
// logger0.Error("TestError")
// buf = testReadOsOutput(os.Stderr, 9)
// if string(buf) != "TestError" {
// t.Fatalf("Unexpected message: %s ;", string(buf))
// }
// logger0.Warning("TestWarning")
// buf = testReadOsOutput(os.Stdout, 11)
// if string(buf) != "TestWarning" {
// t.Fatalf("Unexpected logger behavior: depth permission corrupted.")
// }
// logger0.Info("TestInfo")
// buf = testReadOsOutput(os.Stdout, 8)
// if string(buf) != "TestInfo" {
// t.Fatalf("Unexpected logger behavior: depth permission corrupted.")
// }
}
func TestServerConnectionsLim(t *testing.T){
fmt.Println("TestServerConnectionsLim")
srv := NewServer(test_port, "", "", 2, false, false, 2, 1024)
srv.RunServer()
defer srv.StopServer()
time.Sleep(time.Millisecond * time.Duration(10)) // Let's wait a bit while goroutines will start
connection1, err := net.Dial("tcp", test_address)
//defer connection1.Close()
if err != nil{
t.Fatalf("Unexpected server behavior.", err)
}
_, err = connection1.Write([]byte("TEST"))
if err != nil{
t.Fatalf("Unexpected server behavior.", err)
}
connection2, err := net.Dial("tcp", test_address)
//defer connection2.Close()
if err != nil{
t.Fatalf("Unexpected server behavior.", err)
}
_, err = connection2.Write([]byte("TEST"))
if err != nil{
t.Fatalf("Unexpected server behavior.", err)
}
excess_conn, err := net.Dial("tcp", test_address)
//defer excess_conn.Close()
if err != nil{
t.Fatalf("Unexpected server behavior.", err)
}
_, err = excess_conn.Write([]byte("TEST"))
if err != nil{
t.Fatalf("Unexpected server behavior.", err)
}
test_response := make([]byte, 10)
n, err := excess_conn.Read(test_response[ : ])
if err == nil || n != 0 {
t.Fatalf("Unexpected behavior: connection shouldn't be handled.")
}
connection1.Close()
connection2.Close()
excess_conn.Close()
}
func TestServerConnectionListener(t *testing.T){
fmt.Println("TestServerConnectionListener")
srv := NewServer(test_port, "", "123.45.67.89", 1024, false, false, 2, 1024)
srv.RunServer()
defer srv.StopServer()
time.Sleep(time.Millisecond * time.Duration(10)) // Let's wait a bit while goroutines will start
conn, err := net.Dial("tcp", test_address)
if err != nil{
t.Fatalf("Unexpected server behavior.", err)
}
_, err = conn.Write([]byte("You'll never see me"))
if err != nil{
t.Fatalf("Unexpected server behavior.", err)
}
test_response := make([]byte, 10)
n, err := conn.Read(test_response[ : ])
if err == nil || n != 0 || string(test_response) == "ERROR\r\n"{
t.Fatalf("Unexpected behavior: connection shouldn't be handled.")
}
conn.Close()
}
func TestServerForbiddenCmds(t *testing.T){
fmt.Println("TestServerForbiddenCmds")
srv := NewServer(test_port, "", "", 1024, true, true, 2, 1024)
srv.RunServer()
defer srv.StopServer()
time.Sleep(time.Millisecond * time.Duration(10)) // Let's wait a bit while goroutines will start
var test_response = make([]byte, 42)
connection, err := net.Dial("tcp", test_address)
//defer connection.Close()
if err != nil{
t.Fatalf("Unexpected server behavior.", err)
}
_, err = connection.Write([]byte("cas key 0 0 4 424242\r\nTEST\r\n"))
if err != nil {
t.Fatalf("Unexpected server behavior.", err)
}
n, err := connection.Read(test_response[ : ])
if err != nil || n == 0 {
t.Fatalf("Unexpected server behavior.", err)
}
if string(test_response) == protocol.NOT_FOUND {
t.Fatalf("Unexpected server behavior: forbidden command CAS was handled.")
}
_, err = connection.Write([]byte("flush_all\r\n"))
if err != nil {
t.Fatalf("Unexpected server behavior.", err)
}
n, err = connection.Read(test_response[ : ])
if err != nil || n == 0 {
t.Fatalf("Unexpected server behavior.", err)
}
if string(test_response) == "OK\r\n" {
t.Fatalf("Unexpected server behavior: forbidden command FLUSH_ALL was handled.")
}
_, err = connection.Write([]byte("gets key\r\n"))
if err != nil {
t.Fatalf("Unexpected server behavior.", err)
}
n, err = connection.Read(test_response[ : ])
if err != nil || n == 0 {
t.Fatalf("Unexpected server behavior.", err)
}
if string(test_response) == "END\r\n" {
t.Fatalf("Unexpected server behavior: forbidden command GETS/CAS was handled.")
}
connection.Close()
}
func TestServerWaitSuite(t *testing.T) {
srv := NewServer(test_port, "", "", 1024, false, false, 2, 1024)
start := time.Now().UnixNano()
srv.threads = 0
srv.Wait()
end := time.Now().UnixNano()
if end-start > 1000 {
t.Fatalf("Unexpected waiting behaviour: wait had to finish immidiatelly: %d.", end-start)
}
}
| bsd-3-clause |
nvbn/django-session-csrf | example/forms.py | 20 | __author__ = 'nvbn'
| bsd-3-clause |
OS2World/DEV-SAMPLES-The-IBM-Developer-Connection-Release-2--Volume-2_CD4 | javaxmp/javaxmp/lang/RuntimeExec/RuntimeExec.java | 2133 | //------------------------------------------------------------------------
// File Name: RuntimeExec.java
// Description: Tests the exec method of the runtime class.
// Executes operating system specific commands.
//
// Modification History
// Date Developer Defect Tag Description
// ------ --------- ------- ----------- ----------------------------------
// 041498 DOBecker Created.
//------------------------------------------------------------------------
import java.io.*;
public class RuntimeExec {
public static void main( String [] args ) {
System.out.println( "Java version is " + System.getProperty( "java.version" ) +
" by " + System.getProperty( "java.vendor" ) + "." );
System.out.println( "The operating system name is " + System.getProperty( "os.name" ) +
", version " + System.getProperty( "os.version" ) + ".\n" );
// Run each arg as a command.
for ( int i = 0; i < args.length; i++ ) {
try {
// Some command sends information to stdout. Other commands send info to stderr.
// For example, run this command with "net" or "attrib".
// Does not work with inherent commands like dir and cd.
Process p = Runtime.getRuntime().exec( args[ i ] );
String line;
System.out.println( "The contents of stdout is:" );
DataInputStream dis = new DataInputStream( p.getInputStream() );
while ( null != ( line = dis.readLine() ))
System.out.println( line );
System.out.println( "The contents of stderr is:" );
dis = new DataInputStream( p.getErrorStream() );
while ( null != ( line = dis.readLine() ))
System.out.println( line );
// Wait for pricess to finish and print exit value.
p.waitFor();
System.out.println( "The process exit value of " + args[ i ] + " is " + p.exitValue() + "." );
} catch (Exception e ) {
e.printStackTrace();
} /* endcatch */
} /* endfor */
}
}
| bsd-3-clause |
cherokee/pyscgi | CTK/SortableList.py | 4074 | # CTK: Cherokee Toolkit
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2009 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
from Table import Table
from Server import get_server
from PageCleaner import Uniq_Block
from Server import publish, post, cfg, cfg_reply_ajax_ok
HEADER = [
'<script type="text/javascript" src="/CTK/js/jquery.tablednd_0_5.js"></script>'
]
JS_INIT = """
$("#%(id)s").tableDnD({
onDrop: function (table, row) {
$.ajax ({url: "%(url)s",
async: true,
type: "POST",
dataType: "text",
data: $.tableDnD.serialize_plain(),
success: function (data_raw) {
var data = eval('(' + data_raw + ')');
if (data['ret'] == 'ok') {
/* Modified: Save button */
var modified = data['modified'];
var not_modified = data['not-modified'];
if (modified != undefined) {
$(modified).show();
$(modified).removeClass('saved');
} else if (not_modified) {
$(not_modified).addClass('saved');
}
}
/* Signal */
$("#%(id)s").trigger ('reordered');
}
});
},
dragHandle: "dragHandle",
containerDiv: $("#%(container)s")
});
"""
JS_INIT_FUNC = """
jQuery.tableDnD.serialize_plain = function() {
var result = "";
var table = jQuery.tableDnD.currentTable;
/* Serialize */
for (var i=0; i<table.rows.length; i++) {
if (result.length > 0) {
result += ",";
}
result += table.rows[i].id;
}
return table.id + "_order=" + result;
};
"""
def changed_handler_func (callback, key_id, **kwargs):
return callback (key_id, **kwargs)
class SortableList (Table):
def __init__ (self, callback, container, *args, **kwargs):
Table.__init__ (self, *args, **kwargs)
self.id = "sortablelist_%d" %(self.uniq_id)
self.url = "/sortablelist_%d"%(self.uniq_id)
self.container = container
# Secure submit
srv = get_server()
if srv.use_sec_submit:
self.url += '?key=%s' %(srv.sec_submit)
# Register the public URL
publish (r"^/sortablelist_%d"%(self.uniq_id), changed_handler_func,
method='POST', callback=callback, key_id='%s_order'%(self.id), **kwargs)
def Render (self):
render = Table.Render (self)
props = {'id': self.id, 'url': self.url, 'container': self.container}
render.js += JS_INIT %(props) + Uniq_Block (JS_INIT_FUNC %(props))
render.headers += HEADER
return render
def set_header (self, row_num):
# Set the row properties
self[row_num].props['class'] = "nodrag nodrop"
# Let Table do the rest
Table.set_header (self, num=row_num)
def SortableList__reorder_generic (post_arg_name, pre, step=10):
# Process new list
order = post.pop (post_arg_name)
tmp = order.split(',')
# Build and alternative tree
num = step
for v in tmp:
cfg.clone ('%s!%s'%(pre, v), 'tmp!reorder!%s!%d'%(pre, num))
num += step
# Set the new list in place
del (cfg[pre])
cfg.rename ('tmp!reorder!%s'%(pre), pre)
return cfg_reply_ajax_ok()
| bsd-3-clause |
IanCodyBurnet/lpthw | ex2.py | 311 | # A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print "I could have code like this." # and the comment after is ignored
# You can also use the comment to "disable" or comment out a piece of code:
# print "This won't run."
print "This will run."
| bsd-3-clause |
smilusingjavascript/blink | Source/core/frame/csp/ContentSecurityPolicy.cpp | 38756 | /*
* Copyright (C) 2011 Google, Inc. All rights reserved.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "core/frame/csp/ContentSecurityPolicy.h"
#include "bindings/core/v8/ScriptCallStackFactory.h"
#include "bindings/core/v8/ScriptController.h"
#include "core/dom/DOMStringList.h"
#include "core/dom/Document.h"
#include "core/events/SecurityPolicyViolationEvent.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/UseCounter.h"
#include "core/frame/csp/CSPDirectiveList.h"
#include "core/frame/csp/CSPSource.h"
#include "core/frame/csp/CSPSourceList.h"
#include "core/frame/csp/MediaListDirective.h"
#include "core/frame/csp/SourceListDirective.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/loader/DocumentLoader.h"
#include "core/loader/PingLoader.h"
#include "platform/Crypto.h"
#include "platform/JSONValues.h"
#include "platform/ParsingUtilities.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/network/ContentSecurityPolicyParsers.h"
#include "platform/network/ContentSecurityPolicyResponseHeaders.h"
#include "platform/network/FormData.h"
#include "platform/network/ResourceResponse.h"
#include "platform/weborigin/KURL.h"
#include "platform/weborigin/KnownPorts.h"
#include "platform/weborigin/SchemeRegistry.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "public/platform/Platform.h"
#include "public/platform/WebArrayBuffer.h"
#include "public/platform/WebCrypto.h"
#include "public/platform/WebCryptoAlgorithm.h"
#include "wtf/StringHasher.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/StringUTF8Adaptor.h"
namespace blink {
// CSP 1.0 Directives
const char ContentSecurityPolicy::ConnectSrc[] = "connect-src";
const char ContentSecurityPolicy::DefaultSrc[] = "default-src";
const char ContentSecurityPolicy::FontSrc[] = "font-src";
const char ContentSecurityPolicy::FrameSrc[] = "frame-src";
const char ContentSecurityPolicy::ImgSrc[] = "img-src";
const char ContentSecurityPolicy::MediaSrc[] = "media-src";
const char ContentSecurityPolicy::ObjectSrc[] = "object-src";
const char ContentSecurityPolicy::ReportURI[] = "report-uri";
const char ContentSecurityPolicy::Sandbox[] = "sandbox";
const char ContentSecurityPolicy::ScriptSrc[] = "script-src";
const char ContentSecurityPolicy::StyleSrc[] = "style-src";
// CSP 1.1 Directives
const char ContentSecurityPolicy::BaseURI[] = "base-uri";
const char ContentSecurityPolicy::ChildSrc[] = "child-src";
const char ContentSecurityPolicy::FormAction[] = "form-action";
const char ContentSecurityPolicy::FrameAncestors[] = "frame-ancestors";
const char ContentSecurityPolicy::PluginTypes[] = "plugin-types";
const char ContentSecurityPolicy::ReflectedXSS[] = "reflected-xss";
const char ContentSecurityPolicy::Referrer[] = "referrer";
// Manifest Directives
// https://w3c.github.io/manifest/#content-security-policy
const char ContentSecurityPolicy::ManifestSrc[] = "manifest-src";
bool ContentSecurityPolicy::isDirectiveName(const String& name)
{
return (equalIgnoringCase(name, ConnectSrc)
|| equalIgnoringCase(name, DefaultSrc)
|| equalIgnoringCase(name, FontSrc)
|| equalIgnoringCase(name, FrameSrc)
|| equalIgnoringCase(name, ImgSrc)
|| equalIgnoringCase(name, MediaSrc)
|| equalIgnoringCase(name, ObjectSrc)
|| equalIgnoringCase(name, ReportURI)
|| equalIgnoringCase(name, Sandbox)
|| equalIgnoringCase(name, ScriptSrc)
|| equalIgnoringCase(name, StyleSrc)
|| equalIgnoringCase(name, BaseURI)
|| equalIgnoringCase(name, ChildSrc)
|| equalIgnoringCase(name, FormAction)
|| equalIgnoringCase(name, FrameAncestors)
|| equalIgnoringCase(name, PluginTypes)
|| equalIgnoringCase(name, ReflectedXSS)
|| equalIgnoringCase(name, Referrer)
|| equalIgnoringCase(name, ManifestSrc)
);
}
static UseCounter::Feature getUseCounterType(ContentSecurityPolicyHeaderType type)
{
switch (type) {
case ContentSecurityPolicyHeaderTypeEnforce:
return UseCounter::ContentSecurityPolicy;
case ContentSecurityPolicyHeaderTypeReport:
return UseCounter::ContentSecurityPolicyReportOnly;
}
ASSERT_NOT_REACHED();
return UseCounter::NumberOfFeatures;
}
static ReferrerPolicy mergeReferrerPolicies(ReferrerPolicy a, ReferrerPolicy b)
{
if (a != b)
return ReferrerPolicyNever;
return a;
}
ContentSecurityPolicy::ContentSecurityPolicy()
: m_executionContext(nullptr)
, m_overrideInlineStyleAllowed(false)
, m_scriptHashAlgorithmsUsed(ContentSecurityPolicyHashAlgorithmNone)
, m_styleHashAlgorithmsUsed(ContentSecurityPolicyHashAlgorithmNone)
, m_sandboxMask(0)
, m_referrerPolicy(ReferrerPolicyDefault)
{
}
void ContentSecurityPolicy::bindToExecutionContext(ExecutionContext* executionContext)
{
m_executionContext = executionContext;
applyPolicySideEffectsToExecutionContext();
}
void ContentSecurityPolicy::applyPolicySideEffectsToExecutionContext()
{
ASSERT(m_executionContext);
// Ensure that 'self' processes correctly.
m_selfProtocol = securityOrigin()->protocol();
m_selfSource = adoptPtr(new CSPSource(this, m_selfProtocol, securityOrigin()->host(), securityOrigin()->port(), String(), CSPSource::NoWildcard, CSPSource::NoWildcard));
// If we're in a Document, set the referrer policy and sandbox flags, then dump all the
// parsing error messages, then poke at histograms.
if (Document* document = this->document()) {
document->enforceSandboxFlags(m_sandboxMask);
if (didSetReferrerPolicy())
document->setReferrerPolicy(m_referrerPolicy);
for (const auto& consoleMessage : m_consoleMessages)
m_executionContext->addConsoleMessage(consoleMessage);
m_consoleMessages.clear();
for (const auto& policy : m_policies)
UseCounter::count(*document, getUseCounterType(policy->headerType()));
}
// We disable 'eval()' even in the case of report-only policies, and rely on the check in the
// V8Initializer::codeGenerationCheckCallbackInMainThread callback to determine whether the
// call should execute or not.
if (!m_disableEvalErrorMessage.isNull())
m_executionContext->disableEval(m_disableEvalErrorMessage);
}
ContentSecurityPolicy::~ContentSecurityPolicy()
{
}
Document* ContentSecurityPolicy::document() const
{
return m_executionContext->isDocument() ? toDocument(m_executionContext) : nullptr;
}
void ContentSecurityPolicy::copyStateFrom(const ContentSecurityPolicy* other)
{
ASSERT(m_policies.isEmpty());
for (const auto& policy : other->m_policies)
addPolicyFromHeaderValue(policy->header(), policy->headerType(), policy->headerSource());
}
void ContentSecurityPolicy::didReceiveHeaders(const ContentSecurityPolicyResponseHeaders& headers)
{
if (!headers.contentSecurityPolicy().isEmpty())
addPolicyFromHeaderValue(headers.contentSecurityPolicy(), ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceHTTP);
if (!headers.contentSecurityPolicyReportOnly().isEmpty())
addPolicyFromHeaderValue(headers.contentSecurityPolicyReportOnly(), ContentSecurityPolicyHeaderTypeReport, ContentSecurityPolicyHeaderSourceHTTP);
}
void ContentSecurityPolicy::didReceiveHeader(const String& header, ContentSecurityPolicyHeaderType type, ContentSecurityPolicyHeaderSource source)
{
addPolicyFromHeaderValue(header, type, source);
// This might be called after we've been bound to an execution context. For example, a <meta>
// element might be injected after page load.
if (m_executionContext)
applyPolicySideEffectsToExecutionContext();
}
void ContentSecurityPolicy::addPolicyFromHeaderValue(const String& header, ContentSecurityPolicyHeaderType type, ContentSecurityPolicyHeaderSource source)
{
// If this is a report-only header inside a <meta> element, bail out.
if (source == ContentSecurityPolicyHeaderSourceMeta && type == ContentSecurityPolicyHeaderTypeReport && experimentalFeaturesEnabled()) {
reportReportOnlyInMeta(header);
return;
}
Vector<UChar> characters;
header.appendTo(characters);
const UChar* begin = characters.data();
const UChar* end = begin + characters.size();
// RFC2616, section 4.2 specifies that headers appearing multiple times can
// be combined with a comma. Walk the header string, and parse each comma
// separated chunk as a separate header.
const UChar* position = begin;
while (position < end) {
skipUntil<UChar>(position, end, ',');
// header1,header2 OR header1
// ^ ^
OwnPtr<CSPDirectiveList> policy = CSPDirectiveList::create(this, begin, position, type, source);
if (type != ContentSecurityPolicyHeaderTypeReport && policy->didSetReferrerPolicy()) {
// FIXME: We need a 'ReferrerPolicyUnset' enum to avoid confusing code like this.
m_referrerPolicy = didSetReferrerPolicy() ? mergeReferrerPolicies(m_referrerPolicy, policy->referrerPolicy()) : policy->referrerPolicy();
}
if (!policy->allowEval(0, SuppressReport) && m_disableEvalErrorMessage.isNull())
m_disableEvalErrorMessage = policy->evalDisabledErrorMessage();
m_policies.append(policy.release());
// Skip the comma, and begin the next header from the current position.
ASSERT(position == end || *position == ',');
skipExactly<UChar>(position, end, ',');
begin = position;
}
}
void ContentSecurityPolicy::setOverrideAllowInlineStyle(bool value)
{
m_overrideInlineStyleAllowed = value;
}
void ContentSecurityPolicy::setOverrideURLForSelf(const KURL& url)
{
// Create a temporary CSPSource so that 'self' expressions can be resolved before we bind to
// an execution context (for 'frame-ancestor' resolution, for example). This CSPSource will
// be overwritten when we bind this object to an execution context.
RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
m_selfProtocol = origin->protocol();
m_selfSource = adoptPtr(new CSPSource(this, m_selfProtocol, origin->host(), origin->port(), String(), CSPSource::NoWildcard, CSPSource::NoWildcard));
}
const String& ContentSecurityPolicy::deprecatedHeader() const
{
return m_policies.isEmpty() ? emptyString() : m_policies[0]->header();
}
ContentSecurityPolicyHeaderType ContentSecurityPolicy::deprecatedHeaderType() const
{
return m_policies.isEmpty() ? ContentSecurityPolicyHeaderTypeEnforce : m_policies[0]->headerType();
}
template<bool (CSPDirectiveList::*allowed)(ContentSecurityPolicy::ReportingStatus) const>
bool isAllowedByAll(const CSPDirectiveListVector& policies, ContentSecurityPolicy::ReportingStatus reportingStatus)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(reportingStatus))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(ScriptState* scriptState, ContentSecurityPolicy::ReportingStatus) const>
bool isAllowedByAllWithState(const CSPDirectiveListVector& policies, ScriptState* scriptState, ContentSecurityPolicy::ReportingStatus reportingStatus)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(scriptState, reportingStatus))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(const String&, const WTF::OrdinalNumber&, ContentSecurityPolicy::ReportingStatus) const>
bool isAllowedByAllWithContext(const CSPDirectiveListVector& policies, const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(contextURL, contextLine, reportingStatus))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(const String&) const>
bool isAllowedByAllWithNonce(const CSPDirectiveListVector& policies, const String& nonce)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(nonce))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(const CSPHashValue&) const>
bool isAllowedByAllWithHash(const CSPDirectiveListVector& policies, const CSPHashValue& hashValue)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(hashValue))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowFromURL)(const KURL&, ContentSecurityPolicy::ReportingStatus) const>
bool isAllowedByAllWithURL(const CSPDirectiveListVector& policies, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus)
{
if (SchemeRegistry::schemeShouldBypassContentSecurityPolicy(url.protocol()))
return true;
for (const auto& policy : policies) {
if (!(policy.get()->*allowFromURL)(url, reportingStatus))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(LocalFrame*, const KURL&, ContentSecurityPolicy::ReportingStatus) const>
bool isAllowedByAllWithFrame(const CSPDirectiveListVector& policies, LocalFrame* frame, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(frame, url, reportingStatus))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(const CSPHashValue&) const>
bool checkDigest(const String& source, uint8_t hashAlgorithmsUsed, const CSPDirectiveListVector& policies)
{
// Any additions or subtractions from this struct should also modify the
// respective entries in the kSupportedPrefixes array in
// CSPSourceList::parseHash().
static const struct {
ContentSecurityPolicyHashAlgorithm cspHashAlgorithm;
HashAlgorithm algorithm;
} kAlgorithmMap[] = {
{ ContentSecurityPolicyHashAlgorithmSha1, HashAlgorithmSha1 },
{ ContentSecurityPolicyHashAlgorithmSha256, HashAlgorithmSha256 },
{ ContentSecurityPolicyHashAlgorithmSha384, HashAlgorithmSha384 },
{ ContentSecurityPolicyHashAlgorithmSha512, HashAlgorithmSha512 }
};
// Only bother normalizing the source/computing digests if there are any checks to be done.
if (hashAlgorithmsUsed == ContentSecurityPolicyHashAlgorithmNone)
return false;
StringUTF8Adaptor normalizedSource(source, StringUTF8Adaptor::Normalize, WTF::EntitiesForUnencodables);
// See comment in CSPSourceList::parseHash about why we are using this sizeof
// calculation instead of WTF_ARRAY_LENGTH.
for (size_t i = 0; i < (sizeof(kAlgorithmMap) / sizeof(kAlgorithmMap[0])); i++) {
DigestValue digest;
if (kAlgorithmMap[i].cspHashAlgorithm & hashAlgorithmsUsed) {
bool digestSuccess = computeDigest(kAlgorithmMap[i].algorithm, normalizedSource.data(), normalizedSource.length(), digest);
if (digestSuccess && isAllowedByAllWithHash<allowed>(policies, CSPHashValue(kAlgorithmMap[i].cspHashAlgorithm, digest)))
return true;
}
}
return false;
}
bool ContentSecurityPolicy::allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithContext<&CSPDirectiveList::allowJavaScriptURLs>(m_policies, contextURL, contextLine, reportingStatus);
}
bool ContentSecurityPolicy::allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithContext<&CSPDirectiveList::allowInlineEventHandlers>(m_policies, contextURL, contextLine, reportingStatus);
}
bool ContentSecurityPolicy::allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithContext<&CSPDirectiveList::allowInlineScript>(m_policies, contextURL, contextLine, reportingStatus);
}
bool ContentSecurityPolicy::allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
if (m_overrideInlineStyleAllowed)
return true;
return isAllowedByAllWithContext<&CSPDirectiveList::allowInlineStyle>(m_policies, contextURL, contextLine, reportingStatus);
}
bool ContentSecurityPolicy::allowEval(ScriptState* scriptState, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithState<&CSPDirectiveList::allowEval>(m_policies, scriptState, reportingStatus);
}
String ContentSecurityPolicy::evalDisabledErrorMessage() const
{
for (const auto& policy : m_policies) {
if (!policy->allowEval(0, SuppressReport))
return policy->evalDisabledErrorMessage();
}
return String();
}
bool ContentSecurityPolicy::allowPluginType(const String& type, const String& typeAttribute, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
for (const auto& policy : m_policies) {
if (!policy->allowPluginType(type, typeAttribute, url, reportingStatus))
return false;
}
return true;
}
bool ContentSecurityPolicy::allowScriptFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowScriptFromSource>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowScriptWithNonce(const String& nonce) const
{
return isAllowedByAllWithNonce<&CSPDirectiveList::allowScriptNonce>(m_policies, nonce);
}
bool ContentSecurityPolicy::allowStyleWithNonce(const String& nonce) const
{
return isAllowedByAllWithNonce<&CSPDirectiveList::allowStyleNonce>(m_policies, nonce);
}
bool ContentSecurityPolicy::allowScriptWithHash(const String& source) const
{
return checkDigest<&CSPDirectiveList::allowScriptHash>(source, m_scriptHashAlgorithmsUsed, m_policies);
}
bool ContentSecurityPolicy::allowStyleWithHash(const String& source) const
{
return checkDigest<&CSPDirectiveList::allowStyleHash>(source, m_styleHashAlgorithmsUsed, m_policies);
}
void ContentSecurityPolicy::usesScriptHashAlgorithms(uint8_t algorithms)
{
m_scriptHashAlgorithmsUsed |= algorithms;
}
void ContentSecurityPolicy::usesStyleHashAlgorithms(uint8_t algorithms)
{
m_styleHashAlgorithmsUsed |= algorithms;
}
bool ContentSecurityPolicy::allowObjectFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowObjectFromSource>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowChildFrameFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowChildFrameFromSource>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowImageFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowImageFromSource>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowStyleFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowStyleFromSource>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowFontFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowFontFromSource>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowMediaFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowMediaFromSource>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowConnectToSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowConnectToSource>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowFormAction(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowFormAction>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowBaseURI(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowBaseURI>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowAncestors(LocalFrame* frame, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithFrame<&CSPDirectiveList::allowAncestors>(m_policies, frame, url, reportingStatus);
}
bool ContentSecurityPolicy::allowChildContextFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowChildContextFromSource>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowWorkerContextFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
// CSP 1.1 moves workers from 'script-src' to the new 'child-src'. Measure the impact of this backwards-incompatible change.
if (Document* document = this->document()) {
UseCounter::count(*document, UseCounter::WorkerSubjectToCSP);
if (isAllowedByAllWithURL<&CSPDirectiveList::allowChildContextFromSource>(m_policies, url, SuppressReport) && !isAllowedByAllWithURL<&CSPDirectiveList::allowScriptFromSource>(m_policies, url, SuppressReport))
UseCounter::count(*document, UseCounter::WorkerAllowedByChildBlockedByScript);
}
return isAllowedByAllWithURL<&CSPDirectiveList::allowChildContextFromSource>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::allowManifestFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
{
return isAllowedByAllWithURL<&CSPDirectiveList::allowManifestFromSource>(m_policies, url, reportingStatus);
}
bool ContentSecurityPolicy::isActive() const
{
return !m_policies.isEmpty();
}
ReflectedXSSDisposition ContentSecurityPolicy::reflectedXSSDisposition() const
{
ReflectedXSSDisposition disposition = ReflectedXSSUnset;
for (const auto& policy : m_policies) {
if (policy->reflectedXSSDisposition() > disposition)
disposition = std::max(disposition, policy->reflectedXSSDisposition());
}
return disposition;
}
ReferrerPolicy ContentSecurityPolicy::referrerPolicy() const
{
ReferrerPolicy referrerPolicy = ReferrerPolicyDefault;
bool first = true;
for (const auto& policy : m_policies) {
if (policy->didSetReferrerPolicy()) {
if (first)
referrerPolicy = policy->referrerPolicy();
else
referrerPolicy = mergeReferrerPolicies(referrerPolicy, policy->referrerPolicy());
}
}
return referrerPolicy;
}
bool ContentSecurityPolicy::didSetReferrerPolicy() const
{
for (const auto& policy : m_policies) {
if (policy->didSetReferrerPolicy())
return true;
}
return false;
}
SecurityOrigin* ContentSecurityPolicy::securityOrigin() const
{
return m_executionContext->securityContext().securityOrigin();
}
const KURL ContentSecurityPolicy::url() const
{
return m_executionContext->contextURL();
}
KURL ContentSecurityPolicy::completeURL(const String& url) const
{
return m_executionContext->contextCompleteURL(url);
}
void ContentSecurityPolicy::enforceSandboxFlags(SandboxFlags mask)
{
m_sandboxMask |= mask;
}
static String stripURLForUseInReport(Document* document, const KURL& url)
{
if (!url.isValid())
return String();
if (!url.isHierarchical() || url.protocolIs("file"))
return url.protocol();
return document->securityOrigin()->canRequest(url) ? url.strippedForUseAsReferrer() : SecurityOrigin::create(url)->toString();
}
static void gatherSecurityPolicyViolationEventData(SecurityPolicyViolationEventInit& init, Document* document, const String& directiveText, const String& effectiveDirective, const KURL& blockedURL, const String& header)
{
if (equalIgnoringCase(effectiveDirective, ContentSecurityPolicy::FrameAncestors)) {
// If this load was blocked via 'frame-ancestors', then the URL of |document| has not yet
// been initialized. In this case, we'll set both 'documentURI' and 'blockedURI' to the
// blocked document's URL.
init.documentURI = blockedURL.string();
init.blockedURI = blockedURL.string();
} else {
init.documentURI = document->url().string();
init.blockedURI = stripURLForUseInReport(document, blockedURL);
}
init.referrer = document->referrer();
init.violatedDirective = directiveText;
init.effectiveDirective = effectiveDirective;
init.originalPolicy = header;
init.sourceFile = String();
init.lineNumber = 0;
init.columnNumber = 0;
init.statusCode = 0;
if (!SecurityOrigin::isSecure(document->url()) && document->loader())
init.statusCode = document->loader()->response().httpStatusCode();
RefPtrWillBeRawPtr<ScriptCallStack> stack = createScriptCallStack(1, false);
if (!stack)
return;
const ScriptCallFrame& callFrame = stack->at(0);
if (callFrame.lineNumber()) {
KURL source = KURL(ParsedURLString, callFrame.sourceURL());
init.sourceFile = stripURLForUseInReport(document, source);
init.lineNumber = callFrame.lineNumber();
init.columnNumber = callFrame.columnNumber();
}
}
void ContentSecurityPolicy::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<String>& reportEndpoints, const String& header, LocalFrame* contextFrame)
{
ASSERT((m_executionContext && !contextFrame) || (equalIgnoringCase(effectiveDirective, ContentSecurityPolicy::FrameAncestors) && contextFrame));
// FIXME: Support sending reports from worker.
Document* document = contextFrame ? contextFrame->document() : this->document();
if (!document)
return;
LocalFrame* frame = document->frame();
if (!frame)
return;
SecurityPolicyViolationEventInit violationData;
gatherSecurityPolicyViolationEventData(violationData, document, directiveText, effectiveDirective, blockedURL, header);
frame->domWindow()->enqueueDocumentEvent(SecurityPolicyViolationEvent::create(EventTypeNames::securitypolicyviolation, violationData));
if (reportEndpoints.isEmpty())
return;
// We need to be careful here when deciding what information to send to the
// report-uri. Currently, we send only the current document's URL and the
// directive that was violated. The document's URL is safe to send because
// it's the document itself that's requesting that it be sent. You could
// make an argument that we shouldn't send HTTPS document URLs to HTTP
// report-uris (for the same reasons that we supress the Referer in that
// case), but the Referer is sent implicitly whereas this request is only
// sent explicitly. As for which directive was violated, that's pretty
// harmless information.
RefPtr<JSONObject> cspReport = JSONObject::create();
cspReport->setString("document-uri", violationData.documentURI);
cspReport->setString("referrer", violationData.referrer);
cspReport->setString("violated-directive", violationData.violatedDirective);
cspReport->setString("effective-directive", violationData.effectiveDirective);
cspReport->setString("original-policy", violationData.originalPolicy);
cspReport->setString("blocked-uri", violationData.blockedURI);
if (!violationData.sourceFile.isEmpty() && violationData.lineNumber) {
cspReport->setString("source-file", violationData.sourceFile);
cspReport->setNumber("line-number", violationData.lineNumber);
cspReport->setNumber("column-number", violationData.columnNumber);
}
cspReport->setNumber("status-code", violationData.statusCode);
RefPtr<JSONObject> reportObject = JSONObject::create();
reportObject->setObject("csp-report", cspReport.release());
String stringifiedReport = reportObject->toJSONString();
if (!shouldSendViolationReport(stringifiedReport))
return;
RefPtr<FormData> report = FormData::create(stringifiedReport.utf8());
for (const String& endpoint : reportEndpoints) {
// If we have a context frame we're dealing with 'frame-ancestors' and we don't have our
// own execution context. Use the frame's document to complete the endpoint URL, overriding
// its URL with the blocked document's URL.
ASSERT(!contextFrame || !m_executionContext);
ASSERT(!contextFrame || equalIgnoringCase(effectiveDirective, FrameAncestors));
KURL url = contextFrame ? frame->document()->completeURLWithOverride(endpoint, blockedURL) : completeURL(endpoint);
PingLoader::sendViolationReport(frame, url, report, PingLoader::ContentSecurityPolicyViolationReport);
}
didSendViolationReport(stringifiedReport);
}
void ContentSecurityPolicy::reportInvalidReferrer(const String& invalidValue)
{
logToConsole("The 'referrer' Content Security Policy directive has the invalid value \"" + invalidValue + "\". Valid values are \"no-referrer\", \"no-referrer-when-downgrade\", \"origin\", and \"unsafe-url\". Note that \"origin-when-cross-origin\" is not yet supported.");
}
void ContentSecurityPolicy::reportReportOnlyInMeta(const String& header)
{
logToConsole("The report-only Content Security Policy '" + header + "' was delivered via a <meta> element, which is disallowed. The policy has been ignored.");
}
void ContentSecurityPolicy::reportMetaOutsideHead(const String& header)
{
logToConsole("The Content Security Policy '" + header + "' was delivered via a <meta> element outside the document's <head>, which is disallowed. The policy has been ignored.");
}
void ContentSecurityPolicy::reportInvalidInReportOnly(const String& name)
{
logToConsole("The Content Security Policy directive '" + name + "' is ignored when delivered in a report-only policy.");
}
void ContentSecurityPolicy::reportUnsupportedDirective(const String& name)
{
DEFINE_STATIC_LOCAL(String, allow, ("allow"));
DEFINE_STATIC_LOCAL(String, options, ("options"));
DEFINE_STATIC_LOCAL(String, policyURI, ("policy-uri"));
DEFINE_STATIC_LOCAL(String, allowMessage, ("The 'allow' directive has been replaced with 'default-src'. Please use that directive instead, as 'allow' has no effect."));
DEFINE_STATIC_LOCAL(String, optionsMessage, ("The 'options' directive has been replaced with 'unsafe-inline' and 'unsafe-eval' source expressions for the 'script-src' and 'style-src' directives. Please use those directives instead, as 'options' has no effect."));
DEFINE_STATIC_LOCAL(String, policyURIMessage, ("The 'policy-uri' directive has been removed from the specification. Please specify a complete policy via the Content-Security-Policy header."));
String message = "Unrecognized Content-Security-Policy directive '" + name + "'.\n";
MessageLevel level = ErrorMessageLevel;
if (equalIgnoringCase(name, allow)) {
message = allowMessage;
} else if (equalIgnoringCase(name, options)) {
message = optionsMessage;
} else if (equalIgnoringCase(name, policyURI)) {
message = policyURIMessage;
} else if (isDirectiveName(name)) {
message = "The Content-Security-Policy directive '" + name + "' is implemented behind a flag which is currently disabled.\n";
level = InfoMessageLevel;
}
logToConsole(message, level);
}
void ContentSecurityPolicy::reportDirectiveAsSourceExpression(const String& directiveName, const String& sourceExpression)
{
String message = "The Content Security Policy directive '" + directiveName + "' contains '" + sourceExpression + "' as a source expression. Did you mean '" + directiveName + " ...; " + sourceExpression + "...' (note the semicolon)?";
logToConsole(message);
}
void ContentSecurityPolicy::reportDuplicateDirective(const String& name)
{
String message = "Ignoring duplicate Content-Security-Policy directive '" + name + "'.\n";
logToConsole(message);
}
void ContentSecurityPolicy::reportInvalidPluginTypes(const String& pluginType)
{
String message;
if (pluginType.isNull())
message = "'plugin-types' Content Security Policy directive is empty; all plugins will be blocked.\n";
else
message = "Invalid plugin type in 'plugin-types' Content Security Policy directive: '" + pluginType + "'.\n";
logToConsole(message);
}
void ContentSecurityPolicy::reportInvalidSandboxFlags(const String& invalidFlags)
{
logToConsole("Error while parsing the 'sandbox' Content Security Policy directive: " + invalidFlags);
}
void ContentSecurityPolicy::reportInvalidReflectedXSS(const String& invalidValue)
{
logToConsole("The 'reflected-xss' Content Security Policy directive has the invalid value \"" + invalidValue + "\". Valid values are \"allow\", \"filter\", and \"block\".");
}
void ContentSecurityPolicy::reportInvalidDirectiveValueCharacter(const String& directiveName, const String& value)
{
String message = "The value for Content Security Policy directive '" + directiveName + "' contains an invalid character: '" + value + "'. Non-whitespace characters outside ASCII 0x21-0x7E must be percent-encoded, as described in RFC 3986, section 2.1: http://tools.ietf.org/html/rfc3986#section-2.1.";
logToConsole(message);
}
void ContentSecurityPolicy::reportInvalidPathCharacter(const String& directiveName, const String& value, const char invalidChar)
{
ASSERT(invalidChar == '#' || invalidChar == '?');
String ignoring = "The fragment identifier, including the '#', will be ignored.";
if (invalidChar == '?')
ignoring = "The query component, including the '?', will be ignored.";
String message = "The source list for Content Security Policy directive '" + directiveName + "' contains a source with an invalid path: '" + value + "'. " + ignoring;
logToConsole(message);
}
void ContentSecurityPolicy::reportInvalidSourceExpression(const String& directiveName, const String& source)
{
String message = "The source list for Content Security Policy directive '" + directiveName + "' contains an invalid source: '" + source + "'. It will be ignored.";
if (equalIgnoringCase(source, "'none'"))
message = message + " Note that 'none' has no effect unless it is the only expression in the source list.";
logToConsole(message);
}
void ContentSecurityPolicy::reportMissingReportURI(const String& policy)
{
logToConsole("The Content Security Policy '" + policy + "' was delivered in report-only mode, but does not specify a 'report-uri'; the policy will have no effect. Please either add a 'report-uri' directive, or deliver the policy via the 'Content-Security-Policy' header.");
}
void ContentSecurityPolicy::logToConsole(const String& message, MessageLevel level)
{
logToConsole(ConsoleMessage::create(SecurityMessageSource, level, message));
}
void ContentSecurityPolicy::logToConsole(PassRefPtrWillBeRawPtr<ConsoleMessage> consoleMessage, LocalFrame* frame)
{
if (frame)
frame->document()->addConsoleMessage(consoleMessage);
else if (m_executionContext)
m_executionContext->addConsoleMessage(consoleMessage);
else
m_consoleMessages.append(consoleMessage);
}
void ContentSecurityPolicy::reportBlockedScriptExecutionToInspector(const String& directiveText) const
{
m_executionContext->reportBlockedScriptExecutionToInspector(directiveText);
}
bool ContentSecurityPolicy::experimentalFeaturesEnabled() const
{
return RuntimeEnabledFeatures::experimentalContentSecurityPolicyFeaturesEnabled();
}
bool ContentSecurityPolicy::urlMatchesSelf(const KURL& url) const
{
return m_selfSource->matches(url);
}
bool ContentSecurityPolicy::protocolMatchesSelf(const KURL& url) const
{
if (equalIgnoringCase("http", m_selfProtocol))
return url.protocolIsInHTTPFamily();
return equalIgnoringCase(url.protocol(), m_selfProtocol);
}
bool ContentSecurityPolicy::shouldBypassMainWorld(ExecutionContext* context)
{
if (context && context->isDocument()) {
Document* document = toDocument(context);
if (document->frame())
return document->frame()->script().shouldBypassMainWorldCSP();
}
return false;
}
bool ContentSecurityPolicy::shouldSendViolationReport(const String& report) const
{
// Collisions have no security impact, so we can save space by storing only the string's hash rather than the whole report.
return !m_violationReportsSent.contains(report.impl()->hash());
}
void ContentSecurityPolicy::didSendViolationReport(const String& report)
{
m_violationReportsSent.add(report.impl()->hash());
}
} // namespace blink
| bsd-3-clause |
frewsxcv/WeasyPrint | weasyprint/css/computed_values.py | 17020 | # coding: utf8
"""
weasyprint.css.computed_values
------------------------------
Convert *specified* property values (the result of the cascade and
inhertance) into *computed* values (that are inherited).
:copyright: Copyright 2011-2014 Simon Sapin and contributors, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import division, unicode_literals
from .properties import INITIAL_VALUES, Dimension
from ..urls import get_link_attribute
from .. import text
ZERO_PIXELS = Dimension(0, 'px')
# How many CSS pixels is one <unit>?
# http://www.w3.org/TR/CSS21/syndata.html#length-units
LENGTHS_TO_PIXELS = {
'px': 1,
'pt': 1. / 0.75,
'pc': 16., # LENGTHS_TO_PIXELS['pt'] * 12
'in': 96., # LENGTHS_TO_PIXELS['pt'] * 72
'cm': 96. / 2.54, # LENGTHS_TO_PIXELS['in'] / 2.54
'mm': 96. / 25.4, # LENGTHS_TO_PIXELS['in'] / 25.4
}
# Value in pixels of font-size for <absolute-size> keywords: 12pt (16px) for
# medium, and scaling factors given in CSS3 for others:
# http://www.w3.org/TR/css3-fonts/#font-size-prop
# TODO: this will need to be ordered to implement 'smaller' and 'larger'
FONT_SIZE_KEYWORDS = dict(
# medium is 16px, others are a ratio of medium
(name, INITIAL_VALUES['font_size'] * a / b)
for name, a, b in [
('xx-small', 3, 5),
('x-small', 3, 4),
('small', 8, 9),
('medium', 1, 1),
('large', 6, 5),
('x-large', 3, 2),
('xx-large', 2, 1),
]
)
# These are unspecified, other than 'thin' <='medium' <= 'thick'.
# Values are in pixels.
BORDER_WIDTH_KEYWORDS = {
'thin': 1,
'medium': 3,
'thick': 5,
}
assert INITIAL_VALUES['border_top_width'] == BORDER_WIDTH_KEYWORDS['medium']
# http://www.w3.org/TR/CSS21/fonts.html#propdef-font-weight
FONT_WEIGHT_RELATIVE = dict(
bolder={
100: 400,
200: 400,
300: 400,
400: 700,
500: 700,
600: 900,
700: 900,
800: 900,
900: 900,
},
lighter={
100: 100,
200: 100,
300: 100,
400: 100,
500: 100,
600: 400,
700: 400,
800: 700,
900: 700,
},
)
# http://www.w3.org/TR/css3-page/#size
# name=(width in pixels, height in pixels)
PAGE_SIZES = dict(
a5=(
Dimension(148, 'mm'),
Dimension(210, 'mm'),
),
a4=(
Dimension(210, 'mm'),
Dimension(297, 'mm'),
),
a3=(
Dimension(297, 'mm'),
Dimension(420, 'mm'),
),
b5=(
Dimension(176, 'mm'),
Dimension(250, 'mm'),
),
b4=(
Dimension(250, 'mm'),
Dimension(353, 'mm'),
),
letter=(
Dimension(8.5, 'in'),
Dimension(11, 'in'),
),
legal=(
Dimension(8.5, 'in'),
Dimension(14, 'in'),
),
ledger=(
Dimension(11, 'in'),
Dimension(17, 'in'),
),
)
# In "portrait" orientation.
for w, h in PAGE_SIZES.values():
assert w.value < h.value
INITIAL_PAGE_SIZE = PAGE_SIZES['a4']
INITIAL_VALUES['size'] = tuple(
d.value * LENGTHS_TO_PIXELS[d.unit] for d in INITIAL_PAGE_SIZE)
def _computing_order():
"""Some computed values are required by others, so order matters."""
first = [
'font_stretch', 'font_weight', 'font_family', 'font_variant',
'font_style', 'font_size', 'line_height']
order = sorted(INITIAL_VALUES)
for name in first:
order.remove(name)
return tuple(first + order)
COMPUTING_ORDER = _computing_order()
# Maps property names to functions returning the computed values
COMPUTER_FUNCTIONS = {}
def register_computer(name):
"""Decorator registering a property ``name`` for a function."""
name = name.replace('-', '_')
def decorator(function):
"""Register the property ``name`` for ``function``."""
COMPUTER_FUNCTIONS[name] = function
return function
return decorator
def compute(element, pseudo_type, specified, computed, parent_style):
"""
Return a StyleDict of computed values.
:param element: The HTML element these style apply to
:param pseudo_type: The type of pseudo-element, eg 'before', None
:param specified: a :class:`StyleDict` of specified values. Should contain
values for all properties.
:param computed: a :class:`StyleDict` of already known computed values.
Only contains some properties (or none).
:param parent_values: a :class:`StyleDict` of computed values of the parent
element (should contain values for all properties),
or ``None`` if ``element`` is the root element.
"""
if parent_style is None:
parent_style = INITIAL_VALUES
computer = lambda: 0 # Dummy object that holds attributes
computer.element = element
computer.pseudo_type = pseudo_type
computer.specified = specified
computer.computed = computed
computer.parent_style = parent_style
getter = COMPUTER_FUNCTIONS.get
for name in COMPUTING_ORDER:
if name in computed:
# Already computed
continue
value = specified[name]
function = getter(name)
if function is not None:
value = function(computer, name, value)
# else: same as specified
computed[name] = value
computed['_weasy_specified_display'] = specified.display
return computed
# Let's be consistent, always use ``name`` as an argument even when
# it is useless.
# pylint: disable=W0613
@register_computer('background-image')
def background_image(computer, name, values):
"""Compute lenghts in gradient background-image."""
for type_, value in values:
if type_ in ('linear-gradient', 'radial-gradient'):
value.stop_positions = [
length(computer, name, pos) if pos is not None else None
for pos in value.stop_positions]
if type_ == 'radial-gradient':
value.center, = background_position(computer, name, [value.center])
if value.size_type == 'explicit':
value.size = length_or_percentage_tuple(
computer, name, value.size)
return values
@register_computer('background-position')
def background_position(computer, name, values):
"""Compute lengths in background-position."""
return [
(origin_x, length(computer, name, pos_x),
origin_y, length(computer, name, pos_y))
for origin_x, pos_x, origin_y, pos_y in values]
@register_computer('transform-origin')
def length_or_percentage_tuple(computer, name, values):
"""Compute the lists of lengths that can be percentages."""
return tuple(length(computer, name, value) for value in values)
@register_computer('border-spacing')
@register_computer('size')
@register_computer('clip')
def length_tuple(computer, name, values):
"""Compute the properties with a list of lengths."""
return tuple(length(computer, name, value, pixels_only=True)
for value in values)
@register_computer('top')
@register_computer('right')
@register_computer('left')
@register_computer('bottom')
@register_computer('margin-top')
@register_computer('margin-right')
@register_computer('margin-bottom')
@register_computer('margin-left')
@register_computer('height')
@register_computer('width')
@register_computer('min-width')
@register_computer('min-height')
@register_computer('max-width')
@register_computer('max-height')
@register_computer('padding-top')
@register_computer('padding-right')
@register_computer('padding-bottom')
@register_computer('padding-left')
@register_computer('text-indent')
@register_computer('hyphenate-limit-zone')
def length(computer, name, value, font_size=None, pixels_only=False):
"""Compute a length ``value``."""
if value == 'auto':
return value
if value.value == 0:
return 0 if pixels_only else ZERO_PIXELS
unit = value.unit
if unit == 'px':
return value.value if pixels_only else value
elif unit in LENGTHS_TO_PIXELS:
# Convert absolute lengths to pixels
result = value.value * LENGTHS_TO_PIXELS[unit]
elif unit in ('em', 'ex', 'ch'):
if font_size is None:
font_size = computer.computed.font_size
if unit in ('ex', 'ch'):
# TODO: cache
if unit == 'ex':
result = value.value * font_size * ex_ratio(computer.computed)
elif unit == 'ch':
layout = text.Layout(
hinting=False, font_size=font_size,
style=computer.computed)
layout.set_text('0')
line, = layout.iter_lines()
logical_width, _ = text.get_size(line)
result = value.value * logical_width
elif unit == 'em':
result = value.value * font_size
else:
# A percentage or 'auto': no conversion needed.
return value
return result if pixels_only else Dimension(result, 'px')
@register_computer('letter-spacing')
def pixel_length(computer, name, value):
if value == 'normal':
return value
else:
return length(computer, name, value, pixels_only=True)
@register_computer('background-size')
def background_size(computer, name, values):
"""Compute the ``background-size`` properties."""
return [value if value in ('contain', 'cover') else
length_or_percentage_tuple(computer, name, value)
for value in values]
@register_computer('border-top-width')
@register_computer('border-right-width')
@register_computer('border-left-width')
@register_computer('border-bottom-width')
@register_computer('outline-width')
def border_width(computer, name, value):
"""Compute the ``border-*-width`` properties."""
style = computer.computed[name.replace('width', 'style')]
if style in ('none', 'hidden'):
return 0
if value in BORDER_WIDTH_KEYWORDS:
return BORDER_WIDTH_KEYWORDS[value]
if isinstance(value, int):
# The initial value can get here, but length() would fail as
# it does not have a 'unit' attribute.
return value
return length(computer, name, value, pixels_only=True)
@register_computer('border-top-left-radius')
@register_computer('border-top-right-radius')
@register_computer('border-bottom-left-radius')
@register_computer('border-bottom-right-radius')
def border_radius(computer, name, values):
"""Compute the ``border-*-radius`` properties."""
return [length(computer, name, value) for value in values]
@register_computer('content')
def content(computer, name, values):
"""Compute the ``content`` property."""
if values in ('normal', 'none'):
return values
else:
return [('STRING', computer.element.get(value, ''))
if type_ == 'attr' else (type_, value)
for type_, value in values]
@register_computer('display')
def display(computer, name, value):
"""Compute the ``display`` property.
See http://www.w3.org/TR/CSS21/visuren.html#dis-pos-flo
"""
float_ = computer.specified.float
position = computer.specified.position
if position in ('absolute', 'fixed') or float_ != 'none' or \
getattr(computer.element, 'getparent', lambda: None)() is None:
if value == 'inline-table':
return'table'
elif value in ('inline', 'table-row-group', 'table-column',
'table-column-group', 'table-header-group',
'table-footer-group', 'table-row', 'table-cell',
'table-caption', 'inline-block'):
return 'block'
return value
@register_computer('float')
def compute_float(computer, name, value):
"""Compute the ``float`` property.
See http://www.w3.org/TR/CSS21/visuren.html#dis-pos-flo
"""
if computer.specified.position in ('absolute', 'fixed'):
return 'none'
else:
return value
@register_computer('font-size')
def font_size(computer, name, value):
"""Compute the ``font-size`` property."""
if value in FONT_SIZE_KEYWORDS:
return FONT_SIZE_KEYWORDS[value]
# TODO: support 'larger' and 'smaller'
parent_font_size = computer.parent_style['font_size']
if value.unit == '%':
return value.value * parent_font_size / 100.
else:
return length(computer, name, value, pixels_only=True,
font_size=parent_font_size)
@register_computer('font-weight')
def font_weight(computer, name, value):
"""Compute the ``font-weight`` property."""
if value == 'normal':
return 400
elif value == 'bold':
return 700
elif value in ('bolder', 'lighter'):
parent_value = computer.parent_style['font_weight']
# Use a string here as StyleDict.__setattr__ turns integers into pixel
# lengths. This is a number without unit.
return FONT_WEIGHT_RELATIVE[value][parent_value]
else:
return value
@register_computer('line-height')
def line_height(computer, name, value):
"""Compute the ``line-height`` property."""
if value == 'normal':
return value
elif not value.unit:
return ('NUMBER', value.value)
elif value.unit == '%':
factor = value.value / 100.
font_size_value = computer.computed.font_size
pixels = factor * font_size_value
else:
pixels = length(computer, name, value, pixels_only=True)
return ('PIXELS', pixels)
@register_computer('anchor')
def anchor(computer, name, values):
"""Compute the ``anchor`` property."""
if values != 'none':
_, key = values
return computer.element.get(key) or None
@register_computer('link')
def link(computer, name, values):
"""Compute the ``link`` property."""
if values == 'none':
return None
else:
type_, value = values
if type_ == 'attr':
return get_link_attribute(computer.element, value)
else:
return values
@register_computer('lang')
def lang(computer, name, values):
"""Compute the ``lang`` property."""
if values == 'none':
return None
else:
type_, key = values
if type_ == 'attr':
return computer.element.get(key) or None
elif type_ == 'string':
return key
@register_computer('transform')
def transform(computer, name, value):
"""Compute the ``transform`` property."""
result = []
for function, args in value:
if function == 'translate':
args = length_or_percentage_tuple(computer, name, args)
result.append((function, args))
return result
@register_computer('vertical-align')
def vertical_align(computer, name, value):
"""Compute the ``vertical-align`` property."""
# Use +/- half an em for super and sub, same as Pango.
# (See the SUPERSUB_RISE constant in pango-markup.c)
if value in ('baseline', 'middle', 'text-top', 'text-bottom',
'top', 'bottom'):
return value
elif value == 'super':
return computer.computed.font_size * 0.5
elif value == 'sub':
return computer.computed.font_size * -0.5
elif value.unit == '%':
height, _ = strut_layout(computer.computed)
return height * value.value / 100.
else:
return length(computer, name, value, pixels_only=True)
@register_computer('word-spacing')
def word_spacing(computer, name, value):
"""Compute the ``word-spacing`` property."""
if value == 'normal':
return 0
else:
return length(computer, name, value, pixels_only=True)
def strut_layout(style, hinting=True):
"""Return a tuple of the used value of ``line-height`` and the baseline.
The baseline is given from the top edge of line height.
"""
# TODO: cache these results for a given set of styles?
line_height = style.line_height
if style.font_size == 0:
pango_height = baseline = 0
else:
# TODO: get the real value for `hinting`? (if we really care…)
_, _, _, _, pango_height, baseline = text.split_first_line(
'', style, hinting=hinting, max_width=None, line_width=None)
if line_height == 'normal':
return pango_height, baseline
type_, value = line_height
if type_ == 'NUMBER':
value *= style.font_size
return value, baseline + (value - pango_height) / 2
def ex_ratio(style):
"""Return the ratio 1ex/font_size, according to given style."""
font_size = 1000 # big value
layout = text.Layout(hinting=False, font_size=font_size, style=style)
layout.set_text('x')
line, = layout.iter_lines()
_, ink_height_above_baseline = text.get_ink_position(line)
# Zero means some kind of failure, fallback is 0.5.
# We round to try keeping exact values that were altered by Pango.
return round(-ink_height_above_baseline / font_size, 5) or 0.5
| bsd-3-clause |
ardekantur/pyglet | pyglet/app/cocoa.py | 7023 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
from __future__ import with_statement
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from pyglet.app.base import PlatformEventLoop
from pyglet.libs.darwin import *
class CocoaEventLoop(PlatformEventLoop):
def __init__(self):
super(CocoaEventLoop, self).__init__()
# Prepare the default application.
NSApplication.sharedApplication()
# Create an autorelease pool for menu creation and finishLaunching
pool = NSAutoreleasePool.alloc().init()
self._create_application_menu()
# The value for the ApplicationPolicy is 0 as opposed to the
# constant name NSApplicationActivationPolicyRegular, as it
# doesn't appear to be in the bridge support in Apple's pyObjC
# as of OS X 10.6.7
NSApp().setActivationPolicy_(0)
NSApp().finishLaunching()
NSApp().activateIgnoringOtherApps_(True)
# Then get rid of the pool when we're done.
del pool
def _create_application_menu(self):
# Sets up a menu and installs a "quit" item so that we can use
# Command-Q to exit the application.
# See http://cocoawithlove.com/2010/09/minimalist-cocoa-programming.html
# This could also be done much more easily with a NIB.
menubar = NSMenu.alloc().init()
appMenuItem = NSMenuItem.alloc().init()
menubar.addItem_(appMenuItem)
NSApp().setMainMenu_(menubar)
appMenu = NSMenu.alloc().init()
processName = NSProcessInfo.processInfo().processName()
hideItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
"Hide " + processName, "hide:", "h")
appMenu.addItem_(hideItem)
appMenu.addItem_(NSMenuItem.separatorItem())
quitItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
"Quit " + processName, "terminate:", "q")
appMenu.addItem_(quitItem)
appMenuItem.setSubmenu_(appMenu)
def start(self):
pass
def step(self, timeout=None):
# Create an autorelease pool for this iteration.
pool = NSAutoreleasePool.alloc().init()
# Determine the timeout date.
if timeout is None:
# Using distantFuture as untilDate means that nextEventMatchingMask
# will wait until the next event comes along.
timeout_date = NSDate.distantFuture()
else:
timeout_date = NSDate.dateWithTimeIntervalSinceNow_(timeout)
# Retrieve the next event (if any). We wait for an event to show up
# and then process it, or if timeout_date expires we simply return.
# We only process one event per call of step().
self._is_running.set()
event = NSApp().nextEventMatchingMask_untilDate_inMode_dequeue_(
NSAnyEventMask, timeout_date, NSDefaultRunLoopMode, True)
# Dispatch the event (if any).
if event is not None:
event_type = event.type()
if event_type != NSApplicationDefined:
# Send out event as normal. Responders will still receive
# keyUp:, keyDown:, and flagsChanged: events.
NSApp().sendEvent_(event)
# Resend key events as special pyglet-specific messages
# which supplant the keyDown:, keyUp:, and flagsChanged: messages
# because NSApplication translates multiple key presses into key
# equivalents before sending them on, which means that some keyUp:
# messages are never sent for individual keys. Our pyglet-specific
# replacements ensure that we see all the raw key presses & releases.
# We also filter out key-down repeats since pyglet only sends one
# on_key_press event per key press.
if event_type == NSKeyDown and not event.isARepeat():
NSApp().sendAction_to_from_("pygletKeyDown:", None, event)
elif event_type == NSKeyUp:
NSApp().sendAction_to_from_("pygletKeyUp:", None, event)
elif event_type == NSFlagsChanged:
NSApp().sendAction_to_from_("pygletFlagsChanged:", None, event)
NSApp().updateWindows()
did_time_out = False
else:
did_time_out = True
self._is_running.clear()
# Destroy the autorelease pool used for this step.
del pool
return did_time_out
def stop(self):
pass
def notify(self):
pool = NSAutoreleasePool.alloc().init()
notifyEvent = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
NSApplicationDefined, # type
NSPoint(0.0, 0.0), # location
0, # modifierFlags
0, # timestamp
0, # windowNumber
None, # graphicsContext
0, # subtype
0, # data1
0, # data2
)
NSApp().postEvent_atStart_(notifyEvent, False)
del pool
| bsd-3-clause |
montagejs/q-git | test/fs-test.js | 12244 |
var Q = require("q");
var GitFs = require("../fs");
var fs = require("q-io/fs");
Q.longStackSupport = true;
var repo = {};
repo.rootPath = fs.join(__dirname, "..", ".git");
require("git-node-fs/mixins/fs-db")(repo, repo.rootPath);
require('js-git/mixins/create-tree')(repo);
require('js-git/mixins/pack-ops')(repo);
require('js-git/mixins/walkers')(repo);
require('js-git/mixins/read-combiner')(repo);
require('js-git/mixins/formats')(repo);
var gitFs;
beforeEach(function () {
gitFs = new GitFs(repo);
return gitFs.load("refs/heads/master");
});
describe("readLink", function () {
it("reads a symbolic link", function () {
return gitFs.readLink("test/fixtures")
.then(function (link) {
expect(link).toBe("fixture")
})
});
it("fails to read a non-link", function () {
return gitFs.readLink("test/fixture")
.then(function (link) {
expect(false).toBe(true);
}, function (error) {
expect(error.message).toBe("Can't read non-symbolic-link at \"test/fixture\"")
expect(error.code).toBe("EINVAL")
})
});
});
describe("canonical", function () {
it("follows a symbolic link", function () {
return gitFs.canonical("test/fixtures")
.then(function (path) {
expect(path).toBe("/test/fixture");
});
});
it("follows through a symbolic link to a file", function () {
return gitFs.canonical("test/fixtures/hello.txt")
.then(function (path) {
expect(path).toBe("/test/fixture/hello.txt");
});
});
it("follows a symbolic link as far as it can then joins the remainder", function () {
return gitFs.canonical("test/fixtures/defunct/zombie")
.then(function (path) {
expect(path).toBe("/test/fixture/defunct/zombie");
});
});
});
describe("list", function () {
it("lists a directory", function () {
return gitFs.list("test/fixture")
.then(function (list) {
expect(list).toEqual(["0123456789.txt", "hello.txt"])
})
});
it("lists a symbolic link to a directory", function () {
return gitFs.list("test/fixture")
.then(function (list) {
expect(list).toEqual(["0123456789.txt", "hello.txt"])
})
});
it("fails to list a non existing directory", function () {
return gitFs.list("test/fixture/defunct")
.then(function () {
expect(true).toBe(false);
}, function (error) {
expect(error.message).toBe("Can't list \"test/fixture/defunct\" because Can't find \"/test/fixture/defunct\"");
expect(error.code).toBe("ENOENT");
});
});
it("fails to list a non-directory", function () {
return gitFs.list("test/fixture/hello.txt")
.then(function () {
expect(true).toBe(false);
}, function (error) {
expect(error.message).toBe("Can't list non-directory \"/test/fixture/hello.txt\"");
expect(error.code).toBe("ENOTDIR");
});
});
});
describe("stat and statLink", function () {
it("distinguish files, directories, and symbolic links", function () {
return Q()
.then(function () {
return gitFs.stat("/test/fixture/hello.txt")
})
.then(function (stat) {
expect(stat.isFile()).toBe(true);
expect(stat.isDirectory()).toBe(false);
expect(stat.isSymbolicLink()).toBe(false);
})
.then(function () {
return gitFs.stat("/test/fixture")
})
.then(function (stat) {
expect(stat.isFile()).toBe(false);
expect(stat.isDirectory()).toBe(true);
expect(stat.isSymbolicLink()).toBe(false);
})
.then(function () {
return gitFs.statLink("/test/fixtures")
})
.then(function (stat) {
expect(stat.isFile()).toBe(false);
expect(stat.isDirectory()).toBe(false);
expect(stat.isSymbolicLink()).toBe(true);
})
.then(function () {
return gitFs.stat("/test/fixtures")
})
.then(function (stat) {
expect(stat.isFile()).toBe(false);
expect(stat.isDirectory()).toBe(true);
expect(stat.isSymbolicLink()).toBe(false);
})
});
});
describe("read", function () {
it("reads the whole content of a file", function () {
return gitFs.read("/test/fixture/hello.txt")
.then(function (content) {
expect(content.toString()).toBe("Hello, World!\n");
})
});
it("reads the whole content of a file in charset", function () {
return gitFs.read("/test/fixture/hello.txt", {charset: "utf-8"})
.then(function (content) {
expect(content).toBe("Hello, World!\n");
})
});
it("reads a partial range", function () {
return gitFs.read("/test/fixture/0123456789.txt", {
begin: 2,
end: 4
})
.then(function (content) {
expect(content.toString()).toBe("23");
})
});
});
describe("write", function () {
it("writes a file", function () {
return gitFs.write("/test/fixture/bye.txt", "Good bye, cruel World!\n")
.then(function () {
return [
gitFs.list("/test/fixture"),
gitFs.read("/test/fixture/bye.txt")
];
})
.spread(function (list, content) {
expect(list).toEqual(["0123456789.txt", "bye.txt", "hello.txt"]);
expect(content.toString()).toBe("Good bye, cruel World!\n");
})
});
it("fails to overwrite a directory", function () {
return gitFs.write("test/fixture", "Good bye, cruel World!\n")
.then(function () {
expect(true).toBe(false);
}, function (error) {
expect(error.message).toBe("Can't over-write directory \"/test/fixture\"");
expect(error.code).toBe("EISDIR");
})
});
});
describe("remove", function () {
it("removes a file", function () {
return gitFs.remove("/test/fixture/hello.txt")
.then(function () {
return gitFs.list("/test/fixture");
})
.then(function (list) {
expect(list).toEqual(["0123456789.txt"]);
})
});
it("fails to remove a non-existant file", function () {
return gitFs.remove("test/fixture/bye.txt")
.then(function () {
expect(true).toBe(false);
}, function (error) {
expect(error.message).toBe("Can't remove \"test/fixture/bye.txt\" because Can't find \"/test/fixture/bye.txt\"");
expect(error.code).toBe("ENOENT");
})
});
it("fails to remove a non-file", function () {
return gitFs.remove("test/fixture")
.then(function () {
expect(true).toBe(false);
}, function (error) {
expect(error.message).toBe("Can't remove \"test/fixture\" because Can't remove non-file \"/test/fixture\"");
expect(error.code).toBe("EINVAL");
})
});
});
describe("removeDirectory", function () {
it("removes a directory", function () {
return gitFs.makeDirectory("/test/fixture/directory")
.then(function () {
return gitFs.removeDirectory("/test/fixture/directory")
})
.then(function () {
return [
gitFs.list("/test/fixture"),
gitFs.isDirectory("/test/fixture/directory")
]
})
.spread(function (parent, isDirectory) {
expect(parent).toEqual(["0123456789.txt", "hello.txt"]);
expect(isDirectory).toBe(false);
})
});
it("fails to remove a non-existant directory", function () {
return gitFs.removeDirectory("/test/fixture/directory")
.then(function () {
expect(true).toBe(false);
}, function (error) {
expect(error.message).toBe("Can't remove non-existant directory \"/test/fixture/directory\"");
expect(error.code).toBe("ENOENT");
})
});
it("fails to remove a non-directory", function () {
return gitFs.removeDirectory("test/fixture/hello.txt")
.then(function () {
expect(true).toBe(false);
}, function (error) {
expect(error.message).toBe("Can't remove non-directory \"/test/fixture/hello.txt\"");
expect(error.code).toBe("ENOTDIR");
})
});
it("fails to remove a non-empty directory", function () {
return gitFs.removeDirectory("test/fixture")
.then(function () {
expect(true).toBe(false);
}, function (error) {
expect(error.message).toBe("Can't remove non-empty directory \"/test/fixture\"");
expect(error.code).toBe("ENOTEMPTY");
})
});
});
describe("removeTree", function () {
it("removes a child tree", function () {
return gitFs.removeTree("/test")
.then(function () {
return gitFs.list("/")
})
.then(function (list) {
expect(list).not.toContain("test");
});
});
it("removes an entire tree like a knife through butter", function () {
return gitFs.removeTree("/")
.then(function () {
return gitFs.list("/")
})
.then(function (list) {
expect(list).toEqual([]);
});
});
});
describe("makeDirectory", function () {
it("makes a directory", function () {
return gitFs.makeDirectory("/test/fixture/directory")
.then(function () {
return [
gitFs.list("/test/fixture"),
gitFs.list("/test/fixture/directory"),
gitFs.isDirectory("/test/fixture/directory")
]
})
.spread(function (parent, child, isDirectory) {
expect(parent).toEqual(["0123456789.txt", "directory", "hello.txt"]);
expect(child).toEqual([]);
expect(isDirectory).toBe(true);
})
});
it("fails to overwrite a directory", function () {
return gitFs.makeDirectory("/test/fixture")
.then(function () {
expect(true).toBe(false);
}, function (error) {
expect(error.message).toBe("Can't make directory over existing directory at \"/test/fixture\"");
expect(error.code).toBe("EISDIR");
});
});
it("fails to overwrite a file", function () {
return gitFs.makeDirectory("/test/fixture/hello.txt")
.then(function () {
expect(true).toBe(false);
}, function (error) {
expect(error.message).toBe("Can't make directory over existing entry at \"/test/fixture/hello.txt\"");
expect(error.code).toBe("EEXIST");
});
});
it("fails to make directory in non-existent directory", function () {
return gitFs.makeDirectory("test/fixture/defunct/zombie")
.then(function () {
expect(true).toBe(false);
}, function (error) {
expect(error.message).toBe("Can't make directory \"test/fixture/defunct/zombie\" because Can't find \"/test/fixture/defunct\"");
expect(error.code).toBe("ENOENT");
});
});
});
describe("index management", function () {
it("clears, saves, restores references", function () {
return gitFs.clear()
.then(function () {
return gitFs.commit({
message: "FIRST!",
author: {name: "Kris Kowal", email: "kris@cixar.com"}
})
})
.then(function () {
return gitFs.saveAs("TEST");
})
.then(function () {
return gitFs.load("refs/heads/master")
})
.then(function () {
return gitFs.list("test")
})
.then(function (list) {
expect(list).toContain("fixture");
return gitFs.load("TEST")
})
.then(function () {
return gitFs.list("");
})
.then(function (list) {
expect(list).toEqual([]);
})
});
});
| bsd-3-clause |
zart/jinja2 | setup.py | 2287 | # -*- coding: utf-8 -*-
"""
Jinja2
~~~~~~
Jinja2 is a template engine written in pure Python. It provides a
`Django`_ inspired non-XML syntax but supports inline expressions and
an optional `sandboxed`_ environment.
Nutshell
--------
Here a small example of a Jinja template::
{% extends 'base.html' %}
{% block title %}Memberlist{% endblock %}
{% block content %}
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
{% endblock %}
Philosophy
----------
Application logic is for the controller but don't try to make the life
for the template designer too hard by giving him too few functionality.
For more informations visit the new `Jinja2 webpage`_ and `documentation`_.
.. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_(computer_security)
.. _Django: http://www.djangoproject.com/
.. _Jinja2 webpage: http://jinja.pocoo.org/
.. _documentation: http://jinja.pocoo.org/2/documentation/
"""
from setuptools import setup
setup(
name='Jinja2',
version='2.8-dev',
url='http://jinja.pocoo.org/',
license='BSD',
author='Armin Ronacher',
author_email='armin.ronacher@active-4.com',
description='A small but fast and easy to use stand-alone template '
'engine written in pure python.',
long_description=__doc__,
# jinja is egg safe. But we hate eggs
zip_safe=False,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Markup :: HTML'
],
packages=['jinja2', 'jinja2.testsuite', 'jinja2.testsuite.res'],
install_requires=['MarkupSafe'],
extras_require={'i18n': ['Babel>=0.8']},
test_suite='jinja2.testsuite.suite',
include_package_data=True,
entry_points="""
[babel.extractors]
jinja2 = jinja2.ext:babel_extract[i18n]
"""
)
| bsd-3-clause |
blueyed/pytest_django | tests/db_helpers.py | 3937 | import subprocess
import pytest
from .compat import force_text
from django.conf import settings
DB_NAME = settings.DATABASES['default']['NAME'] + '_db_test'
TEST_DB_NAME = 'test_' + DB_NAME
def get_db_engine():
from django.conf import settings
return settings.DATABASES['default']['ENGINE'].split('.')[-1]
class CmdResult(object):
def __init__(self, status_code, std_out, std_err):
self.status_code = status_code
self.std_out = std_out
self.std_err = std_err
def run_cmd(*args):
r = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdoutdata, stderrdata = r.communicate()
ret = r.wait()
return CmdResult(ret, stdoutdata, stderrdata)
def run_mysql(*args):
from django.conf import settings
user = settings.DATABASES['default'].get('USER', None)
if user:
args = ('-u', user) + tuple(args)
args = ('mysql',) + tuple(args)
return run_cmd(*args)
def skip_if_sqlite():
from django.conf import settings
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
pytest.skip('Do not test db reuse since database does not support it')
def create_empty_production_database():
drop_database(name=DB_NAME)
if get_db_engine() == 'postgresql_psycopg2':
r = run_cmd('psql', 'postgres', '-c', 'CREATE DATABASE %s' % DB_NAME)
assert ('CREATE DATABASE' in force_text(r.std_out) or
'already exists' in force_text(r.std_err))
return
if get_db_engine() == 'mysql':
r = run_mysql('-e', 'CREATE DATABASE %s' % DB_NAME)
assert (r.status_code == 0 or
'database exists' in force_text(r.std_out) or
'database exists' in force_text(r.std_err))
return
raise AssertionError('%s cannot be tested properly' % get_db_engine())
def drop_database(name=TEST_DB_NAME, suffix=None):
assert bool(name) ^ bool(suffix), 'name and suffix cannot be used together'
if suffix:
name = '%s_%s' % (name, suffix)
if get_db_engine() == 'postgresql_psycopg2':
r = run_cmd('psql', 'postgres', '-c', 'DROP DATABASE %s' % name)
assert ('DROP DATABASE' in force_text(r.std_out) or
'does not exist' in force_text(r.std_err))
return
if get_db_engine() == 'mysql':
r = run_mysql('-e', 'DROP DATABASE %s' % name)
assert ('database doesn\'t exist' in force_text(r.std_err)
or r.status_code == 0)
return
raise AssertionError('%s cannot be tested properly!' % get_db_engine())
def db_exists(db_suffix=None):
name = TEST_DB_NAME
if db_suffix:
name = '%s_%s' % (name, db_suffix)
if get_db_engine() == 'postgresql_psycopg2':
r = run_cmd('psql', name, '-c', 'SELECT 1')
return r.status_code == 0
if get_db_engine() == 'mysql':
r = run_mysql(name, '-e', 'SELECT 1')
return r.status_code == 0
raise AssertionError('%s cannot be tested properly!' % get_db_engine())
def mark_database():
if get_db_engine() == 'postgresql_psycopg2':
r = run_cmd('psql', TEST_DB_NAME, '-c', 'CREATE TABLE mark_table();')
assert r.status_code == 0
return
if get_db_engine() == 'mysql':
r = run_mysql(TEST_DB_NAME, '-e', 'CREATE TABLE mark_table(kaka int);')
assert r.status_code == 0
return
raise AssertionError('%s cannot be tested properly!' % get_db_engine())
def mark_exists():
if get_db_engine() == 'postgresql_psycopg2':
r = run_cmd('psql', TEST_DB_NAME, '-c', 'SELECT 1 FROM mark_table')
# When something pops out on std_out, we are good
return bool(r.std_out)
if get_db_engine() == 'mysql':
r = run_mysql(TEST_DB_NAME, '-e', 'SELECT 1 FROM mark_table')
return r.status_code == 0
raise AssertionError('%s cannot be tested properly!' % get_db_engine())
| bsd-3-clause |
lexfrost83/testyii2 | frontend/views/layouts/inner.php | 1204 | <?
use yii\helpers\Html;
use yii\bootstrap\Nav;
\frontend\assets\MainAsset::register($this);
?>
<?
$this->beginPage();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<?= Html::csrfMetaTags() ?>
<?php $this->head() ?>
</head>
<body>
<? if (Yii::$app->session->hasFlash('success')): ?>
<?
$success = Yii::$app->session->getFlash('success');
echo \yii\bootstrap\Alert::widget([
'options' => [
'class' => 'alert-info'
],
'body' => $success
])
?>
<?
endif;
?>
<?
$this->beginBody();
?>
<!-- Header Starts -->
<? echo $this->render("//common/head") ?>
<!-- #Header Starts -->
<div class="inside-banner">
<div class="container">
<span class="pull-right"><a href="#">Home</a> / <?= $this->title ?></span>
<h2><?= $this->title ?></h2>
</div>
</div>
<!-- banner -->
<!-- banner -->
<div class="container">
<div class="spacer">
<?= $content ?>
</div>
</div>
<? echo $this->render("//common/footer") ?>
<?
$this->endBody();
?>
</body>
</html>
<?
$this->endPage();
?>
| bsd-3-clause |
vovancho/yii2test | views/Fregat/config/import.php | 2188 | <?php
use app\func\Proc;
\Yii::$app->getView()->registerJsFile('@web/js/freewall.js' . Proc::appendTimestampUrlParam(Yii::$app->basePath . '/web/js/freewall.js'));
\Yii::$app->getView()->registerJsFile('@web/js/fregatmainmenu.js' . Proc::appendTimestampUrlParam(Yii::$app->basePath . '/web/js/fregatmainmenu.js'));
$this->title = 'Импорт данных';
$this->params['breadcrumbs'] = Proc::Breadcrumbs($this);
?>
<div class="panel panel-<?= Yii::$app->params['panelStyle'] ?> menuplitka">
<div class="panel-heading">Импорт данных</div>
<div class="panel-body">
<div class="menublock">
<?php if (Yii::$app->user->can('FregatImport')): ?>
<div class="menubutton menubutton_activeanim mb_red" id="mb_fregatimp_conf_employee">
<span class="hoverspan"></span>
<div class="menubutton_cn">Настройка импорта сотрудников
</div>
<i class="glyphicon glyphicon-user"></i>
</div>
<div class="menubutton menubutton_activeanim mb_red" id="mb_fregatimp_conf_material">
<span class="hoverspan"></span>
<div class="menubutton_cn">Настройка импорта материальных
ценностей
</div>
<i class="glyphicon glyphicon-gift"></i>
</div>
<div class="menubutton menubutton_activeanim mb_yellow" id="mb_fregatimp_reports">
<span class="hoverspan"></span>
<div class="menubutton_cn">Сервис</div>
<i class="glyphicon glyphicon-inbox"></i>
</div>
<div class="menubutton menubutton_activeanim mb_gray" id="mb_fregatimp_conf">
<span class="hoverspan"></span>
<div class="menubutton_cn">Общие настройки</div>
<i class="glyphicon glyphicon-cog"></i>
</div>
<?php endif; ?>
</div>
</div>
</div>
| bsd-3-clause |
sdmiller/gtsam_pcl | gtsam_unstable/geometry/tests/testInvDepthCamera3.cpp | 5779 | /*
* testInvDepthFactor.cpp
*
* Created on: Apr 13, 2012
* Author: cbeall3
*/
#include <CppUnitLite/TestHarness.h>
#include <gtsam/base/numericalDerivative.h>
#include <gtsam/base/Testable.h>
#include <gtsam/geometry/SimpleCamera.h>
#include <gtsam_unstable/geometry/InvDepthCamera3.h>
using namespace std;
using namespace gtsam;
static Cal3_S2::shared_ptr K(new Cal3_S2(1500, 1200, 0, 640, 480));
Pose3 level_pose = Pose3(Rot3::ypr(-M_PI/2, 0., -M_PI/2), gtsam::Point3(0,0,1));
SimpleCamera level_camera(level_pose, *K);
/* ************************************************************************* */
TEST( InvDepthFactor, Project1) {
// landmark 5 meters infront of camera
Point3 landmark(5, 0, 1);
Point2 expected_uv = level_camera.project(landmark);
InvDepthCamera3<Cal3_S2> inv_camera(level_pose, K);
LieVector inv_landmark(5, 1., 0., 1., 0., 0.);
LieScalar inv_depth(1./4);
Point2 actual_uv = inv_camera.project(inv_landmark, inv_depth);
EXPECT(assert_equal(expected_uv, actual_uv));
EXPECT(assert_equal(Point2(640,480), actual_uv));
}
/* ************************************************************************* */
TEST( InvDepthFactor, Project2) {
// landmark 1m to the left and 1m up from camera
// inv landmark xyz is same as camera xyz, so depth actually doesn't matter
Point3 landmark(1, 1, 2);
Point2 expected = level_camera.project(landmark);
InvDepthCamera3<Cal3_S2> inv_camera(level_pose, K);
LieVector diag_landmark(5, 0., 0., 1., M_PI/4., atan(1.0/sqrt(2.0)));
LieScalar inv_depth(1/sqrt(3.0));
Point2 actual = inv_camera.project(diag_landmark, inv_depth);
EXPECT(assert_equal(expected, actual));
}
/* ************************************************************************* */
TEST( InvDepthFactor, Project3) {
// landmark 1m to the left and 1m up from camera
// inv depth landmark xyz at origion
Point3 landmark(1, 1, 2);
Point2 expected = level_camera.project(landmark);
InvDepthCamera3<Cal3_S2> inv_camera(level_pose, K);
LieVector diag_landmark(5, 0., 0., 0., M_PI/4., atan(2./sqrt(2.0)));
LieScalar inv_depth( 1./sqrt(1.0+1+4));
Point2 actual = inv_camera.project(diag_landmark, inv_depth);
EXPECT(assert_equal(expected, actual));
}
/* ************************************************************************* */
TEST( InvDepthFactor, Project4) {
// landmark 4m to the left and 1m up from camera
// inv depth landmark xyz at origion
Point3 landmark(1, 4, 2);
Point2 expected = level_camera.project(landmark);
InvDepthCamera3<Cal3_S2> inv_camera(level_pose, K);
LieVector diag_landmark(5, 0., 0., 0., atan(4.0/1), atan(2./sqrt(1.+16.)));
LieScalar inv_depth(1./sqrt(1.+16.+4.));
Point2 actual = inv_camera.project(diag_landmark, inv_depth);
EXPECT(assert_equal(expected, actual));
}
/* ************************************************************************* */
Point2 project_(const Pose3& pose, const LieVector& landmark, const LieScalar& inv_depth) {
return InvDepthCamera3<Cal3_S2>(pose,K).project(landmark, inv_depth); }
TEST( InvDepthFactor, Dproject_pose)
{
LieVector landmark(6,0.1,0.2,0.3, 0.1,0.2);
LieScalar inv_depth(1./4);
Matrix expected = numericalDerivative31<Point2,Pose3,LieVector>(project_,level_pose, landmark, inv_depth);
InvDepthCamera3<Cal3_S2> inv_camera(level_pose,K);
Matrix actual;
Point2 uv = inv_camera.project(landmark, inv_depth, actual, boost::none, boost::none);
EXPECT(assert_equal(expected,actual,1e-6));
}
/* ************************************************************************* */
TEST( InvDepthFactor, Dproject_landmark)
{
LieVector landmark(5,0.1,0.2,0.3, 0.1,0.2);
LieScalar inv_depth(1./4);
Matrix expected = numericalDerivative32<Point2,Pose3,LieVector>(project_,level_pose, landmark, inv_depth);
InvDepthCamera3<Cal3_S2> inv_camera(level_pose,K);
Matrix actual;
Point2 uv = inv_camera.project(landmark, inv_depth, boost::none, actual, boost::none);
EXPECT(assert_equal(expected,actual,1e-7));
}
/* ************************************************************************* */
TEST( InvDepthFactor, Dproject_inv_depth)
{
LieVector landmark(5,0.1,0.2,0.3, 0.1,0.2);
LieScalar inv_depth(1./4);
Matrix expected = numericalDerivative33<Point2,Pose3,LieVector>(project_,level_pose, landmark, inv_depth);
InvDepthCamera3<Cal3_S2> inv_camera(level_pose,K);
Matrix actual;
Point2 uv = inv_camera.project(landmark, inv_depth, boost::none, boost::none, actual);
EXPECT(assert_equal(expected,actual,1e-7));
}
/* ************************************************************************* */
TEST(InvDepthFactor, backproject)
{
LieVector expected(5,0.,0.,1., 0.1,0.2);
LieScalar inv_depth(1./4);
InvDepthCamera3<Cal3_S2> inv_camera(level_pose,K);
Point2 z = inv_camera.project(expected, inv_depth);
LieVector actual_vec;
LieScalar actual_inv;
boost::tie(actual_vec, actual_inv) = inv_camera.backproject(z, 4);
EXPECT(assert_equal(expected,actual_vec,1e-7));
EXPECT(assert_equal(inv_depth,actual_inv,1e-7));
}
/* ************************************************************************* */
TEST(InvDepthFactor, backproject2)
{
// backwards facing camera
LieVector expected(5,-5.,-5.,2., 3., -0.1);
LieScalar inv_depth(1./10);
InvDepthCamera3<Cal3_S2> inv_camera(Pose3(Rot3::ypr(1.5,0.1, -1.5), Point3(-5, -5, 2)),K);
Point2 z = inv_camera.project(expected, inv_depth);
LieVector actual_vec;
LieScalar actual_inv;
boost::tie(actual_vec, actual_inv) = inv_camera.backproject(z, 10);
EXPECT(assert_equal(expected,actual_vec,1e-7));
EXPECT(assert_equal(inv_depth,actual_inv,1e-7));
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
| bsd-3-clause |
beermon/beermon-server | db/migrate/20121016224326_remove_beer_information_from_keg.rb | 302 | class RemoveBeerInformationFromKeg < ActiveRecord::Migration
def change
remove_column :kegs, :brewery
remove_column :kegs, :name
remove_column :kegs, :ibu
remove_column :kegs, :srm
add_column :kegs, :beer_tap_id, :integer
add_column :kegs, :beer_id, :integer
end
end
| bsd-3-clause |
frc868/2014-robot-iri | src/com/techhounds/commands/pneumatics/RunCompressor.java | 1447 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.techhounds.commands.pneumatics;
import com.techhounds.commands.CommandBase;
import com.techhounds.subsystems.CompressorSubsystem;
/**
* @author Atif Niyaz
*/
public class RunCompressor extends CommandBase {
private CompressorSubsystem compressor;
public RunCompressor() {
compressor = CompressorSubsystem.getInstance();
requires(compressor);
setInterruptible(false);
}
// Called just before this Command runs the first time
protected void initialize() {}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if(compressor.isMaxPressure()
//|| CompressorSubsystem.getIsDrivingFast()
|| CompressorSubsystem.getIsShooting())
compressor.stop();
else
compressor.start();
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() { return false; }
// Called once after isFinished returns true
protected void end() {}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {}
}
| bsd-3-clause |