repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
quaintm/octopus | octopus/static/libs/typeahead.js/test/highlight_spec.js | 3601 | describe('highlight', function () {
it('should allow tagName to be specified', function () {
var before = 'abcde',
after = 'a<span>bcd</span>e',
testNode = buildTestNode(before);
highlight({node: testNode, pattern: 'bcd', tagName: 'span'});
expect(testNode.innerHTML).toEqual(after);
});
it('should allow className to be specified', function () {
var before = 'abcde',
after = 'a<strong class="one two">bcd</strong>e',
testNode = buildTestNode(before);
highlight({node: testNode, pattern: 'bcd', className: 'one two'});
expect(testNode.innerHTML).toEqual(after);
});
it('should be case insensitive by default', function () {
var before = 'ABCDE',
after = 'A<strong>BCD</strong>E',
testNode = buildTestNode(before);
highlight({node: testNode, pattern: 'bcd'});
expect(testNode.innerHTML).toEqual(after);
});
it('should support case sensitivity', function () {
var before = 'ABCDE',
after = 'ABCDE',
testNode = buildTestNode(before);
highlight({node: testNode, pattern: 'bcd', caseSensitive: true});
expect(testNode.innerHTML).toEqual(after);
});
it('should support words only matching', function () {
var before = 'tone one phone',
after = 'tone <strong>one</strong> phone',
testNode = buildTestNode(before);
highlight({node: testNode, pattern: 'one', wordsOnly: true});
expect(testNode.innerHTML).toEqual(after);
});
it('should support matching multiple patterns', function () {
var before = 'tone one phone',
after = '<strong>tone</strong> one <strong>phone</strong>',
testNode = buildTestNode(before);
highlight({node: testNode, pattern: ['tone', 'phone']});
expect(testNode.innerHTML).toEqual(after);
});
it('should support regex chars in the pattern', function () {
var before = '*.js when?',
after = '<strong>*.</strong>js when<strong>?</strong>',
testNode = buildTestNode(before);
highlight({node: testNode, pattern: ['*.', '?']});
expect(testNode.innerHTML).toEqual(after);
});
it('should work on complex html structures', function () {
var before = [
'<div>abcde',
'<span>abcde</span>',
'<div><p>abcde</p></div>',
'</div>'
].join(''),
after = [
'<div><strong>abc</strong>de',
'<span><strong>abc</strong>de</span>',
'<div><p><strong>abc</strong>de</p></div>',
'</div>'
].join(''),
testNode = buildTestNode(before);
highlight({node: testNode, pattern: 'abc'});
expect(testNode.innerHTML).toEqual(after);
});
it('should ignore html tags and attributes', function () {
var before = '<span class="class"></span>',
after = '<span class="class"></span>',
testNode = buildTestNode(before);
highlight({node: testNode, pattern: ['span', 'class']});
expect(testNode.innerHTML).toEqual(after);
});
it('should not match across tags', function () {
var before = 'a<span>b</span>c',
after = 'a<span>b</span>c',
testNode = buildTestNode(before);
highlight({node: testNode, pattern: 'abc'});
expect(testNode.innerHTML).toEqual(after);
});
it('should ignore html comments', function () {
var before = '<!-- abc -->',
after = '<!-- abc -->',
testNode = buildTestNode(before);
highlight({node: testNode, pattern: 'abc'});
expect(testNode.innerHTML).toEqual(after);
});
function buildTestNode(content) {
var node = document.createElement('div');
node.innerHTML = content;
return node;
}
});
| bsd-3-clause |
neutrinog/Comperio | comperio/bugs/views.py | 1353 | from comperio.main.tools import MessageManager, render
from comperio.bugs.forms import BugForm
from django.shortcuts import Http404, redirect
from comperio.accounts.views import login_view
from comperio.bugs.models import Bug
def bugs(request):
"""bugs page"""
# prepare messages
mm = MessageManager(request)
bugs = Bug.objects.all()
return render(request, 'bugs/index.html', {'bugs':bugs}, mm.messages())
def create_bug(request):
"""create a new bug report"""
# prepare messages
mm = MessageManager(request)
if request.user.is_authenticated():
if request.POST:
form = BugForm(request.POST)
if form.is_valid():
form.save(request)
mm.set_success("Thanks! We'll fix this bug as soon as possible.")
return redirect('/')
else:
return render(request, 'bugs/create.html', mm.messages(), {'form':form})
else:
form = BugForm()
return render(request, 'bugs/create.html', mm.messages(), {'form':form})
mm.set_notice("You must log in before you can report a bug")
return login_view(request)
def view_bug(request, id):
"""view an individual bug report"""
# prepare messages
mm = MessageManager(request)
return render(request, 'bugs/view.html', mm.messages()) | bsd-3-clause |
loadtestgo/pizzascript | script-tester/src/main/java/com/loadtestgo/script/tester/pages/Headers.java | 1178 | package com.loadtestgo.script.tester.pages;
import com.loadtestgo.script.tester.annotations.Page;
import com.loadtestgo.script.tester.server.HttpHeaders;
import com.loadtestgo.script.tester.server.HttpRequest;
import com.loadtestgo.util.HttpHeader;
import java.io.IOException;
public class Headers {
@Page(desc = "Show all headers")
public void all(HttpRequest request) throws IOException {
HttpHeaders headers = request.readHeaders();
request.write("HTTP/1.1 200 OK\r\n\r\n");
request.write("<html><head></head><body><h1>All Headers</h1>");
for (HttpHeader header : headers) {
request.write(String.format("<p>%s: %s</p>", header.name, header.value));
}
request.write("</body></html>");
}
@Page(desc = "Show User Agent header")
public void userAgent(HttpRequest request) throws IOException {
HttpHeaders headers = request.readHeaders();
request.write("HTTP/1.1 200 OK\r\n\r\n");
request.write("<html><head></head><body><h1>User Agent</h1>");
request.write(String.format("<p>%s</p>", headers.get("User-Agent")));
request.write("</body></html>");
}
}
| bsd-3-clause |
miguelolivaresmendez/mofs | doc/mofs/html/search/all_7.js | 993 | var searchData=
[
['gaz',['gaz',['../structControlCommand.html#a67f1f379ff9963d15736c1e39c272e0d',1,'ControlCommand']]],
['genrule',['genRule',['../classmofs_1_1MOFSModel.html#a99f4ef974f0056a533ddee53b7e869f9',1,'mofs::MOFSModel']]],
['genrulebase',['genRulebase',['../classmofs_1_1MOFSModel.html#a2991bc845158d93913a9fa3e7b15add9',1,'mofs::MOFSModel']]],
['getcurrenttarget',['getCurrentTarget',['../classDroneController.html#adb8a9508d49eebb014c5489288746d55',1,'DroneController']]],
['getlastcontrol',['getLastControl',['../classDroneController.html#a6fc756271c117d1c41f224772d1ef9d1',1,'DroneController']]],
['getlasterr',['getLastErr',['../classDroneController.html#a60334e0c1638e511bbd53fbb791b1ef4',1,'DroneController']]],
['getvalidrules',['getValidRules',['../classmofs_1_1MOFSModel.html#a530210aeb55ae24b3d22363cbd2df946',1,'mofs::MOFSModel']]],
['guardapos',['guardaPos',['../classmofs_1_1MOFSModel.html#a00a6fcd8fbb222753a703fc8118353d7',1,'mofs::MOFSModel']]]
];
| bsd-3-clause |
junctionaof/thanagornfarm | backend/views/pond/edittype.php | 5823 | <?php
use yii\helpers\Url;
use yii\web\View;
use yii\helpers\Html;
use app\CategoryTree;
use app\DateUtil;
use app\Workflow;
use backend\components\UserMessage;
use backend\components\UiMessage;
use backend\components\Portlet;
use common\models\FAQ;
use backend\components\TagCloud;
use common\models\Food;
use common\models\Typelist;
$baseUrl = \Yii::getAlias('@web');
$cancelUrl = Url::toRoute('faq/list');
$identity = \Yii::$app->user->getIdentity();
$contentDate = "";
$contentTime = "";
$this->registerCssFile($baseUrl . '/assets/global/plugins/select2/css/select2.min.css',['position' => \yii\web\View::POS_HEAD]) ;
$this->registerCssFile($baseUrl . '/assets/global/plugins/select2/css/select2-bootstrap.min.css',['position' => \yii\web\View::POS_HEAD]) ;
$this->registerCssFile($baseUrl . '/assets/global/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.min.css',['position' => \yii\web\View::POS_HEAD]) ;
$this->registerCssFile($baseUrl . '/assets/global/plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.css',['position' => \yii\web\View::POS_HEAD]) ;
$this->registerCssFile($baseUrl . '/assets/global/plugins/bootstrap-markdown/css/bootstrap-markdown.min.css',['position' => \yii\web\View::POS_HEAD]) ;
$this->registerCssFile($baseUrl . '/assets/global/css/components-md.min.css',['position' => \yii\web\View::POS_HEAD]) ;
$this->registerCssFile($baseUrl . '/assets/global/css/plugins-md.min.css',['position' => \yii\web\View::POS_HEAD]) ;
$this->registerJsFile($baseUrl . '/assets/global/plugins/jquery-validation/js/jquery.validate.min.js', ['position' => \yii\web\View::POS_END]);
$this->registerJsFile($baseUrl . '/assets/global/plugins/jquery-validation/js/additional-methods.min.js', ['position' => \yii\web\View::POS_END]);
$this->registerJsFile($baseUrl . '/assets/global/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js', ['position' => \yii\web\View::POS_END]);
$this->registerJsFile($baseUrl . '/assets/global/plugins/bootstrap-wysihtml5/wysihtml5-0.3.0.js', ['position' => \yii\web\View::POS_END]);
$this->registerJsFile($baseUrl . '/assets/global/plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.js', ['position' => \yii\web\View::POS_END]);
$this->registerJsFile($baseUrl . '/assets/global/plugins/ckeditor/ckeditor.js', ['position' => \yii\web\View::POS_END]);
$this->registerJsFile($baseUrl . '/assets/global/plugins/bootstrap-markdown/lib/markdown.js', ['position' => \yii\web\View::POS_END]);
$this->registerJsFile($baseUrl . '/assets/global/plugins/bootstrap-markdown/js/bootstrap-markdown.js"', ['position' => \yii\web\View::POS_END]);
$this->registerJsFile($baseUrl . '/assets/pages/scripts/form-validation.min.js', ['position' => \yii\web\View::POS_END]);
$this->registerJsFile($baseUrl . '/assets/global/plugins/select2/js/select2.full.min.js', ['position' => \yii\web\View::POS_END]);
$this->registerJsFile($baseUrl . '/assets/pages/scripts/components-select2.min.js', ['position' => \yii\web\View::POS_END]);
?>
<?php echo UiMessage::widget(); ?>
<div class="row">
<div class="col-md-12">
<!-- BEGIN PORTLET-->
<div class="portlet box blue">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i>บันทึกบ่อเลี้ยงกุ้ง </div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<?php echo Html::beginForm('', 'post', array('class' => 'form-horizontal form-bordered')) ?>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">ชื่อบ่อ<span class="required">*</span></label>
<div class="col-md-9">
<?= Html::activeInput('text', $model, 'name', ['class' => 'form-control', 'placeholder' => 'กรุณาระบุ ชื่อบ่อ'])?>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">ขนาดบ่อ<span class="required">*</span></label>
<div class="col-md-9">
<?= Html::activeInput('text', $model, 'size', ['class' => 'form-control', 'placeholder' => 'กรุณาระบุ ขนาดของบ่อ'])?>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">ผู้ดูแลบ่อ</label>
<div class="col-md-9">
<?php echo Html::dropDownList('user[]',unserialize($model->keeper),$arrUser , ['id'=>'type','class' => 'form-control select2-multiple','multiple'=>''])?>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3"></label>
<div class="col-md-9">
<?php
if ($model->id) {
echo Html::hiddenInput('id', $model->id);
}
?>
<button type="submit" class="btn btn-primary">บันทึก</button>
<a href="<?php echo Url::toRoute('pond/typelist') ?>" class="btn" >ยกเลิก </a>
</div>
</div>
</div>
<?php echo Html::endForm() ?>
<!-- END FORM-->
</div>
</div>
<!-- END PORTLET-->
</div>
</div>
| bsd-3-clause |
alkaest2002/gzts-lab | modules/paypal/views/default/_paypalForm.php | 3241 | <?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div id="paypalForm">
<?php $form = ActiveForm::begin(
[
'id' => 'paypal-form',
'enableAjaxValidation' => false,
'enableClientValidation' => false,
'successCssClass' => '',
'fieldConfig' => ['template' => "{label}\n{input}\n{hint}\n<small>{error}</small>",],
'options' => ['autocomplete' => 'off']
]
); ?>
<?= $form->field($model, 'credits')->textInput(
[
'id' =>'paypal-credits',
'placeholder' => Yii::t('general', 'amount')
]
)->label(false); ?>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th><?= Yii::t('paypal','Description') ?></th>
<th class="text-center"><?= Yii::t('paypal','Qty') ?></th>
<th class="text-center"><?= Yii::t('paypal','Price') ?></th>
<th class="text-center"><?= Yii::t('paypal','Amount') ?></th>
</tr>
</thead>
<tbody id="paypal-table-body">
<tr>
<td><?= Yii::t('paypal','Credits') ?></td>
<td id="paypal-qty" class="text-center">0</td>
<td id="paypal-price" class="text-center"><?= Yii::$app->formatter->asCurrency($model->price) ?></td>
<td id="paypal-net" class="text-center">0,00</td>
</tr>
<tr>
<td><?= Yii::t('paypal','Vat') ?></td>
<td id="paypal-vat" data-value="<?= $model->vatCR ?>" class="text-center"><?= $model->vatHR ?></td>
<td class="text-center">-</td>
<td id="paypal-tax" class="text-center">0,00</td>
</tr>
<tr>
<td colspan="3"><?= Yii::t('paypal','Total amount') ?> <small><em>(<?= $model->cur ?>)</em></small></td>
<td id="paypal-total" class="text-center">0,00</td>
</tr>
</tbody>
</table>
<?= $form->field($model, 'amount')->hiddenInput(['id' =>'paypal-amount',])->label(false); ?>
<?= $form->field($model, 'token' )->hiddenInput(['id' =>'paypal-token',])->label(false); ?>
<?= $form->field($model, 'nonce' )->hiddenInput(['id' =>'paypal-nonce',])->label(false); ?>
<div class="form-group">
<?= Html::submitButton('<i class="fa fa-paypal"></i><i class="fa fa-cog fa-spin hidden"></i>' .Yii::t('site','submit'),
['id' => 'goPaypal', 'class' => 'btn btn-primary btn-block', 'disabled' => 'disabled']) ?>
</div>
<small><b>Attenzione!</b> Non rigenerare la pagina, dopo aver cliccato il pulsante. Attendi il completamento della procedura di acquisto tramite Paypal.</small>
<?php ActiveForm::end(); ?>
</div> | bsd-3-clause |
lebeddima/bookimed | backend/views/store/price/update.php | 88 | <?php
/**
* Created by PhpStorm.
* User: dimalebed
* Date: 7/18/16
* Time: 17:05
*/ | bsd-3-clause |
kusubooru/shimmie | shimmiedb/auth_test.go | 1449 | package shimmiedb_test
import (
"reflect"
"testing"
"github.com/kusubooru/shimmie"
)
func TestVerify(t *testing.T) {
shim, schema := setup(t)
defer teardown(t, shim, schema)
username := "john"
password := "1234"
u := &shimmie.User{
Name: username,
Pass: password,
Email: "john@doe.com",
}
// Create a user.
err := shim.CreateUser(u)
if err != nil {
t.Fatalf("CreateUser(%q) returned err: %v", u, err)
}
// Verify success case.
got, err := shim.Verify(username, password)
if err != nil {
t.Fatalf("Verify(%q, %q) returned err: %v", username, password, err)
}
if want := u; !reflect.DeepEqual(got, want) {
t.Errorf("Verify(%q, %q) -> user =\n%#v, want\n%#v", username, password, got, want)
}
// Verify wrong password case.
password = "wrongpassword"
_, err = shim.Verify(username, password)
if err == nil {
t.Fatalf("Verify(%q, %q) expected to return err", username, password)
}
if got, want := err, shimmie.ErrWrongCredentials; got != want {
t.Errorf("Verify(%q, %q) -> err =\n%#v, want\n%#v", username, password, got, want)
}
// Verify user not found case.
username = "nonexistentuser"
password = "wrongpassword"
_, err = shim.Verify(username, password)
if err == nil {
t.Fatalf("Verify(%q, %q) expected to return err", username, password)
}
if got, want := err, shimmie.ErrNotFound; got != want {
t.Errorf("Verify(%q, %q) -> err =\n%#v, want\n%#v", username, password, got, want)
}
}
| bsd-3-clause |
vanadium/go.jiri | cmd/jiri/cl_test.go | 42845 | // Copyright 2015 The Vanadium 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 main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"v.io/jiri"
"v.io/jiri/gerrit"
"v.io/jiri/gitutil"
"v.io/jiri/jiritest"
"v.io/jiri/project"
"v.io/jiri/runutil"
)
// assertCommitCount asserts that the commit count between two
// branches matches the expectedCount.
func assertCommitCount(t *testing.T, jirix *jiri.X, branch, baseBranch string, expectedCount int) {
got, err := gitutil.New(jirix.NewSeq()).CountCommits(branch, baseBranch)
if err != nil {
t.Fatalf("%v", err)
}
if want := 1; got != want {
t.Fatalf("unexpected number of commits: got %v, want %v", got, want)
}
}
// assertFileContent asserts that the content of the given file
// matches the expected content.
func assertFileContent(t *testing.T, jirix *jiri.X, file, want string) {
got, err := jirix.NewSeq().ReadFile(file)
if err != nil {
t.Fatalf("%v\n", err)
}
if string(got) != want {
t.Fatalf("unexpected content of file %v: got %v, want %v", file, got, want)
}
}
// assertFilesExist asserts that the files exist.
func assertFilesExist(t *testing.T, jirix *jiri.X, files []string) {
s := jirix.NewSeq()
for _, file := range files {
if _, err := s.Stat(file); err != nil {
if runutil.IsNotExist(err) {
t.Fatalf("expected file %v to exist but it did not", file)
}
t.Fatalf("%v", err)
}
}
}
// assertFilesDoNotExist asserts that the files do not exist.
func assertFilesDoNotExist(t *testing.T, jirix *jiri.X, files []string) {
s := jirix.NewSeq()
for _, file := range files {
if _, err := s.Stat(file); err != nil && !runutil.IsNotExist(err) {
t.Fatalf("%v", err)
} else if err == nil {
t.Fatalf("expected file %v to not exist but it did", file)
}
}
}
// assertFilesCommitted asserts that the files exist and are committed
// in the current branch.
func assertFilesCommitted(t *testing.T, jirix *jiri.X, files []string) {
assertFilesExist(t, jirix, files)
for _, file := range files {
if !gitutil.New(jirix.NewSeq()).IsFileCommitted(file) {
t.Fatalf("expected file %v to be committed but it is not", file)
}
}
}
// assertFilesNotCommitted asserts that the files exist and are *not*
// committed in the current branch.
func assertFilesNotCommitted(t *testing.T, jirix *jiri.X, files []string) {
assertFilesExist(t, jirix, files)
for _, file := range files {
if gitutil.New(jirix.NewSeq()).IsFileCommitted(file) {
t.Fatalf("expected file %v not to be committed but it is", file)
}
}
}
// assertFilesPushedToRef asserts that the given files have been
// pushed to the given remote repository reference.
func assertFilesPushedToRef(t *testing.T, jirix *jiri.X, repoPath, gerritPath, pushedRef string, files []string) {
chdir(t, jirix, gerritPath)
assertCommitCount(t, jirix, pushedRef, "master", 1)
if err := gitutil.New(jirix.NewSeq()).CheckoutBranch(pushedRef); err != nil {
t.Fatalf("%v", err)
}
assertFilesCommitted(t, jirix, files)
chdir(t, jirix, repoPath)
}
// assertStashSize asserts that the stash size matches the expected
// size.
func assertStashSize(t *testing.T, jirix *jiri.X, want int) {
got, err := gitutil.New(jirix.NewSeq()).StashSize()
if err != nil {
t.Fatalf("%v", err)
}
if got != want {
t.Fatalf("unxpected stash size: got %v, want %v", got, want)
}
}
// commitFile commits a file with the specified content into a branch
func commitFile(t *testing.T, jirix *jiri.X, filename string, content string) {
s := jirix.NewSeq()
if err := s.WriteFile(filename, []byte(content), 0644).Done(); err != nil {
t.Fatalf("%v", err)
}
commitMessage := "Commit " + filename
if err := gitutil.New(jirix.NewSeq()).CommitFile(filename, commitMessage); err != nil {
t.Fatalf("%v", err)
}
}
// commitFiles commits the given files into to current branch.
func commitFiles(t *testing.T, jirix *jiri.X, filenames []string) {
// Create and commit the files one at a time.
for _, filename := range filenames {
content := "This is file " + filename
commitFile(t, jirix, filename, content)
}
}
// createRepo creates a new repository with the given prefix.
func createRepo(t *testing.T, jirix *jiri.X, prefix string) string {
s := jirix.NewSeq()
repoPath, err := s.TempDir(jirix.Root, "repo-"+prefix)
if err != nil {
t.Fatalf("TempDir() failed: %v", err)
}
if err := os.Chmod(repoPath, 0777); err != nil {
t.Fatalf("Chmod(%v) failed: %v", repoPath, err)
}
if err := gitutil.New(jirix.NewSeq()).Init(repoPath); err != nil {
t.Fatalf("%v", err)
}
if err := s.MkdirAll(filepath.Join(repoPath, jiri.ProjectMetaDir), os.FileMode(0755)).Done(); err != nil {
t.Fatalf("%v", err)
}
return repoPath
}
// Simple commit-msg hook that removes any existing Change-Id and adds a
// fake one.
var commitMsgHook string = `#!/bin/sh
MSG="$1"
cat $MSG | sed -e "/Change-Id/d" > $MSG.tmp
echo "Change-Id: I0000000000000000000000000000000000000000" >> $MSG.tmp
mv $MSG.tmp $MSG
`
// installCommitMsgHook links the gerrit commit-msg hook into a different repo.
func installCommitMsgHook(t *testing.T, jirix *jiri.X, repoPath string) {
hookLocation := path.Join(repoPath, ".git/hooks/commit-msg")
if err := jirix.NewSeq().WriteFile(hookLocation, []byte(commitMsgHook), 0755).Done(); err != nil {
t.Fatalf("WriteFile(%v) failed: %v", hookLocation, err)
}
}
// chdir changes the runtime working directory and traps any errors.
func chdir(t *testing.T, jirix *jiri.X, path string) {
if err := jirix.NewSeq().Chdir(path).Done(); err != nil {
_, file, line, _ := runtime.Caller(1)
t.Fatalf("%s: %d: Chdir(%v) failed: %v", file, line, path, err)
}
}
// createRepoFromOrigin creates a Git repo tracking origin/master.
func createRepoFromOrigin(t *testing.T, jirix *jiri.X, subpath string, originPath string) string {
repoPath := createRepo(t, jirix, subpath)
chdir(t, jirix, repoPath)
if err := gitutil.New(jirix.NewSeq()).AddRemote("origin", originPath); err != nil {
t.Fatalf("%v", err)
}
if err := gitutil.New(jirix.NewSeq()).Pull("origin", "master"); err != nil {
t.Fatalf("%v", err)
}
return repoPath
}
// createTestRepos sets up three local repositories: origin, gerrit,
// and the main test repository which pulls from origin and can push
// to gerrit.
func createTestRepos(t *testing.T, jirix *jiri.X) (string, string, string) {
// Create origin.
originPath := createRepo(t, jirix, "origin")
chdir(t, jirix, originPath)
if err := gitutil.New(jirix.NewSeq()).CommitWithMessage("initial commit"); err != nil {
t.Fatalf("%v", err)
}
// Create test repo.
repoPath := createRepoFromOrigin(t, jirix, "test", originPath)
// Add Gerrit remote.
gerritPath := createRepoFromOrigin(t, jirix, "gerrit", originPath)
// Switch back to test repo.
chdir(t, jirix, repoPath)
return repoPath, originPath, gerritPath
}
// submit mocks a Gerrit review submit by pushing the Gerrit remote to origin.
// Actually origin pulls from Gerrit since origin isn't actually a bare git repo.
// Some of our tests actually rely on accessing .git in origin, so it must be non-bare.
func submit(t *testing.T, jirix *jiri.X, originPath string, gerritPath string, review *review) {
cwd, err := os.Getwd()
if err != nil {
t.Fatalf("Getwd() failed: %v", err)
}
chdir(t, jirix, originPath)
expectedRef := gerrit.Reference(review.CLOpts)
if err := gitutil.New(jirix.NewSeq()).Pull(gerritPath, expectedRef); err != nil {
t.Fatalf("Pull gerrit to origin failed: %v", err)
}
chdir(t, jirix, cwd)
}
// setupTest creates a setup for testing the review tool.
func setupTest(t *testing.T, installHook bool) (fake *jiritest.FakeJiriRoot, repoPath, originPath, gerritPath string, cleanup func()) {
oldWD, err := os.Getwd()
if err != nil {
t.Fatalf("Getwd() failed: %v", err)
}
var cleanupFake func()
if fake, cleanupFake = jiritest.NewFakeJiriRoot(t); err != nil {
t.Fatalf("%v", err)
}
repoPath, originPath, gerritPath = createTestRepos(t, fake.X)
if installHook == true {
for _, path := range []string{repoPath, originPath, gerritPath} {
installCommitMsgHook(t, fake.X, path)
}
}
chdir(t, fake.X, repoPath)
cleanup = func() {
chdir(t, fake.X, oldWD)
cleanupFake()
}
return
}
func createCLWithFiles(t *testing.T, jirix *jiri.X, branch string, files ...string) {
if err := newCL(jirix, []string{branch}); err != nil {
t.Fatalf("%v", err)
}
commitFiles(t, jirix, files)
}
// TestCleanupClean checks that cleanup succeeds if the branch to be
// cleaned up has been merged with the master.
func TestCleanupClean(t *testing.T) {
fake, repoPath, originPath, _, cleanup := setupTest(t, true)
defer cleanup()
branch := "my-branch"
if err := gitutil.New(fake.X.NewSeq()).CreateAndCheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
commitFiles(t, fake.X, []string{"file1", "file2"})
if err := gitutil.New(fake.X.NewSeq()).CheckoutBranch("master"); err != nil {
t.Fatalf("%v", err)
}
chdir(t, fake.X, originPath)
commitFiles(t, fake.X, []string{"file1", "file2"})
chdir(t, fake.X, repoPath)
if err := cleanupCL(fake.X, []string{branch}); err != nil {
t.Fatalf("cleanup() failed: %v", err)
}
if gitutil.New(fake.X.NewSeq()).BranchExists(branch) {
t.Fatalf("cleanup failed to remove the feature branch")
}
}
// TestCleanupDirty checks that cleanup is a no-op if the branch to be
// cleaned up has unmerged changes.
func TestCleanupDirty(t *testing.T) {
fake, _, _, _, cleanup := setupTest(t, true)
defer cleanup()
branch := "my-branch"
if err := gitutil.New(fake.X.NewSeq()).CreateAndCheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
files := []string{"file1", "file2"}
commitFiles(t, fake.X, files)
if err := gitutil.New(fake.X.NewSeq()).CheckoutBranch("master"); err != nil {
t.Fatalf("%v", err)
}
if err := cleanupCL(fake.X, []string{branch}); err == nil {
t.Fatalf("cleanup did not fail when it should")
}
if err := gitutil.New(fake.X.NewSeq()).CheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
assertFilesCommitted(t, fake.X, files)
}
// TestCreateReviewBranch checks that the temporary review branch is
// created correctly.
func TestCreateReviewBranch(t *testing.T) {
fake, _, _, _, cleanup := setupTest(t, true)
defer cleanup()
branch := "my-branch"
if err := gitutil.New(fake.X.NewSeq()).CreateAndCheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
files := []string{"file1", "file2", "file3"}
commitFiles(t, fake.X, files)
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{})
if err != nil {
t.Fatalf("%v", err)
}
if expected, got := branch+"-REVIEW", review.reviewBranch; expected != got {
t.Fatalf("Unexpected review branch name: expected %v, got %v", expected, got)
}
commitMessage := "squashed commit"
if err := review.createReviewBranch(commitMessage); err != nil {
t.Fatalf("%v", err)
}
// Verify that the branch exists.
if !gitutil.New(fake.X.NewSeq()).BranchExists(review.reviewBranch) {
t.Fatalf("review branch not found")
}
if err := gitutil.New(fake.X.NewSeq()).CheckoutBranch(review.reviewBranch); err != nil {
t.Fatalf("%v", err)
}
assertCommitCount(t, fake.X, review.reviewBranch, "master", 1)
assertFilesCommitted(t, fake.X, files)
}
// TestCreateReviewBranchWithEmptyChange checks that running
// createReviewBranch() on a branch with no changes will result in an
// EmptyChangeError.
func TestCreateReviewBranchWithEmptyChange(t *testing.T) {
fake, _, _, _, cleanup := setupTest(t, true)
defer cleanup()
branch := "my-branch"
if err := gitutil.New(fake.X.NewSeq()).CreateAndCheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{Remote: branch})
if err != nil {
t.Fatalf("%v", err)
}
commitMessage := "squashed commit"
err = review.createReviewBranch(commitMessage)
if err == nil {
t.Fatalf("creating a review did not fail when it should")
}
if _, ok := err.(emptyChangeError); !ok {
t.Fatalf("unexpected error type: %v", err)
}
}
// TestSendReview checks the various options for sending a review.
func TestSendReview(t *testing.T) {
fake, repoPath, _, gerritPath, cleanup := setupTest(t, true)
defer cleanup()
branch := "my-branch"
if err := gitutil.New(fake.X.NewSeq()).CreateAndCheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
files := []string{"file1"}
commitFiles(t, fake.X, files)
{
// Test with draft = false, no reviewiers, and no ccs.
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{Remote: gerritPath})
if err != nil {
t.Fatalf("%v", err)
}
if err := review.send(); err != nil {
t.Fatalf("failed to send a review: %v", err)
}
expectedRef := gerrit.Reference(review.CLOpts)
assertFilesPushedToRef(t, fake.X, repoPath, gerritPath, expectedRef, files)
}
{
// Test with draft = true, no reviewers, and no ccs.
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{
Draft: true,
Remote: gerritPath,
})
if err != nil {
t.Fatalf("%v", err)
}
if err := review.send(); err != nil {
t.Fatalf("failed to send a review: %v", err)
}
expectedRef := gerrit.Reference(review.CLOpts)
assertFilesPushedToRef(t, fake.X, repoPath, gerritPath, expectedRef, files)
}
{
// Test with draft = false, reviewers, and no ccs.
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{
Remote: gerritPath,
Reviewers: parseEmails("reviewer1,reviewer2@example.org"),
})
if err != nil {
t.Fatalf("%v", err)
}
if err := review.send(); err != nil {
t.Fatalf("failed to send a review: %v", err)
}
expectedRef := gerrit.Reference(review.CLOpts)
assertFilesPushedToRef(t, fake.X, repoPath, gerritPath, expectedRef, files)
}
{
// Test with draft = true, reviewers, and ccs.
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{
Ccs: parseEmails("cc1@example.org,cc2"),
Draft: true,
Remote: gerritPath,
Reviewers: parseEmails("reviewer3@example.org,reviewer4"),
})
if err != nil {
t.Fatalf("%v", err)
}
if err := review.send(); err != nil {
t.Fatalf("failed to send a review: %v", err)
}
expectedRef := gerrit.Reference(review.CLOpts)
assertFilesPushedToRef(t, fake.X, repoPath, gerritPath, expectedRef, files)
}
}
// TestSendReviewNoChangeID checks that review.send() correctly errors when
// not run with a commit hook that adds a Change-Id.
func TestSendReviewNoChangeID(t *testing.T) {
// Pass 'false' to setup so it doesn't install the commit-msg hook.
fake, _, _, gerritPath, cleanup := setupTest(t, false)
defer cleanup()
branch := "my-branch"
if err := gitutil.New(fake.X.NewSeq()).CreateAndCheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
commitFiles(t, fake.X, []string{"file1"})
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{Remote: gerritPath})
if err != nil {
t.Fatalf("%v", err)
}
err = review.send()
if err == nil {
t.Fatalf("sending a review did not fail when it should")
}
if _, ok := err.(noChangeIDError); !ok {
t.Fatalf("unexpected error type: %v", err)
}
}
// TestEndToEnd checks the end-to-end functionality of the review tool.
func TestEndToEnd(t *testing.T) {
fake, repoPath, _, gerritPath, cleanup := setupTest(t, true)
defer cleanup()
branch := "my-branch"
if err := gitutil.New(fake.X.NewSeq()).CreateAndCheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
files := []string{"file1", "file2", "file3"}
commitFiles(t, fake.X, files)
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{Remote: gerritPath})
if err != nil {
t.Fatalf("%v", err)
}
setTopicFlag = false
if err := review.run(); err != nil {
t.Fatalf("run() failed: %v", err)
}
expectedRef := gerrit.Reference(review.CLOpts)
assertFilesPushedToRef(t, fake.X, repoPath, gerritPath, expectedRef, files)
}
// TestLabelsInCommitMessage checks the labels are correctly processed
// for the commit message.
//
// HACK ALERT: This test runs the review.run() function multiple
// times. The function ends up pushing a commit to a fake "gerrit"
// repository created by the setupTest() function. For the real gerrit
// repository, it is possible to push to the refs/for/change reference
// multiple times, because it is a special reference that "maps"
// incoming commits to CL branches based on the commit message
// Change-Id. The fake "gerrit" repository does not implement this
// logic and thus the same reference cannot be pushed to multiple
// times. To overcome this obstacle, the test takes advantage of the
// fact that the reference name is a function of the reviewers and
// uses different reviewers for different review runs.
func TestLabelsInCommitMessage(t *testing.T) {
fake, repoPath, _, gerritPath, cleanup := setupTest(t, true)
defer cleanup()
s := fake.X.NewSeq()
branch := "my-branch"
if err := gitutil.New(fake.X.NewSeq()).CreateAndCheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
// Test setting -presubmit=none and autosubmit.
files := []string{"file1", "file2", "file3"}
commitFiles(t, fake.X, files)
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{
Autosubmit: true,
Presubmit: gerrit.PresubmitTestTypeNone,
Remote: gerritPath,
Reviewers: parseEmails("run1"),
})
if err != nil {
t.Fatalf("%v", err)
}
setTopicFlag = false
if err := review.run(); err != nil {
t.Fatalf("%v", err)
}
expectedRef := gerrit.Reference(review.CLOpts)
assertFilesPushedToRef(t, fake.X, repoPath, gerritPath, expectedRef, files)
// The last three lines of the gerrit commit message file should be:
// AutoSubmit
// PresubmitTest: none
// Change-Id: ...
file, err := getCommitMessageFileName(review.jirix, review.CLOpts.Branch)
if err != nil {
t.Fatalf("%v", err)
}
bytes, err := s.ReadFile(file)
if err != nil {
t.Fatalf("%v\n", err)
}
content := string(bytes)
lines := strings.Split(content, "\n")
// Make sure the Change-Id line is the last line.
if got := lines[len(lines)-1]; !strings.HasPrefix(got, "Change-Id") {
t.Fatalf("no Change-Id line found: %s", got)
}
// Make sure the "AutoSubmit" label exists.
if autosubmitLabelRE.FindString(content) == "" {
t.Fatalf("AutoSubmit label doesn't exist in the commit message: %s", content)
}
// Make sure the "PresubmitTest" label exists.
if presubmitTestLabelRE.FindString(content) == "" {
t.Fatalf("PresubmitTest label doesn't exist in the commit message: %s", content)
}
// Test setting -presubmit=all but keep autosubmit=true.
review, err = newReview(fake.X, project.Project{}, gerrit.CLOpts{
Autosubmit: true,
Remote: gerritPath,
Reviewers: parseEmails("run2"),
})
if err != nil {
t.Fatalf("%v", err)
}
if err := review.run(); err != nil {
t.Fatalf("%v", err)
}
expectedRef = gerrit.Reference(review.CLOpts)
assertFilesPushedToRef(t, fake.X, repoPath, gerritPath, expectedRef, files)
bytes, err = s.ReadFile(file)
if err != nil {
t.Fatalf("%v\n", err)
}
content = string(bytes)
// Make sure there is no PresubmitTest=none any more.
match := presubmitTestLabelRE.FindString(content)
if match != "" {
t.Fatalf("want no presubmit label line, got: %s", match)
}
// Make sure the "AutoSubmit" label still exists.
if autosubmitLabelRE.FindString(content) == "" {
t.Fatalf("AutoSubmit label doesn't exist in the commit message: %s", content)
}
// Test setting autosubmit=false.
review, err = newReview(fake.X, project.Project{}, gerrit.CLOpts{
Remote: gerritPath,
Reviewers: parseEmails("run3"),
})
if err != nil {
t.Fatalf("%v", err)
}
if err := review.run(); err != nil {
t.Fatalf("%v", err)
}
expectedRef = gerrit.Reference(review.CLOpts)
assertFilesPushedToRef(t, fake.X, repoPath, gerritPath, expectedRef, files)
bytes, err = s.ReadFile(file)
if err != nil {
t.Fatalf("%v\n", err)
}
content = string(bytes)
// Make sure there is no AutoSubmit label any more.
match = autosubmitLabelRE.FindString(content)
if match != "" {
t.Fatalf("want no AutoSubmit label line, got: %s", match)
}
}
// TestDirtyBranch checks that the tool correctly handles unstaged and
// untracked changes in a working branch with stashed changes.
func TestDirtyBranch(t *testing.T) {
fake, _, _, gerritPath, cleanup := setupTest(t, true)
defer cleanup()
s := fake.X.NewSeq()
branch := "my-branch"
if err := gitutil.New(fake.X.NewSeq()).CreateAndCheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
files := []string{"file1", "file2"}
commitFiles(t, fake.X, files)
assertStashSize(t, fake.X, 0)
stashedFile, stashedFileContent := "stashed-file", "stashed-file content"
if err := s.WriteFile(stashedFile, []byte(stashedFileContent), 0644).Done(); err != nil {
t.Fatalf("WriteFile(%v, %v) failed: %v", stashedFile, stashedFileContent, err)
}
if err := gitutil.New(fake.X.NewSeq()).Add(stashedFile); err != nil {
t.Fatalf("%v", err)
}
if _, err := gitutil.New(fake.X.NewSeq()).Stash(); err != nil {
t.Fatalf("%v", err)
}
assertStashSize(t, fake.X, 1)
modifiedFile, modifiedFileContent := "file1", "modified-file content"
if err := s.WriteFile(modifiedFile, []byte(modifiedFileContent), 0644).Done(); err != nil {
t.Fatalf("WriteFile(%v, %v) failed: %v", modifiedFile, modifiedFileContent, err)
}
stagedFile, stagedFileContent := "file2", "staged-file content"
if err := s.WriteFile(stagedFile, []byte(stagedFileContent), 0644).Done(); err != nil {
t.Fatalf("WriteFile(%v, %v) failed: %v", stagedFile, stagedFileContent, err)
}
if err := gitutil.New(fake.X.NewSeq()).Add(stagedFile); err != nil {
t.Fatalf("%v", err)
}
untrackedFile, untrackedFileContent := "file3", "untracked-file content"
if err := s.WriteFile(untrackedFile, []byte(untrackedFileContent), 0644).Done(); err != nil {
t.Fatalf("WriteFile(%v, %v) failed: %v", untrackedFile, untrackedFileContent, err)
}
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{Remote: gerritPath})
if err != nil {
t.Fatalf("%v", err)
}
setTopicFlag = false
if err := review.run(); err == nil {
t.Fatalf("run() didn't fail when it should")
}
assertFilesNotCommitted(t, fake.X, []string{stagedFile})
assertFilesNotCommitted(t, fake.X, []string{untrackedFile})
assertFileContent(t, fake.X, modifiedFile, modifiedFileContent)
assertFileContent(t, fake.X, stagedFile, stagedFileContent)
assertFileContent(t, fake.X, untrackedFile, untrackedFileContent)
// As of git 2.4.3 "git stash pop" fails if there are uncommitted
// changes in the index. So we need to commit them first.
if err := gitutil.New(fake.X.NewSeq()).Commit(); err != nil {
t.Fatalf("%v", err)
}
assertStashSize(t, fake.X, 1)
if err := gitutil.New(fake.X.NewSeq()).StashPop(); err != nil {
t.Fatalf("%v", err)
}
assertStashSize(t, fake.X, 0)
assertFilesNotCommitted(t, fake.X, []string{stashedFile})
assertFileContent(t, fake.X, stashedFile, stashedFileContent)
}
// TestRunInSubdirectory checks that the command will succeed when run from
// within a subdirectory of a branch that does not exist on master branch, and
// will return the user to the subdirectory after completion.
func TestRunInSubdirectory(t *testing.T) {
fake, repoPath, _, gerritPath, cleanup := setupTest(t, true)
defer cleanup()
s := fake.X.NewSeq()
branch := "my-branch"
if err := gitutil.New(fake.X.NewSeq()).CreateAndCheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
subdir := "sub/directory"
subdirPerms := os.FileMode(0744)
if err := s.MkdirAll(subdir, subdirPerms).Done(); err != nil {
t.Fatalf("MkdirAll(%v, %v) failed: %v", subdir, subdirPerms, err)
}
files := []string{path.Join(subdir, "file1")}
commitFiles(t, fake.X, files)
chdir(t, fake.X, subdir)
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{Remote: gerritPath})
if err != nil {
t.Fatalf("%v", err)
}
setTopicFlag = false
if err := review.run(); err != nil {
t.Fatalf("run() failed: %v", err)
}
path := path.Join(repoPath, subdir)
want, err := filepath.EvalSymlinks(path)
if err != nil {
t.Fatalf("EvalSymlinks(%v) failed: %v", path, err)
}
cwd, err := os.Getwd()
if err != nil {
t.Fatalf("%v", err)
}
got, err := filepath.EvalSymlinks(cwd)
if err != nil {
t.Fatalf("EvalSymlinks(%v) failed: %v", cwd, err)
}
if got != want {
t.Fatalf("unexpected working directory: got %v, want %v", got, want)
}
expectedRef := gerrit.Reference(review.CLOpts)
assertFilesPushedToRef(t, fake.X, repoPath, gerritPath, expectedRef, files)
}
// TestProcessLabels checks that the processLabels function works as expected.
func TestProcessLabels(t *testing.T) {
fake, _, _, _, cleanup := setupTest(t, true)
defer cleanup()
testCases := []struct {
autosubmit bool
presubmitType gerrit.PresubmitTestType
originalMessage string
expectedMessage string
}{
{
presubmitType: gerrit.PresubmitTestTypeNone,
originalMessage: "",
expectedMessage: "PresubmitTest: none\n",
},
{
autosubmit: true,
presubmitType: gerrit.PresubmitTestTypeNone,
originalMessage: "",
expectedMessage: "AutoSubmit\nPresubmitTest: none\n",
},
{
presubmitType: gerrit.PresubmitTestTypeNone,
originalMessage: "review message\n",
expectedMessage: "review message\nPresubmitTest: none\n",
},
{
autosubmit: true,
presubmitType: gerrit.PresubmitTestTypeNone,
originalMessage: "review message\n",
expectedMessage: "review message\nAutoSubmit\nPresubmitTest: none\n",
},
{
presubmitType: gerrit.PresubmitTestTypeNone,
originalMessage: `review message
Change-Id: I0000000000000000000000000000000000000000`,
expectedMessage: `review message
PresubmitTest: none
Change-Id: I0000000000000000000000000000000000000000`,
},
{
autosubmit: true,
presubmitType: gerrit.PresubmitTestTypeNone,
originalMessage: `review message
Change-Id: I0000000000000000000000000000000000000000`,
expectedMessage: `review message
AutoSubmit
PresubmitTest: none
Change-Id: I0000000000000000000000000000000000000000`,
},
{
presubmitType: gerrit.PresubmitTestTypeAll,
originalMessage: "",
expectedMessage: "",
},
{
presubmitType: gerrit.PresubmitTestTypeAll,
originalMessage: "review message\n",
expectedMessage: "review message\n",
},
{
presubmitType: gerrit.PresubmitTestTypeAll,
originalMessage: `review message
Change-Id: I0000000000000000000000000000000000000000`,
expectedMessage: `review message
Change-Id: I0000000000000000000000000000000000000000`,
},
}
for _, test := range testCases {
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{
Autosubmit: test.autosubmit,
Presubmit: test.presubmitType,
})
if err != nil {
t.Fatalf("%v", err)
}
if got := review.processLabelsAndCommitFile(test.originalMessage); got != test.expectedMessage {
t.Fatalf("want %s, got %s", test.expectedMessage, got)
}
}
}
// TestCLNew checks the operation of the "jiri cl new" command.
func TestCLNew(t *testing.T) {
fake, _, _, _, cleanup := setupTest(t, true)
defer cleanup()
// Create some dependent CLs.
if err := newCL(fake.X, []string{"feature1"}); err != nil {
t.Fatalf("%v", err)
}
if err := newCL(fake.X, []string{"feature2"}); err != nil {
t.Fatalf("%v", err)
}
// Check that their dependency paths have been recorded correctly.
testCases := []struct {
branch string
data []byte
}{
{
branch: "feature1",
data: []byte("master"),
},
{
branch: "feature2",
data: []byte("master\nfeature1"),
},
}
s := fake.X.NewSeq()
for _, testCase := range testCases {
file, err := getDependencyPathFileName(fake.X, testCase.branch)
if err != nil {
t.Fatalf("%v", err)
}
data, err := s.ReadFile(file)
if err != nil {
t.Fatalf("%v", err)
}
if bytes.Compare(data, testCase.data) != 0 {
t.Fatalf("unexpected data:\ngot\n%v\nwant\n%v", string(data), string(testCase.data))
}
}
}
// TestDependentClsWithEditDelete exercises a previously observed failure case
// where if a CL edits a file and a dependent CL deletes it, jiri cl mail after
// the deletion failed with unrecoverable merge errors.
func TestDependentClsWithEditDelete(t *testing.T) {
fake, repoPath, originPath, gerritPath, cleanup := setupTest(t, true)
defer cleanup()
chdir(t, fake.X, originPath)
commitFiles(t, fake.X, []string{"A", "B"})
chdir(t, fake.X, repoPath)
if err := syncCL(fake.X); err != nil {
t.Fatalf("%v", err)
}
assertFilesExist(t, fake.X, []string{"A", "B"})
createCLWithFiles(t, fake.X, "editme", "C")
if err := fake.X.NewSeq().WriteFile("B", []byte("Will I dream?"), 0644).Done(); err != nil {
t.Fatalf("%v", err)
}
if err := gitutil.New(fake.X.NewSeq()).Add("B"); err != nil {
t.Fatalf("%v", err)
}
if err := gitutil.New(fake.X.NewSeq()).CommitWithMessage("editing stuff"); err != nil {
t.Fatalf("git commit failed: %v", err)
}
review, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{
Remote: gerritPath,
Reviewers: parseEmails("run1"), // See hack note about TestLabelsInCommitMessage
})
if err != nil {
t.Fatalf("%v", err)
}
setTopicFlag = false
if err := review.run(); err != nil {
t.Fatalf("run() failed: %v", err)
}
if err := newCL(fake.X, []string{"deleteme"}); err != nil {
t.Fatalf("%v", err)
}
if err := gitutil.New(fake.X.NewSeq()).Remove("B", "C"); err != nil {
t.Fatalf("git rm B C failed: %v", err)
}
if err := gitutil.New(fake.X.NewSeq()).CommitWithMessage("deleting stuff"); err != nil {
t.Fatalf("git commit failed: %v", err)
}
review, err = newReview(fake.X, project.Project{}, gerrit.CLOpts{
Remote: gerritPath,
Reviewers: parseEmails("run2"),
})
if err != nil {
t.Fatalf("%v", err)
}
if err := review.run(); err != nil {
t.Fatalf("run() failed: %v", err)
}
chdir(t, fake.X, gerritPath)
expectedRef := gerrit.Reference(review.CLOpts)
if err := gitutil.New(fake.X.NewSeq()).CheckoutBranch(expectedRef); err != nil {
t.Fatalf("%v", err)
}
assertFilesExist(t, fake.X, []string{"A"})
assertFilesDoNotExist(t, fake.X, []string{"B", "C"})
}
// TestParallelDev checks "jiri cl mail" behavior when parallel development has
// been submitted upstream.
func TestParallelDev(t *testing.T) {
fake, repoPath, originPath, gerritAPath, cleanup := setupTest(t, true)
defer cleanup()
gerritBPath := createRepoFromOrigin(t, fake.X, "gerritB", originPath)
chdir(t, fake.X, repoPath)
// Create parallel branches with:
// * non-conflicting changes in different files
// * conflicting changes in a file
createCLWithFiles(t, fake.X, "feature1-A", "A")
if err := gitutil.New(fake.X.NewSeq()).CheckoutBranch("master"); err != nil {
t.Fatalf("%v", err)
}
createCLWithFiles(t, fake.X, "feature1-B", "B")
commitFile(t, fake.X, "A", "Don't tread on me.")
reviewB, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{Remote: gerritBPath})
if err != nil {
t.Fatalf("%v", err)
}
setTopicFlag = false
if err := reviewB.run(); err != nil {
t.Fatalf("run() failed: %v", err)
}
// Submit B and verify A doesn't revert it.
submit(t, fake.X, originPath, gerritBPath, reviewB)
// Assert files pushed to origin.
chdir(t, fake.X, originPath)
assertFilesExist(t, fake.X, []string{"A", "B"})
chdir(t, fake.X, repoPath)
if err := gitutil.New(fake.X.NewSeq()).CheckoutBranch("feature1-A"); err != nil {
t.Fatalf("%v", err)
}
reviewA, err := newReview(fake.X, project.Project{}, gerrit.CLOpts{Remote: gerritAPath})
if err == nil {
t.Fatalf("creating a review did not fail when it should")
}
// Assert state restored after failed review.
assertFileContent(t, fake.X, "A", "This is file A")
assertFilesDoNotExist(t, fake.X, []string{"B"})
// Manual conflict resolution.
if err := gitutil.New(fake.X.NewSeq()).Merge("master", gitutil.ResetOnFailureOpt(false)); err == nil {
t.Fatalf("merge applied cleanly when it shouldn't")
}
assertFilesNotCommitted(t, fake.X, []string{"A", "B"})
assertFileContent(t, fake.X, "B", "This is file B")
if err := fake.X.NewSeq().WriteFile("A", []byte("This is file A. Don't tread on me."), 0644).Done(); err != nil {
t.Fatalf("%v", err)
}
if err := gitutil.New(fake.X.NewSeq()).Add("A"); err != nil {
t.Fatalf("%v", err)
}
if err := gitutil.New(fake.X.NewSeq()).Add("B"); err != nil {
t.Fatalf("%v", err)
}
if err := gitutil.New(fake.X.NewSeq()).CommitWithMessage("Conflict resolution"); err != nil {
t.Fatalf("%v", err)
}
// Retry review.
reviewA, err = newReview(fake.X, project.Project{}, gerrit.CLOpts{Remote: gerritAPath})
if err != nil {
t.Fatalf("review failed: %v", err)
}
if err := reviewA.run(); err != nil {
t.Fatalf("run() failed: %v", err)
}
chdir(t, fake.X, gerritAPath)
expectedRef := gerrit.Reference(reviewA.CLOpts)
if err := gitutil.New(fake.X.NewSeq()).CheckoutBranch(expectedRef); err != nil {
t.Fatalf("%v", err)
}
assertFilesExist(t, fake.X, []string{"B"})
}
// TestCLSync checks the operation of the "jiri cl sync" command.
func TestCLSync(t *testing.T) {
fake, _, _, _, cleanup := setupTest(t, true)
defer cleanup()
// Create some dependent CLs.
if err := newCL(fake.X, []string{"feature1"}); err != nil {
t.Fatalf("%v", err)
}
if err := newCL(fake.X, []string{"feature2"}); err != nil {
t.Fatalf("%v", err)
}
// Add the "test" file to the master.
if err := gitutil.New(fake.X.NewSeq()).CheckoutBranch("master"); err != nil {
t.Fatalf("%v", err)
}
commitFiles(t, fake.X, []string{"test"})
// Sync the dependent CLs.
if err := gitutil.New(fake.X.NewSeq()).CheckoutBranch("feature2"); err != nil {
t.Fatalf("%v", err)
}
if err := syncCL(fake.X); err != nil {
t.Fatalf("%v", err)
}
// Check that the "test" file exists in the dependent CLs.
for _, branch := range []string{"feature1", "feature2"} {
if err := gitutil.New(fake.X.NewSeq()).CheckoutBranch(branch); err != nil {
t.Fatalf("%v", err)
}
assertFilesExist(t, fake.X, []string{"test"})
}
}
func TestMultiPart(t *testing.T) {
fake, cleanup := jiritest.NewFakeJiriRoot(t)
defer cleanup()
projects := addProjects(t, fake)
origCleanupFlag, origCurrentProjectFlag := cleanupMultiPartFlag, currentProjectFlag
defer func() {
cleanupMultiPartFlag, currentProjectFlag = origCleanupFlag, origCurrentProjectFlag
}()
cleanupMultiPartFlag, currentProjectFlag = false, false
name, err := gitutil.New(fake.X.NewSeq()).CurrentBranchName()
if err != nil {
t.Fatal(err)
}
if name == "master" {
// The test cases below assume that they are run on a feature-branch,
// but this is not necessarily always the case when running under
// jenkins, so if it's run on a master branch it will create
// a feature branch.
if err := gitutil.New(fake.X.NewSeq()).CreateAndCheckoutBranch("feature-branch"); err != nil {
t.Fatal(err)
}
defer func() {
git := gitutil.New(fake.X.NewSeq())
git.CheckoutBranch("master", gitutil.ForceOpt(true))
git.DeleteBranch("feature-branch", gitutil.ForceOpt(true))
}()
}
cwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(cwd)
relchdir := func(dir string) {
chdir(t, fake.X, dir)
}
initMP := func() *multiPart {
mp, err := initForMultiPart(fake.X)
if err != nil {
_, file, line, _ := runtime.Caller(1)
t.Fatalf("%s:%d: %v", filepath.Base(file), line, err)
}
return mp
}
wr := func(mp *multiPart) *multiPart {
return mp
}
git := func(dir string) *gitutil.Git {
return gitutil.New(fake.X.NewSeq(), gitutil.RootDirOpt(dir))
}
cleanupMultiPartFlag = true
if got, want := initMP(), wr(&multiPart{clean: true}); !reflect.DeepEqual(got, want) {
t.Errorf("got %#v, want %#v", got, want)
}
currentProjectFlag = true
if got, want := initMP(), wr(&multiPart{clean: true, current: true}); !reflect.DeepEqual(got, want) {
t.Errorf("got %#v, want %#v", got, want)
}
cleanupMultiPartFlag, currentProjectFlag = false, false
// Test metadata generation.
ra := projects[0].Path
rb := projects[1].Path
rc := projects[2].Path
t1 := projects[3].Path
git(ra).CreateAndCheckoutBranch("a1")
relchdir(ra)
if got, want := initMP(), wr(&multiPart{current: true, currentKey: projects[0].Key(), currentBranch: "a1"}); !reflect.DeepEqual(got, want) {
t.Errorf("got %#v, want %#v", got, want)
}
git(rb).CreateAndCheckoutBranch("a1")
mp := initMP()
if mp.current != false || mp.clean != false {
t.Errorf("current or clean not false: %v, %v", mp.current, mp.clean)
}
if got, want := len(mp.keys), 2; got != want {
t.Errorf("got %v, want %v", got, want)
}
tmp := &multiPart{
keys: project.ProjectKeys{projects[0].Key(), projects[1].Key()},
}
for i, k := range mp.keys {
if got, want := k, tmp.keys[i]; got != want {
t.Errorf("got %v, want %v", got, want)
}
}
if got, want := len(mp.states), 2; got != want {
t.Errorf("got %v, want %v", got, want)
}
git(rc).CreateAndCheckoutBranch("a1")
git(t1).CreateAndCheckoutBranch("a2")
mp = initMP()
if got, want := len(mp.keys), 3; got != want {
t.Errorf("got %v, want %v", got, want)
}
if err := mp.writeMultiPartMetadata(fake.X); err != nil {
t.Fatal(err)
}
hasMetaData := func(total int, branch string, projectPaths ...string) {
_, file, line, _ := runtime.Caller(1)
loc := fmt.Sprintf("%s:%d", filepath.Base(file), line)
for i, dir := range projectPaths {
filename := filepath.Join(dir, jiri.ProjectMetaDir, branch, multiPartMetaDataFileName)
msg, err := ioutil.ReadFile(filename)
if err != nil {
t.Fatalf("%s: %v", loc, err)
}
if got, want := string(msg), fmt.Sprintf("MultiPart: %d/%d\n", i+1, total); got != want {
t.Errorf("%v: got %v, want %v", dir, got, want)
}
}
}
hasNoMetaData := func(branch string, projectPaths ...string) {
_, file, line, _ := runtime.Caller(1)
loc := fmt.Sprintf("%s:%d", filepath.Base(file), line)
for _, dir := range projectPaths {
filename := filepath.Join(fake.X.Root, dir, jiri.ProjectMetaDir, branch, multiPartMetaDataFileName)
_, err := os.Stat(filename)
if !os.IsNotExist(err) {
t.Fatalf("%s: %s should not exist", loc, filename)
}
}
}
newFile := func(dir, file string) {
testfile := filepath.Join(dir, file)
_, err := fake.X.NewSeq().Create(testfile)
if err != nil {
t.Errorf("failed to create %s: %v", testfile, err)
}
}
hasMetaData(len(mp.keys), "a1", ra, rb, rc)
hasNoMetaData(t1, "a2")
if err := mp.cleanMultiPartMetadata(fake.X); err != nil {
t.Fatal(err)
}
hasNoMetaData(ra, "a1", rb, rc, t1)
// Test CL messages.
for _, p := range projects {
// Install commit hook so that Change-Id is written.
installCommitMsgHook(t, fake.X, p.Path)
}
// Create a fake jiri root for the fake gerrit repos.
gerritFake, gerritCleanup := jiritest.NewFakeJiriRoot(t)
defer gerritCleanup()
relchdir(ra)
if err := mp.writeMultiPartMetadata(fake.X); err != nil {
t.Fatal(err)
}
hasMetaData(len(mp.keys), "a1", ra, rb, rc)
gitAddFiles := func(name string, repos ...string) {
for _, dir := range repos {
newFile(dir, name)
if err := git(dir).Add(name); err != nil {
t.Error(err)
}
}
}
gitCommit := func(msg string, repos ...string) {
for _, dir := range repos {
committer := git(dir).NewCommitter(false)
if err := committer.Commit(msg); err != nil {
t.Error(err)
}
}
}
gitAddFiles("new-file", ra, rb, rc)
_, err = initForMultiPart(fake.X)
if err == nil || !strings.Contains(err.Error(), "uncommitted changes:") {
t.Fatalf("expected an error about uncommitted changes: got %v", err)
}
gitCommit("oh multipart test\n", ra, rb, rc)
bodyMessage := "xyz\n\na simple message\n"
messageFile := filepath.Join(fake.X.Root, jiri.RootMetaDir, "message-body")
if err := ioutil.WriteFile(messageFile, []byte(bodyMessage), 0666); err != nil {
t.Fatal(err)
}
mp = initMP()
setTopicFlag = false
commitMessageBodyFlag = messageFile
testCommitMsgs := func(branch string, cls ...*project.Project) {
_, file, line, _ := runtime.Caller(1)
loc := fmt.Sprintf("%s:%d", filepath.Base(file), line)
total := len(cls)
for index, p := range cls {
// Create a new gerrit repo each time we commit, since we can't
// push more than once to the fake gerrit repo without actually
// running gerrit.
gp := createRepoFromOrigin(t, gerritFake.X, "gerrit", p.Remote)
defer os.Remove(gp)
relchdir(p.Path)
review, err := newReview(fake.X, *p, gerrit.CLOpts{
Presubmit: gerrit.PresubmitTestTypeNone,
Remote: gp,
})
if err != nil {
t.Fatalf("%v: %v: %v", loc, p.Path, err)
}
// use the default commit message
if err := review.run(); err != nil {
t.Fatalf("%v: %v, %v", loc, p.Path, err)
}
filename, err := getCommitMessageFileName(fake.X, branch)
if err != nil {
t.Fatalf("%v: %v", loc, err)
}
msg, err := ioutil.ReadFile(filename)
if err != nil {
t.Fatalf("%v: %v", loc, err)
}
if total < 2 {
if strings.Contains(string(msg), "MultiPart") {
t.Errorf("%v: commit message contains MultiPart when it should not: %v", loc, string(msg))
}
continue
}
expected := fmt.Sprintf("\nMultiPart: %d/%d\n", index+1, total)
if !strings.Contains(string(msg), expected) {
t.Errorf("%v: commit message for %v does not contain %v: %v", loc, p.Path, expected, string(msg))
}
if got, want := string(msg), bodyMessage+"PresubmitTest: none"+expected+"Change-Id: I0000000000000000000000000000000000000000"; got != want {
t.Errorf("got %v, want %v", got, want)
}
}
}
testCommitMsgs("a1", projects[0], projects[1], projects[2])
cl := mp.commandline("", []string{"-r=alice"})
expected := []string{
"runp",
"--interactive",
"--projects=" + string(projects[0].Key()) + "," + string(projects[1].Key()) + "," + string(projects[2].Key()),
"jiri",
"cl",
"mail",
"--current-project-only=true",
"-r=alice",
}
if got, want := strings.Join(cl, " "), strings.Join(expected, " "); got != want {
t.Errorf("got %v, want %v", got, want)
}
cl = mp.commandline(projects[0].Key(), []string{"-r=bob"})
expected[2] = "--projects=" + string(projects[1].Key()) + "," + string(projects[2].Key())
expected[len(expected)-1] = "-r=bob"
if got, want := strings.Join(cl, " "), strings.Join(expected, " "); got != want {
t.Errorf("got %v, want %v", got, want)
}
git(rb).CreateAndCheckoutBranch("a2")
gitAddFiles("new-file1", ra, rc)
gitCommit("oh multipart test: 2\n", ra, rc)
mp = initMP()
if err := mp.writeMultiPartMetadata(fake.X); err != nil {
t.Fatal(err)
}
hasMetaData(len(mp.keys), "a1", ra, rc)
testCommitMsgs("a1", projects[0], projects[2])
git(ra).CreateAndCheckoutBranch("a2")
mp = initMP()
if err := mp.writeMultiPartMetadata(fake.X); err != nil {
t.Fatal(err)
}
hasNoMetaData(rc)
testCommitMsgs("a1", projects[2])
}
| bsd-3-clause |
jamesslock/james.sl | src/components/pages/TheSchoolFund/VideoAbout.js | 600 | import React, {Component} from 'react';
import YouTube from 'react-youtube';
import s from './TheSchoolFund.css';
export default class VideoABout extends Component {
render() {
const opts = {
height: '720',
width: '1280',
playerVars: { // https://developers.google.com/youtube/player_parameters
autoplay: 1,
controls: 0,
showinfo: 0,
red: 0,
}
};
return (
<div className={s.videoAbout}>
<YouTube
videoId="9YhUSwjb_LI"
opts={opts}
onReady={this._onReady}
/>
</div>
);
}
}
| bsd-3-clause |
aarondancer/react-devtools | plugins/Relay/installRelayHook.js | 3833 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
/**
* NOTE: This file cannot `require` any other modules. We `.toString()` the
* function in some places and inject the source into the page.
* Also do not declare any variables in top level scope!
*/
function installRelayHook(window: Object) {
var performance = window.performance;
var performanceNow;
if (performance && typeof performance.now === 'function') {
performanceNow = () => performance.now();
} else {
performanceNow = () => Date.now();
}
const TEXT_CHUNK_LENGTH = 500;
var hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
if (!hook) {
return;
}
function decorate(obj, attr, fn) {
var old = obj[attr];
obj[attr] = function() {
var res = old.apply(this, arguments);
fn.apply(this, arguments);
return res;
};
}
var _eventQueue = [];
var _listener = null;
function emit(name: string, data: mixed) {
_eventQueue.push({name, data});
if (_listener) {
_listener(name, data);
}
}
function setRequestListener(
listener: (name: string, data: mixed) => void
): () => void {
if (_listener) {
throw new Error(
'Relay Devtools: Called only call setRequestListener once.'
);
}
_listener = listener;
_eventQueue.forEach(({name, data}) => {
listener(name, data);
});
return () => {
_listener = null;
};
}
function recordRequest(
type: 'mutation' | 'query',
start: number,
request,
requestNumber: number,
) {
var id = Math.random().toString(16).substr(2);
request.then(
response => {
emit('relay:success', {
id: id,
end: performanceNow(),
response: response.response,
});
},
error => {
emit('relay:failure', {
id: id,
end: performanceNow(),
error: error,
});
},
);
const textChunks = [];
let text = request.getQueryString();
while (text.length > 0) {
textChunks.push(text.substr(0, TEXT_CHUNK_LENGTH));
text = text.substr(TEXT_CHUNK_LENGTH);
}
return {
id: id,
name: request.getDebugName(),
requestNumber: requestNumber,
start: start,
text: textChunks,
type: type,
variables: request.getVariables(),
};
}
let requestNumber = 0;
function instrumentRelayRequests(relayInternals: Object) {
var NetworkLayer = relayInternals.NetworkLayer;
decorate(NetworkLayer, 'sendMutation', mutation => {
requestNumber++;
emit(
'relay:pending',
[recordRequest('mutation', performanceNow(), mutation, requestNumber)]
);
});
decorate(NetworkLayer, 'sendQueries', queries => {
requestNumber++;
const start = performanceNow();
emit(
'relay:pending',
queries.map(query => recordRequest('query', start, query, requestNumber))
);
});
var instrumented = {};
for (var key in relayInternals) {
if (relayInternals.hasOwnProperty(key)) {
instrumented[key] = relayInternals[key];
}
}
instrumented.setRequestListener = setRequestListener;
return instrumented;
}
var _relayInternals = null;
Object.defineProperty(hook, '_relayInternals', ({
configurable: true,
set: function(relayInternals) {
_relayInternals = instrumentRelayRequests(relayInternals);
},
get: function() {
return _relayInternals;
},
}: any));
}
module.exports = installRelayHook;
| bsd-3-clause |
blutack/mavlog | mavlog/__init__.py | 116 | # -*- coding: utf-8 -*-
__author__ = 'Gareth R'
__email__ = 'gareth.roberts@manchester.ac.uk'
__version__ = '0.1.0' | bsd-3-clause |
manuelpichler/phpUnderControl-copy-fork-and-follow-organization-repo | java/src/org/phpundercontrol/dashboard/ProjectInfos.java | 4208 | /**
* This file is part of phpUnderControl.
*
* Copyright (c) 2007-2010, Manuel Pichler <mapi@phpundercontrol.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:
*
* * 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 Manuel Pichler nor the names of his
* 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.
*
* @category QualityAssurance
* @author Manuel Pichler <mapi@phpundercontrol.org>
* @category 2007-2010 Manuel Pichler. All rights reserved.
* @version SVN: $Id$
*/
package org.phpundercontrol.dashboard;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
/**
* This class provides a simple list of all installed projects.
*
* @author Manuel Pichler
*/
public class ProjectInfos implements Iterable<ProjectInfo> {
/**
* The CruiseControl log directory.
*/
private String logDirectory = null;
/**
* Name of a CruiseControl build status file.
*/
private String fileName = null;
/**
* The used time/date string formater.
*/
private TimeFormater formater;
/**
* List of all project directories.
*/
private List<ProjectInfo> projects;
/**
* Marks the given log source as valid.
*/
private boolean valid = true;
/**
* Constructs a new project log directory instance.
*
* @param logDirectory The cc log directory
* @param fileName Name of CruisreControl's build status file
* @param locale The received client locals
*/
public ProjectInfos(String logDirectory, String fileName, Locale locale)
throws ParseException, IOException {
this.logDirectory = logDirectory;
this.fileName = fileName;
this.formater = new TimeFormater(locale);
this.loadProjectInfo();
}
/**
* Returns <b>true</b> when this is a valid result.
*
* @return boolean
*/
public boolean isValid() {
return this.valid;
}
/**
* This method will return <b>true</b> when no projects exists.
*
* @return boolean
*/
public boolean isEmpty() {
return this.projects.isEmpty();
}
@Override
public Iterator<ProjectInfo> iterator() {
return this.projects.iterator();
}
/**
* Loads all project info objects from CruiseControl's log directory.
*
* @throws ParseException
* @throws IOException
*/
private void loadProjectInfo() throws ParseException, IOException {
this.projects = new ArrayList<ProjectInfo>();
File file = new File(this.logDirectory);
this.valid = file.isDirectory();
if (this.valid == false) {
return;
}
String[] projectDirList = file.list(new DirectoryFilter());
for (String project: projectDirList) {
this.projects.add(new ProjectInfo(this.formater, this.fileName, file, project));
}
Collections.sort(this.projects);
}
} | bsd-3-clause |
dictyBase/apihelpers | aphtest/expect.go | 1847 | package aphtest
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/gocraft/dbr/v2"
)
// Resource is the interface that every http handler have to implement
type Resource interface {
// Gets the database handler
GetDbh() *dbr.Connection
// Handles the http GET for singular resource
Get(http.ResponseWriter, *http.Request)
// Handles the http GET for collection resource
GetAll(http.ResponseWriter, *http.Request)
// Handles the http POST
Create(http.ResponseWriter, *http.Request)
// Handles the http PATCH
Update(http.ResponseWriter, *http.Request)
// Handles the http DELETE
Delete(http.ResponseWriter, *http.Request)
}
// ExpectBuilder interface is for incremental building of http configuration
type ExpectBuilder interface {
Get(string) RequestBuilder
GetAll(string) RequestBuilder
}
// HTTPExpectBuilder implements ExpectBuilder interface
type HTTPExpectBuilder struct {
reporter Reporter
host string
resource Resource
}
// NewHTTPExpectBuilder is the constructor for HTTPExpectBuilder
func NewHTTPExpectBuilder(rep Reporter, host string, rs Resource) ExpectBuilder {
return &HTTPExpectBuilder{
reporter: rep,
host: host,
resource: rs,
}
}
// Get configures Request to execute a http GET request
func (b *HTTPExpectBuilder) Get(path string) RequestBuilder {
req := httptest.NewRequest(
"GET",
fmt.Sprintf(
"%s/%s",
b.host,
strings.Trim(path, "/"),
),
nil,
)
return NewHTTPRequestBuilder(b.reporter, req, b.resource.Get)
}
// GetAll configures Request to execute a http GET request to a collection resource
func (b *HTTPExpectBuilder) GetAll(path string) RequestBuilder {
req := httptest.NewRequest(
"GET",
fmt.Sprintf(
"%s/%s",
b.host,
strings.Trim(path, "/"),
),
nil,
)
return NewHTTPRequestBuilder(b.reporter, req, b.resource.GetAll)
}
| bsd-3-clause |
strogo/turbion | turbion/bits/watchlist/feeds.py | 1057 | from django.contrib.syndication.feeds import Feed
from django.utils.feedgenerator import Atom1Feed
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _
from django import http
from turbion.bits.blogs.models import Comment
from turbion.bits.profiles.models import Profile
from turbion.bits.blogs.feeds import CommentsFeedAtom
from turbion.bits.watchlist.models import Subscription
from turbion.bits import watchlist
from turbion.bits.utils.title import gen_title
class UserWatchlistFeed(CommentsFeedAtom):
link = ''
def get_object(self, bits):
if len(bits) >= 1:
return Profile.objects.get(pk=bits[0])
raise http.Http404
def title(self, user):
return gen_title({
"page": _('Watchlist'),
"section": _('For %s') % user.name
})
def description(self, user):
return _('Watchlist for %s') % user.name
subtitle = description
def items(self, user):
return watchlist.get_subcription_comments(user)[:50]
| bsd-3-clause |
lichong012245/django-lfs-0.7.8 | lfs/static/jquery/jquery.fileupload-4.2.1/jquery.fileupload-ui.js | 19946 | /*
* jQuery File Upload User Interface Plugin 4.3
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://creativecommons.org/licenses/MIT/
*/
/*jslint browser: true */
/*global jQuery, FileReader, URL, webkitURL */
(function ($) {
var undef = 'undefined',
func = 'function',
UploadHandler,
methods,
MultiLoader = function (callBack) {
var loaded = 0,
list = [];
this.complete = function () {
loaded += 1;
if (loaded === list.length + 1) {
// list.length * onComplete + 1 * onLoadAll
callBack(list);
loaded = 0;
list = [];
}
};
this.push = function (item) {
list.push(item);
};
this.getList = function () {
return list;
};
};
UploadHandler = function (container, options) {
var uploadHandler = this,
dragOverTimeout,
isDropZoneEnlarged,
multiLoader = new MultiLoader(function (list) {
uploadHandler.hideProgressBarAll(function () {
uploadHandler.resetProgressBarAll();
if (typeof uploadHandler.onCompleteAll === func) {
uploadHandler.onCompleteAll(list);
}
});
}),
getUploadTable = function (handler) {
return typeof handler.uploadTable === func ?
handler.uploadTable(handler) : handler.uploadTable;
},
getDownloadTable = function (handler) {
return typeof handler.downloadTable === func ?
handler.downloadTable(handler) : handler.downloadTable;
};
this.requestHeaders = {'Accept': 'application/json, text/javascript, */*; q=0.01'};
this.dropZone = container;
this.imageTypes = /^image\/(gif|jpeg|png)$/;
this.previewMaxWidth = this.previewMaxHeight = 80;
this.previewLoadDelay = 100;
this.previewAsCanvas = true;
this.previewSelector = '.file_upload_preview';
this.progressSelector = '.file_upload_progress div';
this.cancelSelector = '.file_upload_cancel button';
this.cssClassSmall = 'file_upload_small';
this.cssClassLarge = 'file_upload_large';
this.cssClassHighlight = 'file_upload_highlight';
this.dropEffect = 'highlight';
this.uploadTable = this.downloadTable = null;
this.buildUploadRow = this.buildDownloadRow = null;
this.progressAllNode = null;
this.loadImage = function (file, callBack, maxWidth, maxHeight, imageTypes, noCanvas) {
var img,
scaleImage,
urlAPI,
fileReader;
if (imageTypes && !imageTypes.test(file.type)) {
return null;
}
scaleImage = function (img) {
var canvas = document.createElement('canvas'),
scale = Math.min(
(maxWidth || img.width) / img.width,
(maxHeight || img.height) / img.height
);
if (scale > 1) {
scale = 1;
}
img.width = parseInt(img.width * scale, 10);
img.height = parseInt(img.height * scale, 10);
if (noCanvas || typeof canvas.getContext !== func) {
return img;
}
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
return canvas;
};
img = document.createElement('img');
urlAPI = typeof URL !== undef ? URL : typeof webkitURL !== undef ? webkitURL : null;
if (urlAPI && typeof urlAPI.createObjectURL === func) {
img.onload = function () {
urlAPI.revokeObjectURL(this.src);
callBack(scaleImage(img));
};
img.src = urlAPI.createObjectURL(file);
} else if (typeof FileReader !== undef &&
typeof FileReader.prototype.readAsDataURL === func) {
img.onload = function () {
callBack(scaleImage(img));
};
fileReader = new FileReader();
fileReader.onload = function (e) {
img.src = e.target.result;
};
fileReader.readAsDataURL(file);
} else {
callBack(null);
}
};
this.addNode = function (parentNode, node, callBack) {
if (parentNode && node) {
node.css('display', 'none').appendTo(parentNode).fadeIn(function () {
if (typeof callBack === func) {
try {
callBack();
} catch (e) {
// Fix endless exception loop:
node.stop();
throw e;
}
}
});
} else if (typeof callBack === func) {
callBack();
}
};
this.removeNode = function (node, callBack) {
if (node) {
node.fadeOut(function () {
node.remove();
if (typeof callBack === func) {
try {
callBack();
} catch (e) {
// Fix endless exception loop:
node.stop();
throw e;
}
}
});
} else if (typeof callBack === func) {
callBack();
}
};
this.replaceNode = function (oldNode, newNode, callBack) {
if (oldNode && newNode) {
oldNode.fadeOut(function () {
newNode.css('display', 'none');
oldNode.replaceWith(newNode);
newNode.fadeIn(function () {
if (typeof callBack === func) {
try {
callBack();
} catch (e) {
// Fix endless exception loop:
oldNode.stop();
newNode.stop();
throw e;
}
}
});
});
} else if (typeof callBack === func) {
callBack();
}
};
this.resetProgressBarAll = function () {
if (uploadHandler.progressbarAll) {
uploadHandler.progressbarAll.progressbar(
'value',
0
);
}
};
this.hideProgressBarAll = function (callBack) {
if (uploadHandler.progressbarAll && !$(getUploadTable(uploadHandler))
.find(uploadHandler.progressSelector + ':visible:first').length) {
uploadHandler.progressbarAll.fadeOut(callBack);
} else if (typeof callBack === func) {
callBack();
}
};
this.onAbort = function (event, files, index, xhr, handler) {
handler.removeNode(handler.uploadRow, handler.hideProgressBarAll);
};
this.cancelUpload = function (event, files, index, xhr, handler) {
var readyState = xhr.readyState;
xhr.abort();
// If readyState is below 2, abort() has no effect:
if (typeof readyState !== 'number' || readyState < 2) {
handler.onAbort(event, files, index, xhr, handler);
}
};
this.initProgressBar = function (node, value) {
if (!node || !node.length) {
return null;
}
if (typeof node.progressbar === func) {
return node.progressbar({
value: value
});
} else {
node.addClass('progressbar')
.append($('<div/>').css('width', value + '%'))
.progressbar = function (key, value) {
return this.each(function () {
if (key === 'destroy') {
$(this).removeClass('progressbar').empty();
} else {
$(this).children().css('width', value + '%');
}
});
};
return node;
}
};
this.destroyProgressBar = function (node) {
if (!node || !node.length) {
return null;
}
return node.progressbar('destroy');
};
this.initUploadProgress = function (xhr, handler) {
if (!xhr.upload && handler.progressbar) {
handler.progressbar.progressbar(
'value',
100 // indeterminate progress displayed by a full animated progress bar
);
}
};
this.initUploadProgressAll = function () {
if (uploadHandler.progressbarAll && uploadHandler.progressbarAll.is(':hidden')) {
uploadHandler.progressbarAll.fadeIn();
}
};
this.onSend = function (event, files, index, xhr, handler) {
handler.initUploadProgress(xhr, handler);
};
this.onProgress = function (event, files, index, xhr, handler) {
if (handler.progressbar && event.lengthComputable) {
handler.progressbar.progressbar(
'value',
parseInt(event.loaded / event.total * 100, 10)
);
}
};
this.onProgressAll = function (event, list) {
if (uploadHandler.progressbarAll && event.lengthComputable) {
uploadHandler.progressbarAll.progressbar(
'value',
parseInt(event.loaded / event.total * 100, 10)
);
}
};
this.onLoadAll = function (list) {
multiLoader.complete();
};
this.initProgressBarAll = function () {
if (!uploadHandler.progressbarAll) {
uploadHandler.progressbarAll = uploadHandler.initProgressBar(
(typeof uploadHandler.progressAllNode === func ?
uploadHandler.progressAllNode(uploadHandler) : uploadHandler.progressAllNode),
0
);
}
};
this.destroyProgressBarAll = function () {
uploadHandler.destroyProgressBar(uploadHandler.progressbarAll);
};
this.initUploadRow = function (event, files, index, xhr, handler) {
var uploadRow = handler.uploadRow = (typeof handler.buildUploadRow === func ?
handler.buildUploadRow(files, index, handler) : null);
if (uploadRow) {
handler.progressbar = handler.initProgressBar(
uploadRow.find(handler.progressSelector),
0
);
uploadRow.find(handler.cancelSelector).click(function (e) {
handler.cancelUpload(e, files, index, xhr, handler);
e.preventDefault();
});
uploadRow.find(handler.previewSelector).each(function () {
var previewNode = $(this),
file = files[index];
if (file) {
setTimeout(function () {
handler.loadImage(
file,
function (img) {
handler.addNode(
previewNode,
$(img)
);
},
handler.previewMaxWidth,
handler.previewMaxHeight,
handler.imageTypes,
!handler.previewAsCanvas
);
}, handler.previewLoadDelay);
}
});
}
};
this.initUpload = function (event, files, index, xhr, handler, callBack) {
handler.initUploadRow(event, files, index, xhr, handler);
handler.addNode(
getUploadTable(handler),
handler.uploadRow,
function () {
if (typeof handler.beforeSend === func) {
handler.beforeSend(event, files, index, xhr, handler, callBack);
} else {
callBack();
}
}
);
handler.initUploadProgressAll();
};
this.parseResponse = function (xhr) {
if (typeof xhr.responseText !== undef) {
return $.parseJSON(xhr.responseText);
} else {
// Instead of an XHR object, an iframe is used for legacy browsers:
return $.parseJSON(xhr.contents().text());
}
};
this.initDownloadRow = function (event, files, index, xhr, handler) {
var json, downloadRow;
try {
json = handler.response = handler.parseResponse(xhr);
downloadRow = handler.downloadRow = (typeof handler.buildDownloadRow === func ?
handler.buildDownloadRow(json, handler) : null);
} catch (e) {
if (typeof handler.onError === func) {
handler.originalEvent = event;
handler.onError(e, files, index, xhr, handler);
} else {
throw e;
}
}
};
this.onLoad = function (event, files, index, xhr, handler) {
var uploadTable = getUploadTable(handler),
downloadTable = getDownloadTable(handler),
callBack = function () {
if (typeof handler.onComplete === func) {
handler.onComplete(event, files, index, xhr, handler);
}
multiLoader.complete();
};
multiLoader.push(Array.prototype.slice.call(arguments, 1));
handler.initDownloadRow(event, files, index, xhr, handler);
if (uploadTable && (!downloadTable || uploadTable.get(0) === downloadTable.get(0))) {
handler.replaceNode(handler.uploadRow, handler.downloadRow, callBack);
} else {
handler.removeNode(handler.uploadRow, function () {
handler.addNode(
downloadTable,
handler.downloadRow,
callBack
);
});
}
};
this.dropZoneEnlarge = function () {
if (!isDropZoneEnlarged) {
if (typeof uploadHandler.dropZone.switchClass === func) {
uploadHandler.dropZone.switchClass(
uploadHandler.cssClassSmall,
uploadHandler.cssClassLarge
);
} else {
uploadHandler.dropZone.addClass(uploadHandler.cssClassLarge);
uploadHandler.dropZone.removeClass(uploadHandler.cssClassSmall);
}
isDropZoneEnlarged = true;
}
};
this.dropZoneReduce = function () {
if (typeof uploadHandler.dropZone.switchClass === func) {
uploadHandler.dropZone.switchClass(
uploadHandler.cssClassLarge,
uploadHandler.cssClassSmall
);
} else {
uploadHandler.dropZone.addClass(uploadHandler.cssClassSmall);
uploadHandler.dropZone.removeClass(uploadHandler.cssClassLarge);
}
isDropZoneEnlarged = false;
};
this.onDocumentDragEnter = function (event) {
uploadHandler.dropZoneEnlarge();
};
this.onDocumentDragOver = function (event) {
if (dragOverTimeout) {
clearTimeout(dragOverTimeout);
}
dragOverTimeout = setTimeout(function () {
uploadHandler.dropZoneReduce();
}, 200);
};
this.onDragEnter = this.onDragLeave = function (event) {
uploadHandler.dropZone.toggleClass(uploadHandler.cssClassHighlight);
};
this.onDrop = function (event) {
if (dragOverTimeout) {
clearTimeout(dragOverTimeout);
}
if (uploadHandler.dropEffect && typeof uploadHandler.dropZone.effect === func) {
uploadHandler.dropZone.effect(uploadHandler.dropEffect, function () {
uploadHandler.dropZone.removeClass(uploadHandler.cssClassHighlight);
uploadHandler.dropZoneReduce();
});
} else {
uploadHandler.dropZone.removeClass(uploadHandler.cssClassHighlight);
uploadHandler.dropZoneReduce();
}
};
this.init = function () {
uploadHandler.initProgressBarAll();
};
this.destroy = function () {
uploadHandler.destroyProgressBarAll();
};
$.extend(this, options);
};
methods = {
init : function (options) {
return this.each(function () {
$(this).fileUpload(new UploadHandler($(this), options))
.fileUploadUI('option', 'init', undefined, options.namespace)();
});
},
option: function (option, value, namespace) {
if (!option || (typeof option === 'string' && typeof value === undef)) {
return $(this).fileUpload('option', option, value, namespace);
}
return this.each(function () {
$(this).fileUpload('option', option, value, namespace);
});
},
destroy : function (namespace) {
return this.each(function () {
$(this).fileUploadUI('option', 'destroy', undefined, namespace)();
$(this).fileUpload('destroy', namespace);
});
},
upload: function (files, namespace) {
return this.each(function () {
$(this).fileUpload('upload', files, namespace);
});
}
};
$.fn.fileUploadUI = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method "' + method + '" does not exist on jQuery.fileUploadUI');
}
};
}(jQuery)); | bsd-3-clause |
denners777/API-Phalcon | app/modules/nucleo/controllers/ControllersController.php | 5775 | <?php
/**
* @copyright 2015 - 2016 Grupo MPE
* @license New BSD License; see LICENSE
* @link http://www.grupompe.com.br
* @author Denner Fernandes <denner.fernandes@grupompe.com.br>
* */
namespace App\Modules\Nucleo\Controllers;
use App\Modules\Nucleo\Models\Controllers;
use App\Shared\Controllers\ControllerBase;
class ControllersController extends ControllerBase {
/**
* initialize
*/
public function initialize() {
$this->tag->setTitle(' Controladores ');
parent::initialize();
$this->entity = new Controllers();
}
/**
* Index controller
*/
public function indexAction() {
try {
$this->view->controllers = Controllers::find();
$this->view->pesquisa = '';
if ($this->request->isPost()) {
$post = $this->request->getPost('controllers', 'string');
$search = "(UPPER(title) LIKE UPPER('%" . $post . "%')
OR UPPER(slug) LIKE UPPER('%" . $post . "%')
OR UPPER(description) LIKE UPPER('%" . $post . "%'))";
$this->view->controllers = Controllers::find($search);
$this->view->pesquisa = $this->request->getPost('controllers');
}
} catch (\Exception $e) {
$this->flash->error($e->getMessage());
}
}
/**
* Displays the creation form
*/
public function newAction() {
}
/**
* Edits a controller
*
* @param string $id
*/
public function editAction($id) {
try {
if ($this->request->isPost()) {
throw new Exception('Acesso inválido a essa action!!!');
}
$controller = Controllers::findFirstByid($id);
if (!$controller) {
throw new Exception('Controlador não encontrado!');
}
$this->view->id = $controller->id;
$this->tag->setDefault('id', $controller->getId());
$this->tag->setDefault('title', $controller->getTitle());
$this->tag->setDefault('slug', $controller->getSlug());
$this->tag->setDefault('description', $controller->getDescription());
} catch (Exception $e) {
$this->flash->error($e->getMessage());
return $this->response->redirect('nucleo/controllers');
}
}
/**
* Creates a new controller
*/
public function createAction() {
try {
if (!$this->request->isPost()) {
throw new Exception('Acesso não permitido a essa action.');
}
$controller = $this->entity;
$controller->setId($controller->autoincrement());
$controller->setTitle($this->request->getPost('title'));
$controller->setSlug($this->request->getPost('slug'));
$controller->setDescription($this->request->getPost('description'));
if (!$controller->create()) {
$msg = '';
foreach ($controller->getMessages() as $message) {
$msg .= $message . '<br />';
}
throw new Exception($msg);
}
$this->flash->success('Controlador gravado com sucesso!!!');
} catch (Exception $e) {
$this->flash->error($e->getMessage());
}
return $this->response->redirect('nucleo/controllers');
}
/**
* Saves a controller edited
*
*/
public function saveAction() {
try {
if (!$this->request->isPost()) {
throw new Exception('Acesso não permitido a essa action.');
}
$id = $this->request->getPost('id');
$controller = Controllers::findFirstByid($id);
if (!$controller) {
throw new Exception('Controlador não encontrado!');
}
$controller->setId($this->request->getPost('id'));
$controller->setTitle($this->request->getPost('title'));
$controller->setSlug($this->request->getPost('slug'));
$controller->setDescription($this->request->getPost('description'));
if (!$controller->update()) {
$msg = '';
foreach ($controller->getMessages() as $message) {
$msg .= $message . '<br />';
}
throw new Exception($msg);
}
$this->flash->success('Controlador atualizado com sucesso!!!');
} catch (Exception $e) {
$this->flash->error($e->getMessage());
}
return $this->response->redirect('nucleo/controllers');
}
/**
* Deletes a controller
*
* @param string $id
*/
public function deleteAction() {
try {
if (!$this->request->isPost()) {
throw new Exception('Acesso não permitido a essa action.');
}
if ($this->request->isAjax()) {
$this->view->disable();
}
$id = $this->request->getPost('id');
$controller = Controllers::findFirstByid($id);
if (!$controller) {
throw new Exception('Controlador não encontrado!');
}
if (!$controller->delete()) {
$msg = '';
foreach ($controller->getMessages() as $message) {
$msg .= $message . '<br />';
}
throw new Exception($msg);
}
echo 'ok';
} catch (Exception $e) {
$this->flash->error($e->getMessage());
return $this->response->redirect('nucleo/controllers');
}
}
}
| bsd-3-clause |
owtf/owtf | owtf/webapp/src/containers/Report/Export.js | 1257 | import Docxtemplater from "docxtemplater";
import { importDirectory } from "../../utils/export";
import JSZip from "jszip";
import saveAs from "save-as";
import "@babel/polyfill";
const templates = importDirectory(
require.context("./templates/", true, /\.(docx)$/)
);
export const templatesNames = Object.keys(templates);
// Funtion responsible for generating docx from JSON using docxtemplater.
export function getDocxReportFromJSON(json, template) {
var zip = new JSZip(templates[template]);
var doc = new Docxtemplater();
doc.loadZip(zip);
//set the templateVariables
doc.setData(json);
try {
// render the document (replace all occurences of tags.
doc.render();
} catch (error) {
var e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties
};
console.log(
JSON.stringify({
error: e
})
);
// The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
throw error;
}
var out = doc.getZip().generate({
type: "blob",
mimeType:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
});
saveAs(out, "report.docx");
}
| bsd-3-clause |
dgg/nmoneys | src/NMoneys/Serialization/Data.net.cs | 1392 | using System.Runtime.Serialization;
namespace NMoneys.Serialization
{
internal static class Data
{
[DataContract]
public class Currency
{
internal const string ISO_CODE = "isoCode";
internal const string ROOT_NAME = "currency", DATA_TYPE = "currencyType";
[DataMember(Name = ISO_CODE)]
public string IsoCode { get; set; }
public Currency(NMoneys.Currency surrogated)
{
IsoCode = surrogated.IsoSymbol;
}
public Currency(CurrencyIsoCode surrogated)
{
IsoCode = surrogated.AlphabeticCode();
}
public NMoneys.Currency RevertSurrogation()
{
return NMoneys.Currency.Get(IsoCode);
}
}
[DataContract]
public class Money
{
internal const string AMOUNT = "amount", CURRENCY = "currency";
internal const string ROOT_NAME = "money", DATA_TYPE = "moneyType";
[DataMember(Name = AMOUNT)]
public decimal Amount { get; set; }
[DataMember(Name = CURRENCY)]
public Currency Currency { get; set; }
public Money(NMoneys.Money surrogated)
{
Amount = surrogated.Amount;
Currency = new Currency(surrogated.CurrencyCode);
}
public NMoneys.Money RevertSurrogation()
{
return new NMoneys.Money(Amount, Currency.IsoCode);
}
}
internal const string NAMESPACE = "urn:nmoneys";
internal static readonly string ResourceName = typeof(Data).Namespace + "." + "SerializationSchema.xsd";
}
}
| bsd-3-clause |
nsf-ri-ubicv/sthor | sthor/model/slm.py | 12479 | """Sequential Layered Model"""
# Authors: Nicolas Pinto <nicolas.pinto@gmail.com>
# Nicolas Poilvert <nicolas.poilvert@gmail.com>
#
# License: BSD
import numpy as np
import numexpr as ne
import warnings
from skimage.util.shape import view_as_windows
from sthor.operation import lcdnorm3
from sthor.operation import fbcorr3
from sthor.operation import lpool3
from sthor.util.pad import filter_pad2d
from pprint import pprint
DTYPE = np.float32
# ----------------
# Helper functions
# ----------------
def _get_ops_nbh_nbw_stride(description):
to_return = []
for layer in description:
for operation in layer:
if operation[0] == 'lnorm':
nbh, nbw = operation[1]['kwargs']['inker_shape']
to_return += [('lnorm', nbh, nbw, 1)]
elif operation[0] == 'fbcorr':
nbh, nbw = operation[1]['initialize']['filter_shape']
to_return += [('fbcorr', nbh, nbw, 1)]
else:
nbh, nbw = operation[1]['kwargs']['ker_shape']
striding = operation[1]['kwargs']['stride']
to_return += [('lpool', nbh, nbw, striding)]
return to_return
def _get_receptive_field_shape(description):
ops_param = _get_ops_nbh_nbw_stride(description)
# -- in this case the SLM does nothing so
# it is the identity
if len(ops_param) == 0:
return (1, 1)
# -- otherwise we processed the image with some
# operations and we go backwards to estimate
# the global receptive field of the SLM
else:
# -- we start from a single pixel-wide shape
out_h, out_w = 1, 1
# -- then we compute what was the shape before
# we applied the preceding operation
for _, nbh, nbw, s in reversed(ops_param):
in_h = (out_h - 1) * s + nbh
in_w = (out_w - 1) * s + nbw
out_h, out_w = in_h, in_w
return (out_h, out_w)
# --------------
# SLM base class
# --------------
class SequentialLayeredModel(object):
def __init__(self, in_shape, description):
"""XXX: docstring for __init__"""
pprint(description)
self.description = description
self.n_layers = len(description)
self.in_shape = in_shape
self.filterbanks = {}
self.ops_nbh_nbw_stride = _get_ops_nbh_nbw_stride(description)
self.receptive_field_shape = _get_receptive_field_shape(description)
try:
self.process = profile(self.process)
except NameError:
pass
def process(self, arr_in, pad_apron=False, interleave_stride=False):
warnings.warn("process(...) is deprecated, please use transform(...)",
DeprecationWarning, stacklevel=2)
return self.transform(arr_in, pad_apron=pad_apron, interleave_stride=interleave_stride)
def transform(self, arr_in, pad_apron=False, interleave_stride=False):
"""XXX: docstring for transform"""
rcpt_field = self.receptive_field_shape
description = self.description
input_shape = arr_in.shape
assert input_shape[:2] == self.in_shape
assert len(input_shape) == 2 or len(input_shape) == 3
if len(input_shape) == 3:
tmp_out = arr_in
elif len(input_shape) == 2:
tmp_out = arr_in[..., np.newaxis]
else:
raise ValueError("The input array should be 2D or 3D")
# -- first we initialize some variables to be used in
# the processing of the feature maps
h, w = self.in_shape
Y, X = np.mgrid[:h, :w]
tmp_out_l = [(tmp_out, X, Y)]
nbh_nbw_stride_l = self.ops_nbh_nbw_stride
# -- loop over all the SLM operations in order
op_counter = 0
for layer_idx, layer_desc in enumerate(description):
for op_idx, (op_name, op_params) in enumerate(layer_desc):
kwargs = op_params['kwargs']
tmp_l = []
_, nbh, nbw, stride = nbh_nbw_stride_l[op_counter]
for arr, X, Y in tmp_out_l:
tmp_l += self._process_one_op(arr, X, Y,
layer_idx, op_idx, kwargs,
op_params,
op_name, nbh, nbw, stride,
pad_apron=pad_apron,
interleave_stride=interleave_stride)
tmp_out_l = tmp_l
op_counter += 1
# -- now we need to possibly interleave the arrays
# in ``tmp_out_l``
if interleave_stride:
out_shape = (h, w, tmp_out_l[0][0].shape[-1])
arr_out = np.empty(out_shape, dtype=arr_in.dtype)
Y_ref, X_ref = np.mgrid[:h, :w]
Y_int, X_int = np.zeros((h, w), dtype=np.int), \
np.zeros((h, w), dtype=np.int)
if pad_apron:
for arr, Xc, Yc in tmp_out_l:
anchor_h, anchor_w = Yc[0, 0], Xc[0, 0]
stride_h = Yc[1, 0] - Yc[0, 0]
stride_w = Xc[0, 1] - Xc[0, 0]
arr_out[anchor_h::stride_h, anchor_w::stride_w, ...] = arr
X_int[anchor_h::stride_h, anchor_w::stride_w] = Xc
Y_int[anchor_h::stride_h, anchor_w::stride_w] = Yc
assert (X_int == X_ref).all()
assert (Y_int == Y_ref).all()
return arr_out
else:
X_int = filter_pad2d(X_int[..., np.newaxis], rcpt_field,
reverse_padding=True).squeeze()
Y_int = filter_pad2d(Y_int[..., np.newaxis], rcpt_field,
reverse_padding=True).squeeze()
X_ref = filter_pad2d(X_ref[..., np.newaxis], rcpt_field,
reverse_padding=True).squeeze()
Y_ref = filter_pad2d(Y_ref[..., np.newaxis], rcpt_field,
reverse_padding=True).squeeze()
arr_out = filter_pad2d(arr_out, rcpt_field,
reverse_padding=True)
offset_Y = Y_ref.min()
offset_X = X_ref.min()
for arr, Xc, Yc in tmp_out_l:
anchor_h, anchor_w = Yc[0, 0] - offset_Y, \
Xc[0, 0] - offset_X
stride_h = Yc[1, 0] - Yc[0, 0]
stride_w = Xc[0, 1] - Xc[0, 0]
arr_out[anchor_h::stride_h, anchor_w::stride_w, ...] = arr
X_int[anchor_h::stride_h, anchor_w::stride_w] = Xc
Y_int[anchor_h::stride_h, anchor_w::stride_w] = Yc
assert (X_int == X_ref).all()
assert (Y_int == Y_ref).all()
return arr_out
else:
assert len(tmp_out_l) == 1
arr_out, _, _ = tmp_out_l[0]
return arr_out
def _process_one_op(self, arr, X, Y,
layer_idx, op_idx, kwargs,
op_params,
op_name, nbh, nbw, stride,
pad_apron=False,
interleave_stride=False):
out_l = []
# -- here we compute the pixel coordinates of
# the central pixel in a patch
hc, wc = nbh / 2, nbw / 2
if pad_apron:
arr = filter_pad2d(arr, (nbh, nbw))
X = np.squeeze(filter_pad2d(X[..., np.newaxis], (nbh, nbw),
constant=-1))
Y = np.squeeze(filter_pad2d(Y[..., np.newaxis], (nbh, nbw),
constant=-1))
if interleave_stride:
for i in xrange(stride):
for j in xrange(stride):
arr_out_ij = self._get_feature_map(arr[i::, j::, ...],
layer_idx, op_idx, kwargs,
op_params, op_name)
X_out_ij = view_as_windows(X[i::, j::],
(nbh, nbw))[::stride, ::stride,
hc, wc]
Y_out_ij = view_as_windows(Y[i::, j::],
(nbh, nbw))[::stride, ::stride,
hc, wc]
out_l += [(arr_out_ij, X_out_ij, Y_out_ij)]
else:
arr_out = self._get_feature_map(arr, layer_idx, op_idx, kwargs,
op_params, op_name)
X_out = view_as_windows(X, (nbh, nbw))[::stride, ::stride, hc, wc]
Y_out = view_as_windows(Y, (nbh, nbw))[::stride, ::stride, hc, wc]
out_l += [(arr_out, X_out, Y_out)]
return out_l
def _get_feature_map(self, tmp_in,
layer_idx, op_idx, kwargs,
op_params, op_name):
if op_name == 'lnorm':
inker_shape = kwargs['inker_shape']
outker_shape = kwargs['outker_shape']
remove_mean = kwargs['remove_mean']
stretch = kwargs['stretch']
threshold = kwargs['threshold']
# SLM PLoS09 / FG11 constraints:
assert inker_shape == outker_shape
tmp_out = lcdnorm3(tmp_in, inker_shape,
contrast=remove_mean,
stretch=stretch,
threshold=threshold)
elif op_name == 'fbcorr':
max_out = kwargs['max_out']
min_out = kwargs['min_out']
fbkey = layer_idx, op_idx
if fbkey not in self.filterbanks:
initialize = op_params['initialize']
if isinstance(initialize, np.ndarray):
fb = initialize
if len(fb.shape) == 3:
fb = fb[..., np.newaxis]
else:
filter_shape = list(initialize['filter_shape'])
generate = initialize['generate']
n_filters = initialize['n_filters']
fb_shape = [n_filters] + filter_shape + [tmp_in.shape[-1]]
# generate filterbank data
method_name, method_kwargs = generate
assert method_name == 'random:uniform'
rseed = method_kwargs.get('rseed', None)
rng = np.random.RandomState(rseed)
fb = rng.uniform(size=fb_shape)
for fidx in xrange(n_filters):
filt = fb[fidx]
# zero-mean, unit-l2norm
filt -= filt.mean()
filt_norm = np.linalg.norm(filt)
assert filt_norm != 0
filt /= filt_norm
fb[fidx] = filt
fb = np.ascontiguousarray(np.rollaxis(fb, 0, 4)).astype(DTYPE)
self.filterbanks[fbkey] = fb
print fb.shape
fb = self.filterbanks[fbkey]
# -- filter
assert tmp_in.dtype == np.float32
tmp_out = fbcorr3(tmp_in, fb)
# -- activation
min_out = -np.inf if min_out is None else min_out
max_out = +np.inf if max_out is None else max_out
# insure that the type is right before calling numexpr
min_out = np.array([min_out], dtype=tmp_in.dtype)
max_out = np.array([max_out], dtype=tmp_in.dtype)
# call numexpr
tmp_out = ne.evaluate('where(tmp_out < min_out, min_out, tmp_out)')
tmp_out = ne.evaluate('where(tmp_out > max_out, max_out, tmp_out)')
assert tmp_out.dtype == tmp_in.dtype
elif op_name == 'lpool':
ker_shape = kwargs['ker_shape']
order = kwargs['order']
stride = kwargs['stride']
tmp_out = lpool3(tmp_in, ker_shape, order=order, stride=stride)
else:
raise ValueError("operation '%s' not understood" % op_name)
assert tmp_out.dtype == tmp_in.dtype
assert tmp_out.dtype == np.float32
return tmp_out
| bsd-3-clause |
vitalik199415/motor.com | application/logs/2015/03/12.php | 1296 | <?php defined('SYSPATH') OR die('No direct script access.'); ?>
2015-03-12 15:35:14 --- EMERGENCY: ErrorException [ 8 ]: Undefined variable: title ~ APPPATH/views/front/404.php [ 8 ] in /opt/lampp/htdocs/motor.com/application/views/front/404.php:8
2015-03-12 15:35:14 --- DEBUG: #0 /opt/lampp/htdocs/motor.com/application/views/front/404.php(8): Kohana_Core::error_handler(8, 'Undefined varia...', '/opt/lampp/htdo...', 8, Array)
#1 /opt/lampp/htdocs/motor.com/system/classes/Kohana/View.php(62): include('/opt/lampp/htdo...')
#2 /opt/lampp/htdocs/motor.com/system/classes/Kohana/View.php(359): Kohana_View::capture('/opt/lampp/htdo...', Array)
#3 /opt/lampp/htdocs/motor.com/application/classes/HTTP/Exception/404.php(21): Kohana_View->render()
#4 /opt/lampp/htdocs/motor.com/system/classes/Kohana/Request/Client/Internal.php(115): HTTP_Exception_404->get_response()
#5 /opt/lampp/htdocs/motor.com/system/classes/Kohana/Request/Client.php(114): Kohana_Request_Client_Internal->execute_request(Object(Request), Object(Response))
#6 /opt/lampp/htdocs/motor.com/system/classes/Kohana/Request.php(998): Kohana_Request_Client->execute(Object(Request))
#7 /opt/lampp/htdocs/motor.com/index.php(118): Kohana_Request->execute()
#8 {main} in /opt/lampp/htdocs/motor.com/application/views/front/404.php:8 | bsd-3-clause |
nacl-webkit/chrome_deps | chrome/browser/profiles/profile_manager.cc | 39240 | // 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 <set>
#include "chrome/browser/profiles/profile_manager.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/metrics/histogram.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile_destroyer.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_metrics.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/user_metrics.h"
#include "grit/generated_resources.h"
#include "net/http/http_transaction_factory.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_job.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(ENABLE_MANAGED_USERS)
#include "chrome/browser/managed_mode/managed_mode.h"
#include "chrome/browser/managed_mode/managed_user_service.h"
#include "chrome/browser/managed_mode/managed_user_service_factory.h"
#endif
#if !defined(OS_IOS)
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/sessions/session_service_factory.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/startup/startup_browser_creator.h"
#endif // !defined (OS_IOS)
#if defined(OS_WIN)
#include "base/win/metro.h"
#include "chrome/installer/util/browser_distribution.h"
#endif
#if defined(OS_CHROMEOS)
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#endif
using content::BrowserThread;
using content::UserMetricsAction;
namespace {
static bool did_perform_profile_import = false;
// Profiles that should be deleted on shutdown.
std::vector<FilePath>& ProfilesToDelete() {
CR_DEFINE_STATIC_LOCAL(std::vector<FilePath>, profiles_to_delete, ());
return profiles_to_delete;
}
// Simple task to log the size of the current profile.
void ProfileSizeTask(const FilePath& path, int extension_count) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
int64 size = file_util::ComputeFilesSize(path, FILE_PATH_LITERAL("*"));
int size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.TotalSize", size_MB);
size = file_util::ComputeFilesSize(path, FILE_PATH_LITERAL("History"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.HistorySize", size_MB);
size = file_util::ComputeFilesSize(path, FILE_PATH_LITERAL("History*"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.TotalHistorySize", size_MB);
size = file_util::ComputeFilesSize(path, FILE_PATH_LITERAL("Cookies"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.CookiesSize", size_MB);
size = file_util::ComputeFilesSize(path, FILE_PATH_LITERAL("Bookmarks"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.BookmarksSize", size_MB);
size = file_util::ComputeFilesSize(path, FILE_PATH_LITERAL("Favicons"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.FaviconsSize", size_MB);
size = file_util::ComputeFilesSize(path, FILE_PATH_LITERAL("Top Sites"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.TopSitesSize", size_MB);
size = file_util::ComputeFilesSize(path, FILE_PATH_LITERAL("Visited Links"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.VisitedLinksSize", size_MB);
size = file_util::ComputeFilesSize(path, FILE_PATH_LITERAL("Web Data"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.WebDataSize", size_MB);
size = file_util::ComputeFilesSize(path, FILE_PATH_LITERAL("Extension*"));
size_MB = static_cast<int>(size / (1024 * 1024));
UMA_HISTOGRAM_COUNTS_10000("Profile.ExtensionSize", size_MB);
// Count number of extensions in this profile, if we know.
if (extension_count != -1)
UMA_HISTOGRAM_COUNTS_10000("Profile.AppCount", extension_count);
}
void QueueProfileDirectoryForDeletion(const FilePath& path) {
ProfilesToDelete().push_back(path);
}
// Called upon completion of profile creation. This function takes care of
// launching a new browser window and signing the user in to their Google
// account.
void OnOpenWindowForNewProfile(
chrome::HostDesktopType desktop_type,
const ProfileManager::CreateCallback& callback,
Profile* profile,
Profile::CreateStatus status) {
if (status == Profile::CREATE_STATUS_INITIALIZED) {
ProfileManager::FindOrCreateNewWindowForProfile(
profile,
chrome::startup::IS_PROCESS_STARTUP,
chrome::startup::IS_FIRST_RUN,
desktop_type,
false);
}
if (!callback.is_null())
callback.Run(profile, status);
}
#if defined(OS_CHROMEOS)
void CheckCryptohomeIsMounted(chromeos::DBusMethodCallStatus call_status,
bool is_mounted) {
if (call_status != chromeos::DBUS_METHOD_CALL_SUCCESS) {
LOG(ERROR) << "IsMounted call failed.";
return;
}
if (!is_mounted)
LOG(ERROR) << "Cryptohome is not mounted.";
}
#endif
} // namespace
#if defined(ENABLE_SESSION_SERVICE)
// static
void ProfileManager::ShutdownSessionServices() {
ProfileManager* pm = g_browser_process->profile_manager();
if (!pm) // Is NULL when running unit tests.
return;
std::vector<Profile*> profiles(pm->GetLoadedProfiles());
for (size_t i = 0; i < profiles.size(); ++i)
SessionServiceFactory::ShutdownForProfile(profiles[i]);
}
#endif
// static
void ProfileManager::NukeDeletedProfilesFromDisk() {
for (std::vector<FilePath>::iterator it =
ProfilesToDelete().begin();
it != ProfilesToDelete().end();
++it) {
// Delete both the profile directory and its corresponding cache.
FilePath cache_path;
chrome::GetUserCacheDirectory(*it, &cache_path);
file_util::Delete(*it, true);
file_util::Delete(cache_path, true);
}
ProfilesToDelete().clear();
}
// static
Profile* ProfileManager::GetDefaultProfile() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
return profile_manager->GetDefaultProfile(profile_manager->user_data_dir_);
}
// static
Profile* ProfileManager::GetDefaultProfileOrOffTheRecord() {
// TODO (mukai,nkostylev): In the long term we should fix those cases that
// crash on Guest mode and have only one GetDefaultProfile() method.
Profile* profile = GetDefaultProfile();
#if defined(OS_CHROMEOS)
if (chromeos::UserManager::Get()->IsLoggedInAsGuest())
profile = profile->GetOffTheRecordProfile();
#endif
return profile;
}
// static
Profile* ProfileManager::GetLastUsedProfile() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
return profile_manager->GetLastUsedProfile(profile_manager->user_data_dir_);
}
// static
std::vector<Profile*> ProfileManager::GetLastOpenedProfiles() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
return profile_manager->GetLastOpenedProfiles(
profile_manager->user_data_dir_);
}
ProfileManager::ProfileManager(const FilePath& user_data_dir)
: user_data_dir_(user_data_dir),
logged_in_(false),
will_import_(false),
profile_shortcut_manager_(NULL),
#if !defined(OS_ANDROID) && !defined(OS_IOS)
ALLOW_THIS_IN_INITIALIZER_LIST(
browser_list_observer_(this)),
#endif
closing_all_browsers_(false) {
#if defined(OS_CHROMEOS)
registrar_.Add(
this,
chrome::NOTIFICATION_LOGIN_USER_CHANGED,
content::NotificationService::AllSources());
#endif
registrar_.Add(
this,
chrome::NOTIFICATION_BROWSER_OPENED,
content::NotificationService::AllSources());
registrar_.Add(
this,
chrome::NOTIFICATION_BROWSER_CLOSED,
content::NotificationService::AllSources());
registrar_.Add(
this,
chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
content::NotificationService::AllSources());
registrar_.Add(
this,
chrome::NOTIFICATION_BROWSER_CLOSE_CANCELLED,
content::NotificationService::AllSources());
if (ProfileShortcutManager::IsFeatureEnabled() && !user_data_dir.empty())
profile_shortcut_manager_.reset(ProfileShortcutManager::Create(
this));
}
ProfileManager::~ProfileManager() {
}
FilePath ProfileManager::GetDefaultProfileDir(
const FilePath& user_data_dir) {
FilePath default_profile_dir(user_data_dir);
default_profile_dir =
default_profile_dir.AppendASCII(chrome::kInitialProfile);
return default_profile_dir;
}
FilePath ProfileManager::GetProfilePrefsPath(
const FilePath &profile_dir) {
FilePath default_prefs_path(profile_dir);
default_prefs_path = default_prefs_path.Append(chrome::kPreferencesFilename);
return default_prefs_path;
}
FilePath ProfileManager::GetInitialProfileDir() {
FilePath relative_profile_dir;
#if defined(OS_CHROMEOS)
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (logged_in_) {
FilePath profile_dir;
// If the user has logged in, pick up the new profile.
if (command_line.HasSwitch(switches::kLoginProfile)) {
profile_dir = command_line.GetSwitchValuePath(switches::kLoginProfile);
} else {
// We should never be logged in with no profile dir.
NOTREACHED();
return FilePath("");
}
relative_profile_dir = relative_profile_dir.Append(profile_dir);
return relative_profile_dir;
}
#endif
// TODO(mirandac): should not automatically be default profile.
relative_profile_dir =
relative_profile_dir.AppendASCII(chrome::kInitialProfile);
return relative_profile_dir;
}
Profile* ProfileManager::GetLastUsedProfile(const FilePath& user_data_dir) {
#if defined(OS_CHROMEOS)
// Use default login profile if user has not logged in yet.
if (!logged_in_)
return GetDefaultProfile(user_data_dir);
#endif
FilePath last_used_profile_dir(user_data_dir);
std::string last_profile_used;
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
if (local_state->HasPrefPath(prefs::kProfileLastUsed))
last_profile_used = local_state->GetString(prefs::kProfileLastUsed);
last_used_profile_dir = last_profile_used.empty() ?
last_used_profile_dir.AppendASCII(chrome::kInitialProfile) :
last_used_profile_dir.AppendASCII(last_profile_used);
return GetProfile(last_used_profile_dir);
}
std::vector<Profile*> ProfileManager::GetLastOpenedProfiles(
const FilePath& user_data_dir) {
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
std::vector<Profile*> to_return;
if (local_state->HasPrefPath(prefs::kProfilesLastActive)) {
const ListValue* profile_list =
local_state->GetList(prefs::kProfilesLastActive);
if (profile_list) {
ListValue::const_iterator it;
std::string profile;
for (it = profile_list->begin(); it != profile_list->end(); ++it) {
if (!(*it)->GetAsString(&profile) || profile.empty()) {
LOG(WARNING) << "Invalid entry in " << prefs::kProfilesLastActive;
continue;
}
to_return.push_back(GetProfile(user_data_dir.AppendASCII(profile)));
}
}
}
return to_return;
}
Profile* ProfileManager::GetDefaultProfile(const FilePath& user_data_dir) {
FilePath default_profile_dir(user_data_dir);
default_profile_dir = default_profile_dir.Append(GetInitialProfileDir());
#if defined(OS_CHROMEOS)
if (!logged_in_) {
Profile* profile = GetProfile(default_profile_dir);
// For cros, return the OTR profile so we never accidentally keep
// user data in an unencrypted profile. But doing this makes
// many of the browser and ui tests fail. We do return the OTR profile
// if the login-profile switch is passed so that we can test this.
// TODO(davemoore) Fix the tests so they allow OTR profiles.
if (ShouldGoOffTheRecord())
return profile->GetOffTheRecordProfile();
return profile;
}
ProfileInfo* profile_info = GetProfileInfoByPath(default_profile_dir);
// Fallback to default off-the-record profile, if user profile has not fully
// loaded yet.
if (profile_info && !profile_info->created)
default_profile_dir = GetDefaultProfileDir(user_data_dir);
#endif
return GetProfile(default_profile_dir);
}
bool ProfileManager::IsValidProfile(Profile* profile) {
for (ProfilesInfoMap::iterator iter = profiles_info_.begin();
iter != profiles_info_.end(); ++iter) {
if (iter->second->created) {
Profile* candidate = iter->second->profile.get();
if (candidate == profile ||
(candidate->HasOffTheRecordProfile() &&
candidate->GetOffTheRecordProfile() == profile)) {
return true;
}
}
}
return false;
}
std::vector<Profile*> ProfileManager::GetLoadedProfiles() const {
std::vector<Profile*> profiles;
for (ProfilesInfoMap::const_iterator iter = profiles_info_.begin();
iter != profiles_info_.end(); ++iter) {
if (iter->second->created)
profiles.push_back(iter->second->profile.get());
}
return profiles;
}
Profile* ProfileManager::GetProfile(const FilePath& profile_dir) {
// If the profile is already loaded (e.g., chrome.exe launched twice), just
// return it.
Profile* profile = GetProfileByPath(profile_dir);
if (NULL != profile)
return profile;
profile = CreateProfileHelper(profile_dir);
DCHECK(profile);
if (profile) {
bool result = AddProfile(profile);
DCHECK(result);
}
return profile;
}
void ProfileManager::CreateProfileAsync(
const FilePath& profile_path,
const CreateCallback& callback,
const string16& name,
const string16& icon_url,
bool is_managed) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Make sure that this profile is not pending deletion.
if (std::find(ProfilesToDelete().begin(), ProfilesToDelete().end(),
profile_path) != ProfilesToDelete().end()) {
callback.Run(NULL, Profile::CREATE_STATUS_FAIL);
return;
}
ProfilesInfoMap::iterator iter = profiles_info_.find(profile_path);
if (iter != profiles_info_.end()) {
ProfileInfo* info = iter->second.get();
if (info->created) {
// Profile has already been created. Run callback immediately.
callback.Run(info->profile.get(), Profile::CREATE_STATUS_INITIALIZED);
} else {
// Profile is being created. Add callback to list.
info->callbacks.push_back(callback);
}
} else {
// Initiate asynchronous creation process.
ProfileInfo* info =
RegisterProfile(CreateProfileAsyncHelper(profile_path, this), false);
ProfileInfoCache& cache = GetProfileInfoCache();
// Get the icon index from the user's icon url
size_t icon_index;
std::string icon_url_std = UTF16ToASCII(icon_url);
if (cache.IsDefaultAvatarIconUrl(icon_url_std, &icon_index)) {
// add profile to cache with user selected name and avatar
cache.AddProfileToCache(profile_path, name, string16(), icon_index,
is_managed);
}
info->callbacks.push_back(callback);
}
}
// static
void ProfileManager::CreateDefaultProfileAsync(const CreateCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ProfileManager* profile_manager = g_browser_process->profile_manager();
FilePath default_profile_dir = profile_manager->user_data_dir_;
// TODO(mirandac): current directory will not always be default in the future
default_profile_dir = default_profile_dir.Append(
profile_manager->GetInitialProfileDir());
profile_manager->CreateProfileAsync(
default_profile_dir, callback, string16(), string16(), false);
}
bool ProfileManager::AddProfile(Profile* profile) {
DCHECK(profile);
// Make sure that we're not loading a profile with the same ID as a profile
// that's already loaded.
if (GetProfileByPath(profile->GetPath())) {
NOTREACHED() << "Attempted to add profile with the same path (" <<
profile->GetPath().value() <<
") as an already-loaded profile.";
return false;
}
RegisterProfile(profile, true);
DoFinalInit(profile, ShouldGoOffTheRecord());
return true;
}
ProfileManager::ProfileInfo* ProfileManager::RegisterProfile(
Profile* profile,
bool created) {
ProfileInfo* info = new ProfileInfo(profile, created);
profiles_info_.insert(
std::make_pair(profile->GetPath(), linked_ptr<ProfileInfo>(info)));
return info;
}
ProfileManager::ProfileInfo* ProfileManager::GetProfileInfoByPath(
const FilePath& path) const {
ProfilesInfoMap::const_iterator iter = profiles_info_.find(path);
return (iter == profiles_info_.end()) ? NULL : iter->second.get();
}
Profile* ProfileManager::GetProfileByPath(const FilePath& path) const {
ProfileInfo* profile_info = GetProfileInfoByPath(path);
return profile_info ? profile_info->profile.get() : NULL;
}
// static
void ProfileManager::FindOrCreateNewWindowForProfile(
Profile* profile,
chrome::startup::IsProcessStartup process_startup,
chrome::startup::IsFirstRun is_first_run,
chrome::HostDesktopType desktop_type,
bool always_create) {
#if defined(OS_IOS)
NOTREACHED();
#else
DCHECK(profile);
if (!always_create) {
Browser* browser = chrome::FindTabbedBrowser(profile, false, desktop_type);
if (browser) {
browser->window()->Activate();
return;
}
}
content::RecordAction(UserMetricsAction("NewWindow"));
CommandLine command_line(CommandLine::NO_PROGRAM);
int return_code;
StartupBrowserCreator browser_creator;
browser_creator.LaunchBrowser(command_line, profile, FilePath(),
process_startup, is_first_run, &return_code);
#endif // defined(OS_IOS)
}
void ProfileManager::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
#if defined(OS_CHROMEOS)
if (type == chrome::NOTIFICATION_LOGIN_USER_CHANGED) {
logged_in_ = true;
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (!command_line.HasSwitch(switches::kTestType)) {
// If we don't have a mounted profile directory we're in trouble.
// TODO(davemoore) Once we have better api this check should ensure that
// our profile directory is the one that's mounted, and that it's mounted
// as the current user.
chromeos::DBusThreadManager::Get()->GetCryptohomeClient()->IsMounted(
base::Bind(&CheckCryptohomeIsMounted));
// Confirm that we hadn't loaded the new profile previously.
FilePath default_profile_dir =
user_data_dir_.Append(GetInitialProfileDir());
CHECK(!GetProfileByPath(default_profile_dir))
<< "The default profile was loaded before we mounted the cryptohome.";
}
return;
}
#endif
bool save_active_profiles = false;
switch (type) {
case chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST: {
// Ignore any browsers closing from now on.
closing_all_browsers_ = true;
break;
}
case chrome::NOTIFICATION_BROWSER_CLOSE_CANCELLED: {
// This will cancel the shutdown process, so the active profiles are
// tracked again. Also, as the active profiles may have changed (i.e. if
// some windows were closed) we save the current list of active profiles
// again.
closing_all_browsers_ = false;
save_active_profiles = true;
break;
}
case chrome::NOTIFICATION_BROWSER_OPENED: {
Browser* browser = content::Source<Browser>(source).ptr();
DCHECK(browser);
Profile* profile = browser->profile();
DCHECK(profile);
if (!profile->IsOffTheRecord() && ++browser_counts_[profile] == 1) {
active_profiles_.push_back(profile);
save_active_profiles = true;
}
// If browsers are opening, we can't be closing all the browsers. This
// can happen if the application was exited, but background mode or
// packaged apps prevented the process from shutting down, and then
// a new browser window was opened.
closing_all_browsers_ = false;
break;
}
case chrome::NOTIFICATION_BROWSER_CLOSED: {
Browser* browser = content::Source<Browser>(source).ptr();
DCHECK(browser);
Profile* profile = browser->profile();
DCHECK(profile);
if (!profile->IsOffTheRecord() && --browser_counts_[profile] == 0) {
active_profiles_.erase(std::find(active_profiles_.begin(),
active_profiles_.end(), profile));
save_active_profiles = !closing_all_browsers_;
}
break;
}
default: {
NOTREACHED();
break;
}
}
if (save_active_profiles) {
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
ListPrefUpdate update(local_state, prefs::kProfilesLastActive);
ListValue* profile_list = update.Get();
profile_list->Clear();
// crbug.com/120112 -> several non-incognito profiles might have the same
// GetPath().BaseName(). In that case, we cannot restore both
// profiles. Include each base name only once in the last active profile
// list.
std::set<std::string> profile_paths;
std::vector<Profile*>::const_iterator it;
for (it = active_profiles_.begin(); it != active_profiles_.end(); ++it) {
std::string profile_path = (*it)->GetPath().BaseName().MaybeAsASCII();
if (profile_paths.find(profile_path) == profile_paths.end()) {
profile_paths.insert(profile_path);
profile_list->Append(new StringValue(profile_path));
}
}
}
}
// static
bool ProfileManager::IsImportProcess(const CommandLine& command_line) {
return (command_line.HasSwitch(switches::kImport) ||
command_line.HasSwitch(switches::kImportFromFile));
}
// static
bool ProfileManager::DidPerformProfileImport() {
return did_perform_profile_import;
}
void ProfileManager::SetWillImport() {
will_import_ = true;
}
void ProfileManager::OnImportFinished(Profile* profile) {
will_import_ = false;
did_perform_profile_import = true;
DCHECK(profile);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_IMPORT_FINISHED,
content::Source<Profile>(profile),
content::NotificationService::NoDetails());
}
#if !defined(OS_ANDROID) && !defined(OS_IOS)
ProfileManager::BrowserListObserver::BrowserListObserver(
ProfileManager* manager)
: profile_manager_(manager) {
BrowserList::AddObserver(this);
}
ProfileManager::BrowserListObserver::~BrowserListObserver() {
BrowserList::RemoveObserver(this);
}
void ProfileManager::BrowserListObserver::OnBrowserAdded(
Browser* browser) {}
void ProfileManager::BrowserListObserver::OnBrowserRemoved(
Browser* browser) {}
void ProfileManager::BrowserListObserver::OnBrowserSetLastActive(
Browser* browser) {
// If all browsers are being closed (e.g. the user is in the process of
// shutting down), this event will be fired after each browser is
// closed. This does not represent a user intention to change the active
// browser so is not handled here.
if (profile_manager_->closing_all_browsers_)
return;
Profile* last_active = browser->profile();
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
// Only keep track of profiles that we are managing; tests may create others.
if (profile_manager_->profiles_info_.find(
last_active->GetPath()) != profile_manager_->profiles_info_.end()) {
local_state->SetString(prefs::kProfileLastUsed,
last_active->GetPath().BaseName().MaybeAsASCII());
}
}
#endif // !defined(OS_ANDROID) && !defined(OS_IOS)
void ProfileManager::DoFinalInit(Profile* profile, bool go_off_the_record) {
DoFinalInitForServices(profile, go_off_the_record);
InitProfileUserPrefs(profile);
AddProfileToCache(profile);
DoFinalInitLogging(profile);
ProfileMetrics::LogNumberOfProfiles(this, ProfileMetrics::ADD_PROFILE_EVENT);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PROFILE_ADDED,
content::Source<Profile>(profile),
content::NotificationService::NoDetails());
}
void ProfileManager::DoFinalInitForServices(Profile* profile,
bool go_off_the_record) {
#if defined(ENABLE_EXTENSIONS)
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (!IsImportProcess(command_line)) {
extensions::ExtensionSystem::Get(profile)->InitForRegularProfile(
!go_off_the_record);
// During tests, when |profile| is an instance of TestingProfile,
// ExtensionSystem might not create an ExtensionService.
if (extensions::ExtensionSystem::Get(profile)->extension_service()) {
profile->GetHostContentSettingsMap()->RegisterExtensionService(
extensions::ExtensionSystem::Get(profile)->extension_service());
}
}
#endif
}
void ProfileManager::DoFinalInitLogging(Profile* profile) {
// Count number of extensions in this profile.
int extension_count = -1;
#if defined(ENABLE_EXTENSIONS)
ExtensionService* extension_service = profile->GetExtensionService();
if (extension_service)
extension_count = extension_service->GetAppIds().size();
#endif
// Log the profile size after a reasonable startup delay.
BrowserThread::PostDelayedTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&ProfileSizeTask, profile->GetPath(), extension_count),
base::TimeDelta::FromSeconds(112));
}
Profile* ProfileManager::CreateProfileHelper(const FilePath& path) {
return Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS);
}
Profile* ProfileManager::CreateProfileAsyncHelper(const FilePath& path,
Delegate* delegate) {
return Profile::CreateProfile(path,
delegate,
Profile::CREATE_MODE_ASYNCHRONOUS);
}
void ProfileManager::OnProfileCreated(Profile* profile,
bool success,
bool is_new_profile) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ProfilesInfoMap::iterator iter = profiles_info_.find(profile->GetPath());
DCHECK(iter != profiles_info_.end());
ProfileInfo* info = iter->second.get();
std::vector<CreateCallback> callbacks;
info->callbacks.swap(callbacks);
// Invoke CREATED callback for normal profiles.
bool go_off_the_record = ShouldGoOffTheRecord();
if (success && !go_off_the_record)
RunCallbacks(callbacks, profile, Profile::CREATE_STATUS_CREATED);
// Perform initialization.
if (success) {
DoFinalInit(profile, go_off_the_record);
if (go_off_the_record)
profile = profile->GetOffTheRecordProfile();
info->created = true;
} else {
profile = NULL;
profiles_info_.erase(iter);
}
// Invoke CREATED callback for incognito profiles.
if (profile && go_off_the_record)
RunCallbacks(callbacks, profile, Profile::CREATE_STATUS_CREATED);
// Invoke INITIALIZED or FAIL for all profiles.
RunCallbacks(callbacks, profile,
profile ? Profile::CREATE_STATUS_INITIALIZED :
Profile::CREATE_STATUS_FAIL);
}
FilePath ProfileManager::GenerateNextProfileDirectoryPath() {
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
DCHECK(IsMultipleProfilesEnabled());
// Create the next profile in the next available directory slot.
int next_directory = local_state->GetInteger(prefs::kProfilesNumCreated);
std::string profile_name = chrome::kMultiProfileDirPrefix;
profile_name.append(base::IntToString(next_directory));
FilePath new_path = user_data_dir_;
#if defined(OS_WIN)
new_path = new_path.Append(ASCIIToUTF16(profile_name));
#else
new_path = new_path.Append(profile_name);
#endif
local_state->SetInteger(prefs::kProfilesNumCreated, ++next_directory);
return new_path;
}
// TODO(robertshield): ProfileManager should not be opening windows and should
// not have to care about HostDesktopType. See http://crbug.com/153864
// static
void ProfileManager::CreateMultiProfileAsync(
const string16& name,
const string16& icon_url,
const CreateCallback& callback,
chrome::HostDesktopType desktop_type,
bool is_managed) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ProfileManager* profile_manager = g_browser_process->profile_manager();
FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();
profile_manager->CreateProfileAsync(new_path,
base::Bind(&OnOpenWindowForNewProfile,
desktop_type,
callback),
name,
icon_url,
is_managed);
}
// static
void ProfileManager::RegisterPrefs(PrefServiceSimple* prefs) {
prefs->RegisterStringPref(prefs::kProfileLastUsed, "");
prefs->RegisterIntegerPref(prefs::kProfilesNumCreated, 1);
prefs->RegisterListPref(prefs::kProfilesLastActive);
}
size_t ProfileManager::GetNumberOfProfiles() {
return GetProfileInfoCache().GetNumberOfProfiles();
}
bool ProfileManager::CompareProfilePathAndName(
const ProfileManager::ProfilePathAndName& pair1,
const ProfileManager::ProfilePathAndName& pair2) {
int name_compare = pair1.second.compare(pair2.second);
if (name_compare < 0) {
return true;
} else if (name_compare > 0) {
return false;
} else {
return pair1.first < pair2.first;
}
}
ProfileInfoCache& ProfileManager::GetProfileInfoCache() {
if (!profile_info_cache_.get()) {
profile_info_cache_.reset(new ProfileInfoCache(
g_browser_process->local_state(), user_data_dir_));
}
return *profile_info_cache_.get();
}
ProfileShortcutManager* ProfileManager::profile_shortcut_manager() {
return profile_shortcut_manager_.get();
}
void ProfileManager::AddProfileToCache(Profile* profile) {
ProfileInfoCache& cache = GetProfileInfoCache();
if (profile->GetPath().DirName() != cache.GetUserDataDir())
return;
if (cache.GetIndexOfProfileWithPath(profile->GetPath()) != std::string::npos)
return;
string16 username = UTF8ToUTF16(profile->GetPrefs()->GetString(
prefs::kGoogleServicesUsername));
// Profile name and avatar are set by InitProfileUserPrefs and stored in the
// profile. Use those values to setup the cache entry.
string16 profile_name = UTF8ToUTF16(profile->GetPrefs()->GetString(
prefs::kProfileName));
size_t icon_index = profile->GetPrefs()->GetInteger(
prefs::kProfileAvatarIndex);
bool is_managed = profile->GetPrefs()->GetBoolean(prefs::kProfileIsManaged);
cache.AddProfileToCache(profile->GetPath(),
profile_name,
username,
icon_index,
is_managed);
}
void ProfileManager::InitProfileUserPrefs(Profile* profile) {
ProfileInfoCache& cache = GetProfileInfoCache();
if (profile->GetPath().DirName() != cache.GetUserDataDir())
return;
size_t avatar_index;
std::string profile_name;
bool is_managed = false;
size_t profile_cache_index =
cache.GetIndexOfProfileWithPath(profile->GetPath());
// If the cache has an entry for this profile, use the cache data.
if (profile_cache_index != std::string::npos) {
avatar_index =
cache.GetAvatarIconIndexOfProfileAtIndex(profile_cache_index);
profile_name =
UTF16ToUTF8(cache.GetNameOfProfileAtIndex(profile_cache_index));
is_managed = cache.ProfileIsManagedAtIndex(profile_cache_index);
} else if (profile->GetPath() ==
GetDefaultProfileDir(cache.GetUserDataDir())) {
avatar_index = 0;
profile_name = l10n_util::GetStringUTF8(IDS_DEFAULT_PROFILE_NAME);
} else {
avatar_index = cache.ChooseAvatarIconIndexForNewProfile();
profile_name = UTF16ToUTF8(cache.ChooseNameForNewProfile(avatar_index));
}
if (!profile->GetPrefs()->HasPrefPath(prefs::kProfileAvatarIndex))
profile->GetPrefs()->SetInteger(prefs::kProfileAvatarIndex, avatar_index);
if (!profile->GetPrefs()->HasPrefPath(prefs::kProfileName))
profile->GetPrefs()->SetString(prefs::kProfileName, profile_name);
if (!profile->GetPrefs()->HasPrefPath(prefs::kProfileIsManaged)) {
profile->GetPrefs()->SetBoolean(prefs::kProfileIsManaged, is_managed);
#if defined(ENABLE_MANAGED_USERS)
ManagedUserServiceFactory::GetForProfile(profile)->Init();
#else
DCHECK(!is_managed);
#endif
}
}
bool ProfileManager::ShouldGoOffTheRecord() {
bool go_off_the_record = false;
#if defined(OS_CHROMEOS)
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (!logged_in_ &&
(!command_line.HasSwitch(switches::kTestType) ||
command_line.HasSwitch(switches::kLoginProfile))) {
go_off_the_record = true;
}
#endif
return go_off_the_record;
}
// TODO(robertshield): ProfileManager should not be opening windows and should
// not have to care about HostDesktopType. See http://crbug.com/153864
void ProfileManager::ScheduleProfileForDeletion(
const FilePath& profile_dir,
chrome::HostDesktopType desktop_type) {
DCHECK(IsMultipleProfilesEnabled());
// If we're deleting the last profile, then create a new profile in its
// place.
ProfileInfoCache& cache = GetProfileInfoCache();
if (cache.GetNumberOfProfiles() == 1) {
FilePath new_path = GenerateNextProfileDirectoryPath();
// TODO(robertshield): This desktop type needs to come from the invoker,
// currently that involves plumbing this through web UI.
chrome::HostDesktopType desktop_type = chrome::HOST_DESKTOP_TYPE_NATIVE;
CreateProfileAsync(new_path,
base::Bind(&OnOpenWindowForNewProfile,
desktop_type,
CreateCallback()),
string16(),
string16(),
false);
}
// Update the last used profile pref before closing browser windows. This way
// the correct last used profile is set for any notification observers.
PrefService* local_state = g_browser_process->local_state();
std::string last_profile = local_state->GetString(prefs::kProfileLastUsed);
if (profile_dir.BaseName().MaybeAsASCII() == last_profile) {
for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i) {
FilePath cur_path = cache.GetPathOfProfileAtIndex(i);
if (cur_path != profile_dir) {
local_state->SetString(
prefs::kProfileLastUsed, cur_path.BaseName().MaybeAsASCII());
break;
}
}
}
// TODO(sail): Due to bug 88586 we don't delete the profile instance. Once we
// start deleting the profile instance we need to close background apps too.
Profile* profile = GetProfileByPath(profile_dir);
if (profile) {
BrowserList::CloseAllBrowsersWithProfile(profile);
// Disable sync for doomed profile.
if (ProfileSyncServiceFactory::GetInstance()->HasProfileSyncService(
profile)) {
ProfileSyncServiceFactory::GetInstance()->GetForProfile(
profile)->DisableForUser();
}
}
QueueProfileDirectoryForDeletion(profile_dir);
cache.DeleteProfileFromCache(profile_dir);
ProfileMetrics::LogNumberOfProfiles(this,
ProfileMetrics::DELETE_PROFILE_EVENT);
}
// static
bool ProfileManager::IsMultipleProfilesEnabled() {
#if defined(OS_ANDROID)
return false;
#endif
#if defined(OS_CHROMEOS)
if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kMultiProfiles))
return false;
#endif
#if defined(ENABLE_MANAGED_USERS)
if (ManagedMode::IsInManagedMode())
return false;
#endif
return true;
}
void ProfileManager::AutoloadProfiles() {
// If running in the background is disabled for the browser, do not autoload
// any profiles.
PrefService* local_state = g_browser_process->local_state();
if (!local_state->HasPrefPath(prefs::kBackgroundModeEnabled) ||
!local_state->GetBoolean(prefs::kBackgroundModeEnabled)) {
return;
}
ProfileInfoCache& cache = GetProfileInfoCache();
size_t number_of_profiles = cache.GetNumberOfProfiles();
for (size_t p = 0; p < number_of_profiles; ++p) {
if (cache.GetBackgroundStatusOfProfileAtIndex(p)) {
// If status is true, that profile is running background apps. By calling
// GetProfile, we automatically cause the profile to be loaded which will
// register it with the BackgroundModeManager.
GetProfile(cache.GetPathOfProfileAtIndex(p));
}
}
ProfileMetrics::LogNumberOfProfiles(this,
ProfileMetrics::STARTUP_PROFILE_EVENT);
}
ProfileManagerWithoutInit::ProfileManagerWithoutInit(
const FilePath& user_data_dir) : ProfileManager(user_data_dir) {
}
void ProfileManager::RegisterTestingProfile(Profile* profile,
bool add_to_cache) {
RegisterProfile(profile, true);
if (add_to_cache) {
InitProfileUserPrefs(profile);
AddProfileToCache(profile);
}
}
void ProfileManager::RunCallbacks(const std::vector<CreateCallback>& callbacks,
Profile* profile,
Profile::CreateStatus status) {
for (size_t i = 0; i < callbacks.size(); ++i)
callbacks[i].Run(profile, status);
}
ProfileManager::ProfileInfo::ProfileInfo(
Profile* profile,
bool created)
: profile(profile),
created(created) {
}
ProfileManager::ProfileInfo::~ProfileInfo() {
ProfileDestroyer::DestroyProfileWhenAppropriate(profile.release());
}
| bsd-3-clause |
MLCL/Byblo | src/main/java/uk/ac/susx/mlcl/byblo/enumerators/EnumeratorType.java | 3593 | /*
* Copyright (c) 2010-2013, University of Sussex
* 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 University of Sussex nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package uk.ac.susx.mlcl.byblo.enumerators;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
/**
* @author Hamish I A Morgan <hamish.morgan@sussex.ac.uk>
*/
public enum EnumeratorType {
Memory {
@Override
public Enumerator<String> open(@Nullable File file) throws IOException {
if (file != null && file.exists())
return MemoryBasedStringEnumerator.load(file);
else
return MemoryBasedStringEnumerator.newInstance(file);
}
@Override
public void save(Enumerator<String> enumerator) throws IOException {
assert enumerator instanceof MemoryBasedStringEnumerator;
((MemoryBasedStringEnumerator) enumerator).save();
}
@Override
public void close(Enumerator<String> enumerator) {
assert enumerator instanceof MemoryBasedStringEnumerator;
}
},
JDBM {
@Override
public Enumerator<String> open(@Nullable File file) {
if (file == null) {
return JDBMStringEnumerator.newInstance(null);
} else if (!file.exists()) {
return JDBMStringEnumerator.newInstance(file);
} else {
return JDBMStringEnumerator.load(file);
}
}
@Override
public void save(Enumerator<String> enumerator) {
assert enumerator instanceof JDBMStringEnumerator;
((JDBMStringEnumerator) enumerator).save();
}
@Override
public void close(Enumerator<String> enumerator) {
assert enumerator instanceof JDBMStringEnumerator;
((JDBMStringEnumerator) enumerator).close();
}
};
public abstract Enumerator<String> open(File file) throws IOException;
public abstract void save(Enumerator<String> enumerator) throws IOException;
public abstract void close(Enumerator<String> enumerator) ;
}
| bsd-3-clause |
epixa/Epixa | library/Epixa/Acl/AclManager.php | 4319 | <?php
/**
* Epixa Library
*/
namespace Epixa\Acl;
use Zend_Acl as Acl,
Zend_Acl_Resource_Interface as ResourceInterface,
Epixa\Acl\AclService,
Epixa\Acl\MultiRoles,
InvalidArgumentException;
/**
* @category Epixa
* @package Acl
* @copyright 2010 epixa.com - Court Ewing
* @license http://github.com/epixa/Epixa/blob/master/LICENSE New BSD
* @author Court Ewing (court@epixa.com)
*/
class AclManager
{
/**
* @var Acl
*/
protected $_acl;
/**
* @var AclService
*/
protected $_aclService;
/**
* Constructor
*
* Set the acl and acl service objects
*
* @param Acl $acl
* @param AclService $aclService
*/
public function __construct(Acl $acl, AclService $aclService)
{
$this->setAcl($acl)
->setAclService($aclService);
}
/**
* Register a new resource on the acl
*
* @param string $resource
* @return AclManager *Fluent interface*
*/
public function registerResource($resource)
{
$this->getAcl()->addResource($resource);
return $this;
}
/**
* Register multiple resources on the acl
*
* @param array $resources
* @return AclManager *Fluent interface*
*/
public function registerResources(array $resources)
{
foreach ($resources as $resource) {
$this->registerResource($resource);
}
return $this;
}
/**
* Is the specified role allowed to access the given resource
*
* @param MultiRoles|RoleInterface|string $identity
* @param string|ResourceInterface $resource
* @param null|string $privilege
* @return boolean
*/
public function isAllowed($identity, $resource, $privilege = null)
{
$acl = $this->getAcl();
if ($resource instanceof ResourceInterface) {
$resource = $resource->getResourceId();
} else if (!is_string($resource)) {
throw new InvalidArgumentException('Resource must be a string or instance of Zend_Acl_Resource_Interface');
}
// if the resource isn't in the acl, then we should add it to the acl
// and then get all of the roles and rules for it
if (!$acl->has($resource)) {
$this->getAclService()->loadResourceRules($acl, $resource);
}
$roles = $this->getIdentityRoles($identity);
// if any of the roles is allowed to access that resource, then ok
foreach ($roles as $role) {
if (!$acl->hasRole($role)) {
continue;
}
if ($acl->isAllowed($role, $resource, $privilege)) {
return true;
}
}
return false;
}
/**
* Get the roles associated with the given identity
*
* @param MultiRoles|RoleInterface|string $identity
* @return array
* @throws InvalidArgumentException If invalid identity is provided
*/
public function getIdentityRoles($identity)
{
$roles = array();
if ($identity instanceof MultiRoles) {
foreach ($identity->getRoles() as $role) {
array_push($roles, $role);
}
} else if ($identity instanceof RoleInterface || is_string($identity)) {
array_push($roles, $identity);
} else {
throw new InvalidArgumentException('Invalid model specified');
}
return $roles;
}
/**
* Get the acl instance
*
* @return Acl
*/
public function getAcl()
{
return $this->_acl;
}
/**
* Set the acl instance
*
* @param Acl $acl
* @return AclManager *Fluent interface*
*/
public function setAcl(Acl $acl)
{
$this->_acl = $acl;
return $this;
}
/**
* Get the acl service instance
*
* @return AclService
*/
public function getAclService()
{
return $this->_aclService;
}
/**
* Get the acl service instance
*
* @param AclService $service
* @return AclManager
*/
public function setAclService(AclService $service)
{
$this->_aclService = $service;
return $this;
}
} | bsd-3-clause |
thezbyg/gpick | source/uiDialogSort.cpp | 19621 | /*
* Copyright (c) 2009-2021, Albertas Vyšniauskas
* 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 software author 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.
*/
#include "uiDialogSort.h"
#include "uiListPalette.h"
#include "uiUtilities.h"
#include "ColorList.h"
#include "ColorObject.h"
#include "dynv/Map.h"
#include "GlobalState.h"
#include "ColorRYB.h"
#include "Noise.h"
#include "GenerateScheme.h"
#include "I18N.h"
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sstream>
#include <iostream>
#include <map>
using namespace std;
typedef struct DialogSortArgs{
GtkWidget *group_type;
GtkWidget *group_sensitivity;
GtkWidget *max_groups;
GtkWidget *sort_type;
GtkWidget *toggle_reverse;
GtkWidget *toggle_reverse_groups;
ColorList *sorted_color_list;
ColorList *selected_color_list;
ColorList *preview_color_list;
dynv::Ref options;
GlobalState* gs;
}DialogSortArgs;
typedef struct SortType{
const char *name;
double (*get_value)(Color *color);
}SortType;
typedef struct GroupType{
const char *name;
double (*get_group)(Color *color);
}GroupType;
static double sort_rgb_red(Color *color)
{
return color->rgb.red;
}
static double sort_rgb_green(Color *color)
{
return color->rgb.green;
}
static double sort_rgb_blue(Color *color)
{
return color->rgb.blue;
}
static double sort_rgb_grayscale(Color *color)
{
return (color->rgb.red + color->rgb.green + color->rgb.blue) / 3.0;
}
static double sort_hsl_hue(Color *color)
{
return color->rgbToHsl().hsl.hue;
}
static double sort_hsl_saturation(Color *color)
{
return color->rgbToHsl().hsl.saturation;
}
static double sort_hsl_lightness(Color *color)
{
return color->rgbToHsl().hsl.lightness;
}
static double sort_lab_lightness(Color *color)
{
return color->rgbToLabD50().lab.L;
}
static double sort_lab_a(Color *color)
{
return color->rgbToLabD50().lab.a;
}
static double sort_lab_b(Color *color)
{
return color->rgbToLabD50().lab.b;
}
static double sort_lch_lightness(Color *color)
{
return color->rgbToLchD50().lch.L;
}
static double sort_lch_chroma(Color *color)
{
return color->rgbToLchD50().lch.C;
}
static double sort_lch_hue(Color *color)
{
return color->rgbToLchD50().lch.h;
}
const SortType sort_types[] = {
{N_("RGB Red"), sort_rgb_red},
{N_("RGB Green"), sort_rgb_green},
{N_("RGB Blue"), sort_rgb_blue},
{N_("RGB Grayscale"), sort_rgb_grayscale},
{N_("HSL Hue"), sort_hsl_hue},
{N_("HSL Saturation"), sort_hsl_saturation},
{N_("HSL Lightness"), sort_hsl_lightness},
{N_("Lab Lightness"), sort_lab_lightness},
{N_("Lab A"), sort_lab_a},
{N_("Lab B"), sort_lab_b},
{N_("LCh Lightness"), sort_lch_lightness},
{N_("LCh Chroma"), sort_lch_chroma},
{N_("LCh Hue"), sort_lch_hue},
};
static double group_rgb_red(Color *color)
{
return color->rgb.red;
}
static double group_rgb_green(Color *color)
{
return color->rgb.green;
}
static double group_rgb_blue(Color *color)
{
return color->rgb.blue;
}
static double group_rgb_grayscale(Color *color)
{
return (color->rgb.red + color->rgb.green + color->rgb.blue) / 3.0;
}
static double group_hsl_hue(Color *color)
{
return color->rgbToHsl().hsl.hue;
}
static double group_hsl_saturation(Color *color)
{
return color->rgbToHsl().hsl.saturation;
}
static double group_hsl_lightness(Color *color)
{
return color->rgbToHsl().hsl.lightness;
}
static double group_lab_lightness(Color *color)
{
return color->rgbToLabD50().lab.L / 100.0;
}
static double group_lab_a(Color *color)
{
return (color->rgbToLabD50().lab.a + 145) / 290.0;
}
static double group_lab_b(Color *color)
{
return (color->rgbToLabD50().lab.b + 145) / 290.0;
}
static double group_lch_lightness(Color *color)
{
return color->rgbToLchD50().lch.L / 100.0;
}
static double group_lch_chroma(Color *color)
{
return color->rgbToLchD50().lch.C / 136.0;
}
static double group_lch_hue(Color *color)
{
return color->rgbToLchD50().lch.h / 360.0;
}
const GroupType group_types[] = {
{N_("None"), nullptr},
{N_("RGB Red"), group_rgb_red},
{N_("RGB Green"), group_rgb_green},
{N_("RGB Blue"), group_rgb_blue},
{N_("RGB Grayscale"), group_rgb_grayscale},
{N_("HSL Hue"), group_hsl_hue},
{N_("HSL Saturation"), group_hsl_saturation},
{N_("HSL Lightness"), group_hsl_lightness},
{N_("Lab Lightness"), group_lab_lightness},
{N_("Lab A"), group_lab_a},
{N_("Lab B"), group_lab_b},
{N_("LCh Lightness"), group_lch_lightness},
{N_("LCh Chroma"), group_lch_chroma},
{N_("LCh Hue"), group_lch_hue},
};
typedef struct Node{
uint32_t n_values;
uint32_t n_values_in;
double value_sum;
double distance;
Node *child[2];
Node *parent;
}Node;
typedef struct Range{
double x;
double w;
}Range;
static Node* node_new(Node *parent){
Node *n = new Node;
n->value_sum = 0;
n->distance = 0;
n->n_values = 0;
n->n_values_in = 0;
n->parent = parent;
for (int i = 0; i < 2; i++){
n->child[i] = 0;
}
return n;
}
static void node_delete(Node *node){
for (int i = 0; i < 2; i++){
if (node->child[i]){
node_delete(node->child[i]);
}
}
delete node;
}
static Node* node_copy(Node *node, Node *parent){
Node *n = node_new(0);
memcpy(n, node, sizeof(Node));
n->parent = parent;
for (int i = 0; i < 2; i++){
if (node->child[i]){
n->child[i] = node_copy(node->child[i], n);
}else{
n->child[i] = 0;
}
}
return n;
}
static uint32_t node_count_leafs(Node *node){
uint32_t r = 0;
if (node->n_values_in) r++;
for (int i = 0; i < 2; i++){
if (node->child[i])
r += node_count_leafs(node->child[i]);
}
return r;
}
static void node_leaf_callback(Node *node, void (*leaf_cb)(Node* node, void* userdata), void* userdata){
if (node->n_values_in > 0) leaf_cb(node, userdata);
for (int i = 0; i < 2; i++){
if (node->child[i])
node_leaf_callback(node->child[i], leaf_cb, userdata);
}
}
static void node_prune(Node *node){
for (int i = 0; i < 2; i++){
if (node->child[i]){
node_prune(node->child[i]);
node->child[i] = 0;
}
}
if (node->parent){
node->parent->n_values_in += node->n_values_in;
node->parent->value_sum += node->value_sum;
}
node_delete(node);
}
typedef struct PruneData{
double threshold;
double min_distance;
uint32_t n_values;
uint32_t n_values_target;
Node *prune_node;
uint32_t distant_nodes;
}PruneData;
static bool node_prune_threshold(Node *node, PruneData *prune_data, bool leave_node){
if (node->distance <= prune_data->threshold){
uint32_t values_removed;
if (leave_node){
values_removed = 0;
for (int i = 0; i < 2; i++){
if (node->child[i]){
values_removed += node_count_leafs(node->child[i]);
node_prune(node->child[i]);
node->child[i] = 0;
}
}
}else{
values_removed = node_count_leafs(node);
node_prune(node);
}
prune_data->n_values -= values_removed;
return true;
}
if (node->distance < prune_data->min_distance){
prune_data->min_distance = node->distance;
}
uint32_t n = node->n_values_in;
for (int i = 0; i < 2; i++){
if (node->child[i]){
if (node_prune_threshold(node->child[i], prune_data, false)){
node->child[i] = 0;
}
}
}
if (node->n_values_in > 0 && n == 0) prune_data->n_values++;
return false;
}
static void node_reduce(Node *node, double threshold, uintptr_t max_values){
PruneData prune_data;
prune_data.n_values = node_count_leafs(node);
prune_data.n_values_target = max_values;
prune_data.threshold = threshold;
prune_data.min_distance = node->distance;
node_prune_threshold(node, &prune_data, true);
prune_data.threshold = prune_data.min_distance;
while (prune_data.n_values > max_values){
prune_data.min_distance = node->distance;
if (node_prune_threshold(node, &prune_data, true)) break;
prune_data.threshold = prune_data.min_distance;
}
}
static Node* node_find(Node *node, Range *range, double value)
{
Range new_range;
new_range.w = range->w / 2;
int x;
if (value - range->x < new_range.w)
x = 0;
else
x = 1;
new_range.x = range->x + new_range.w * x;
if (node->child[x]){
return node_find(node->child[x], &new_range, value);
}else return node;
}
static void node_update(Node *node, Range *range, double value, uint32_t max_depth){
Range new_range;
new_range.w = range->w / 2;
node->n_values++;
node->distance += (value - (range->x + new_range.w)) * (value - (range->x + new_range.w));
if (!max_depth){
node->n_values_in++;
node->value_sum += value;
}else{
int x;
if (value - range->x < new_range.w)
x = 0;
else
x = 1;
new_range.x = range->x + new_range.w * x;
if (!node->child[x])
node->child[x] = node_new(node);
node->n_values++;
node_update(node->child[x], &new_range, value, max_depth - 1);
}
}
static void calc(DialogSortArgs *args, bool preview, int limit){
int32_t group_type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->group_type));
float group_sensitivity = static_cast<float>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->group_sensitivity)));
int max_groups = static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->max_groups)));
int32_t sort_type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->sort_type));
bool reverse = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->toggle_reverse));
bool reverse_groups = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->toggle_reverse_groups));
if (!preview){
args->options->set("group_type", group_type);
args->options->set("group_sensitivity", group_sensitivity);
args->options->set("max_groups", max_groups);
args->options->set("sort_type", sort_type);
args->options->set("reverse", reverse);
args->options->set("reverse_groups", reverse_groups);
}
ColorList *color_list;
if (preview)
color_list = args->preview_color_list;
else
color_list = args->sorted_color_list;
typedef std::multimap<double, ColorObject*> SortedColors;
typedef std::map<uintptr_t, SortedColors> GroupedSortedColors;
GroupedSortedColors grouped_sorted_colors;
typedef std::multimap<double, uintptr_t> SortedGroups;
SortedGroups sorted_groups;
const GroupType *group = &group_types[group_type];
const SortType *sort = &sort_types[sort_type];
Color in;
Node *group_nodes = node_new(0);
Range range;
range.x = 0;
range.w = 1;
int tmp_limit = limit;
if (group->get_group){
for (ColorList::iter i = args->selected_color_list->colors.begin(); i != args->selected_color_list->colors.end(); ++i){
in = (*i)->getColor();
node_update(group_nodes, &range, group->get_group(&in), 8);
if (preview){
if (tmp_limit <= 0)
break;
tmp_limit--;
}
}
}
node_reduce(group_nodes, group_sensitivity / 100.0, max_groups);
tmp_limit = limit;
for (ColorList::iter i = args->selected_color_list->colors.begin(); i != args->selected_color_list->colors.end(); ++i){
in = (*i)->getColor();
uintptr_t node_ptr = 0;
if (group->get_group){
node_ptr = reinterpret_cast<uintptr_t>(node_find(group_nodes, &range, group->get_group(&in)));
}
grouped_sorted_colors[node_ptr].insert(std::pair<double, ColorObject*>(sort->get_value(&in), *i));
if (preview){
if (tmp_limit <= 0)
break;
tmp_limit--;
}
}
node_delete(group_nodes);
for (GroupedSortedColors::iterator i = grouped_sorted_colors.begin(); i != grouped_sorted_colors.end(); ++i){
in = (*(*i).second.begin()).second->getColor();
sorted_groups.insert(std::pair<double, uintptr_t>(sort->get_value(&in), (*i).first));
}
if (reverse_groups){
for (SortedGroups::reverse_iterator i = sorted_groups.rbegin(); i != sorted_groups.rend(); ++i){
GroupedSortedColors::iterator a, b;
a = grouped_sorted_colors.lower_bound((*i).second);
b = grouped_sorted_colors.upper_bound((*i).second);
for (GroupedSortedColors::iterator j = a; j != b; ++j){
if (reverse){
for (SortedColors::reverse_iterator k = (*j).second.rbegin(); k != (*j).second.rend(); ++k){
color_list_add_color_object(color_list, (*k).second, true);
}
}else{
for (SortedColors::iterator k = (*j).second.begin(); k != (*j).second.end(); ++k){
color_list_add_color_object(color_list, (*k).second, true);
}
}
}
}
}else{
for (SortedGroups::iterator i = sorted_groups.begin(); i != sorted_groups.end(); ++i){
GroupedSortedColors::iterator a, b;
a = grouped_sorted_colors.lower_bound((*i).second);
b = grouped_sorted_colors.upper_bound((*i).second);
for (GroupedSortedColors::iterator j = a; j != b; ++j){
if (reverse){
for (SortedColors::reverse_iterator k = (*j).second.rbegin(); k != (*j).second.rend(); ++k){
color_list_add_color_object(color_list, (*k).second, true);
}
}else{
for (SortedColors::iterator k = (*j).second.begin(); k != (*j).second.end(); ++k){
color_list_add_color_object(color_list, (*k).second, true);
}
}
}
}
}
}
static void update(GtkWidget *widget, DialogSortArgs *args ){
color_list_remove_all(args->preview_color_list);
calc(args, true, 100);
}
bool dialog_sort_show(GtkWindow* parent, ColorList *selected_color_list, ColorList *sorted_color_list, GlobalState* gs)
{
DialogSortArgs *args = new DialogSortArgs;
args->gs = gs;
args->options = args->gs->settings().getOrCreateMap("gpick.group_and_sort");
args->sorted_color_list = sorted_color_list;
GtkWidget *table;
GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Group and sort"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr);
gtk_window_set_default_size(GTK_WINDOW(dialog), args->options->getInt32("window.width", -1), args->options->getInt32("window.height", -1));
gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1);
gint table_y;
table = gtk_table_new(4, 4, FALSE);
table_y = 0;
gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Group type:"),0,0.5,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5);
args->group_type = gtk_combo_box_text_new();
for (uint32_t i = 0; i < sizeof(group_types) / sizeof(GroupType); i++){
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(args->group_type), _(group_types[i].name));
}
gtk_combo_box_set_active(GTK_COMBO_BOX(args->group_type), args->options->getInt32("group_type", 0));
g_signal_connect(G_OBJECT(args->group_type), "changed", G_CALLBACK(update), args);
gtk_table_attach(GTK_TABLE(table), args->group_type,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0);
table_y++;
gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Grouping sensitivity:"),0,0,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5);
args->group_sensitivity = gtk_spin_button_new_with_range(0, 100, 0.01);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->group_sensitivity), args->options->getFloat("group_sensitivity", 50));
gtk_table_attach(GTK_TABLE(table), args->group_sensitivity,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0);
g_signal_connect(G_OBJECT(args->group_sensitivity), "value-changed", G_CALLBACK(update), args);
table_y++;
gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Maximum number of groups:"),0,0,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5);
args->max_groups = gtk_spin_button_new_with_range(1, 255, 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->max_groups), args->options->getInt32("max_groups", 10));
gtk_table_attach(GTK_TABLE(table), args->max_groups,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0);
g_signal_connect(G_OBJECT(args->max_groups), "value-changed", G_CALLBACK(update), args);
table_y++;
gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Sort type:"),0,0.5,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5);
args->sort_type = gtk_combo_box_text_new();
for (uint32_t i = 0; i < sizeof(sort_types) / sizeof(SortType); i++){
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(args->sort_type), _(sort_types[i].name));
}
gtk_combo_box_set_active(GTK_COMBO_BOX(args->sort_type), args->options->getInt32("sort_type", 0));
g_signal_connect (G_OBJECT (args->sort_type), "changed", G_CALLBACK(update), args);
gtk_table_attach(GTK_TABLE(table), args->sort_type,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0);
table_y++;
args->toggle_reverse_groups = gtk_check_button_new_with_mnemonic(_("_Reverse group order"));
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->toggle_reverse_groups), args->options->getBool("reverse_groups", false));
gtk_table_attach(GTK_TABLE(table), args->toggle_reverse_groups,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0);
g_signal_connect (G_OBJECT(args->toggle_reverse_groups), "toggled", G_CALLBACK(update), args);
table_y++;
args->toggle_reverse = gtk_check_button_new_with_mnemonic(_("_Reverse order inside groups"));
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->toggle_reverse), args->options->getBool("reverse", false));
gtk_table_attach(GTK_TABLE(table), args->toggle_reverse,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0);
g_signal_connect (G_OBJECT(args->toggle_reverse), "toggled", G_CALLBACK(update), args);
table_y++;
GtkWidget* preview_expander;
ColorList* preview_color_list = nullptr;
gtk_table_attach(GTK_TABLE(table), preview_expander = palette_list_preview_new(gs, true, args->options->getBool("show_preview", true), gs->getColorList(), &preview_color_list), 0, 4, table_y, table_y + 1 , GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 5, 5);
table_y++;
args->selected_color_list = selected_color_list;
args->preview_color_list = preview_color_list;
update(0, args);
gtk_widget_show_all(table);
setDialogContent(dialog, table);
bool retval = false;
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK){
calc(args, false, 0);
retval = true;
}
gint width, height;
gtk_window_get_size(GTK_WINDOW(dialog), &width, &height);
args->options->set("window.width", width);
args->options->set("window.height", height);
args->options->set<bool>("show_preview", gtk_expander_get_expanded(GTK_EXPANDER(preview_expander)));
gtk_widget_destroy(dialog);
color_list_destroy(args->preview_color_list);
delete args;
return retval;
}
| bsd-3-clause |
Arrayword/Phexcore | public/includes/Phexcore/Exception/FileNotFoundException.php | 217 | <?php
/**
* Phexcore (http://phexcore.com/)
*
* @copyright Copyright (c) 2014 Arrayword (http://arrayword.com/)
*/
namespace Phexcore\Exception;
use Exception;
class FileNotFoundException extends Exception
{
}
| bsd-3-clause |
fdoray/libtrace | src/parser/decoder_unittest.cc | 6913 | // Copyright (c) 2014 The LibTrace Authors.
// 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 <organization> 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 <COPYRIGHT HOLDER> 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 "parser/decoder.h"
#include "gtest/gtest.h"
#include "event/value.h"
namespace parser {
namespace {
using event::ArrayValue;
using event::CharValue;
using event::IntValue;
using event::LongValue;
using event::StringValue;
using event::WStringValue;
using event::Value;
const char kSmallBuffer[] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
size_t kSmallBufferLength = sizeof(kSmallBuffer) / sizeof(char);
} // namespace
TEST(DecoderTest, Constructor) {
Decoder decoder(&kSmallBuffer[0], kSmallBufferLength);
EXPECT_EQ(kSmallBufferLength, decoder.RemainingBytes());
}
TEST(DecoderTest, DecodeChar) {
Decoder decoder(&kSmallBuffer[0], kSmallBufferLength);
std::unique_ptr<CharValue> value(decoder.Decode<CharValue>());
EXPECT_EQ(event::VALUE_CHAR, value->GetType());
EXPECT_EQ(0x01, CharValue::GetValue(value.get()));
EXPECT_EQ(kSmallBufferLength - 1U, decoder.RemainingBytes());
}
TEST(DecoderTest, DecodeInt) {
Decoder decoder(&kSmallBuffer[0], kSmallBufferLength);
std::unique_ptr<IntValue> value(decoder.Decode<IntValue>());
EXPECT_EQ(event::VALUE_INT, value->GetType());
EXPECT_EQ(0x04030201, IntValue::GetValue(value.get()));
EXPECT_EQ(kSmallBufferLength - 4U, decoder.RemainingBytes());
}
TEST(DecoderTest, DecodeLong) {
Decoder decoder(&kSmallBuffer[0], kSmallBufferLength);
std::unique_ptr<LongValue> value(decoder.Decode<LongValue>());
EXPECT_EQ(event::VALUE_LONG, value->GetType());
EXPECT_EQ(0x0807060504030201LL, LongValue::GetValue(value.get()));
EXPECT_EQ(kSmallBufferLength - 8U, decoder.RemainingBytes());
}
TEST(DecoderTest, DecodeEmptyFails) {
Decoder decoder(&kSmallBuffer[0], 0);
std::unique_ptr<IntValue> value(decoder.Decode<IntValue>());
EXPECT_EQ(NULL, value.get());
}
TEST(DecoderTest, DecodeTooSmallFails) {
Decoder decoder(&kSmallBuffer[0], 2);
std::unique_ptr<IntValue> value(decoder.Decode<IntValue>());
EXPECT_EQ(NULL, value.get());
}
TEST(DecoderTest, DecodeArrayChar) {
Decoder decoder(&kSmallBuffer[0], kSmallBufferLength);
std::unique_ptr<ArrayValue> value(decoder.DecodeArray<CharValue>(4));
EXPECT_EQ(event::VALUE_ARRAY, value->GetType());
EXPECT_EQ(4U, ArrayValue::Cast(value.get())->Length());
EXPECT_EQ(kSmallBufferLength - 4U, decoder.RemainingBytes());
for (int i = 0; i < 4; ++i) {
char element = CharValue::GetValue(ArrayValue::Cast(value.get())->at(i));
EXPECT_EQ(i + 1, element);
}
}
TEST(DecoderTest, DecodeEmptyArray) {
Decoder decoder(&kSmallBuffer[0], kSmallBufferLength);
std::unique_ptr<ArrayValue> value(decoder.DecodeArray<CharValue>(0));
EXPECT_EQ(event::VALUE_ARRAY, value->GetType());
EXPECT_EQ(0U, ArrayValue::Cast(value.get())->Length());
EXPECT_EQ(kSmallBufferLength, decoder.RemainingBytes());
}
TEST(DecoderTest, DecodeString) {
const char original[] = "This is a test.";
Decoder decoder(&original[0], sizeof(original) / sizeof(char));
std::unique_ptr<StringValue> value(decoder.DecodeString());
EXPECT_EQ(event::VALUE_STRING, value->GetType());
EXPECT_EQ(0U, decoder.RemainingBytes());
EXPECT_STREQ(original, StringValue::GetValue(value.get()).c_str());
}
TEST(DecoderTest, DecodeStringTemplate) {
const char original[] = "This is a test.";
Decoder decoder(&original[0], sizeof(original) / sizeof(char));
std::unique_ptr<StringValue> value(decoder.Decode<StringValue>());
EXPECT_EQ(event::VALUE_STRING, value->GetType());
EXPECT_EQ(0U, decoder.RemainingBytes());
EXPECT_STREQ(original, StringValue::GetValue(value.get()).c_str());
}
TEST(DecoderTest, DecodeWString) {
const wchar_t original[] = L"This is a test.";
Decoder decoder(reinterpret_cast<const char*>(&original[0]),
sizeof(original) / sizeof(char));
std::unique_ptr<WStringValue> value(decoder.DecodeWString());
EXPECT_EQ(event::VALUE_WSTRING, value->GetType());
EXPECT_EQ(0U, decoder.RemainingBytes());
EXPECT_EQ(0, WStringValue::GetValue(value.get()).compare(original));
}
TEST(DecoderTest, DecodeWStringTemplate) {
const wchar_t original[] = L"This is a test.";
Decoder decoder(reinterpret_cast<const char*>(&original[0]),
sizeof(original) / sizeof(char));
std::unique_ptr<WStringValue> value(decoder.Decode<WStringValue>());
EXPECT_EQ(event::VALUE_WSTRING, value->GetType());
EXPECT_EQ(0U, decoder.RemainingBytes());
EXPECT_EQ(0, WStringValue::GetValue(value.get()).compare(original));
}
TEST(DecoderTest, DecodeW16String) {
const char original[] = "T\0h\0i\0s\0 \0i\0s\0 \0a\0 \0t\0e\0s\0t\0.\0\0";
const wchar_t expected[] = L"This is a test.";
Decoder decoder(&original[0], sizeof(original) / sizeof(char));
std::unique_ptr<WStringValue> value(decoder.DecodeW16String());
EXPECT_EQ(event::VALUE_WSTRING, value->GetType());
EXPECT_EQ(0U, decoder.RemainingBytes());
EXPECT_EQ(0, WStringValue::GetValue(value.get()).compare(expected));
}
TEST(DecoderTest, DecodeFixedW16String) {
const char original[] = "T\0e\0s\0t\0.\0\0\0\0\0\0";
const wchar_t expected[] = L"Test.";
Decoder decoder(&original[0], sizeof(original) / sizeof(char));
std::unique_ptr<WStringValue> value(decoder.DecodeFixedW16String(8));
EXPECT_EQ(event::VALUE_WSTRING, value->GetType());
EXPECT_EQ(0U, decoder.RemainingBytes());
EXPECT_EQ(0, WStringValue::GetValue(value.get()).compare(expected));
}
} // namespace parser
| bsd-3-clause |
mterwoord/uwp-diagnostics | Sources/UwpDiagnostics/App.xaml.cs | 3986 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace UwpDiagnostics
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| bsd-3-clause |
reqT/reqT-syntax | src/org/fife/ui/rsyntaxtextarea/TokenIterator.java | 1844 | /*
* 08/28/2013
*
* TokenIterator.java - An iterator over the Tokens in an RSyntaxDocument.
*
* This library is distributed under a modified BSD license. See the included
* RSyntaxTextArea.License.txt file for details.
*/
package org.fife.ui.rsyntaxtextarea;
import java.util.Iterator;
/**
* Allows you to iterate through all paintable tokens in an
* <code>RSyntaxDocument</code>.
*
* @author Robert Futrell
* @version 1.0
*/
class TokenIterator implements Iterator<Token> {
private RSyntaxDocument doc;
private int curLine;
private Token token;
/**
* Constructor.
*
* @param doc The document whose tokens we should iterate over.
*/
public TokenIterator(RSyntaxDocument doc) {
this.doc = doc;
token = doc.getTokenListForLine(0);
}
private int getLineCount() {
return doc.getDefaultRootElement().getElementCount();
}
/**
* Returns whether any more paintable tokens are in the document.
*
* @return Whether there are any more paintable tokens.
* @see #next()
*/
public boolean hasNext() {
return token!=null;
}
/**
* Returns the next paintable token in the document.
*
* @return The next paintable token in the document.
* @see #hasNext()
*/
public Token next() {
Token t = token;
if (token!=null) {
if (token.isPaintable()) {
token = token.getNextToken();
int lineCount = getLineCount();
while (token!=null && !token.isPaintable() &&
++curLine<lineCount) {
t = new TokenImpl(t);
token = doc.getTokenListForLine(curLine);
}
}
else {
token = null;
}
}
return t;
}
/**
* Always throws {@link UnsupportedOperationException}, as
* <code>Token</code> removal is not supported.
*
* @throws UnsupportedOperationException always.
*/
public void remove() {
throw new UnsupportedOperationException();
}
} | bsd-3-clause |
youtube/cobalt | third_party/devtools/front_end/ui/TextEditor.js | 3074 | // Copyright 2016 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.
/**
* @interface
*/
export class TextEditorFactory {
/**
* @param {!UI.TextEditor.Options} options
* @return {!TextEditor}
*/
createEditor(options) {}
}
/**
* @interface
*/
export class TextEditor extends Common.EventTarget {
/**
* @return {!UI.Widget}
*/
widget() {
}
/**
* @return {!TextUtils.TextRange}
*/
fullRange() {
}
/**
* @return {!TextUtils.TextRange}
*/
selection() {
}
/**
* @param {!TextUtils.TextRange} selection
*/
setSelection(selection) {
}
/**
* @param {!TextUtils.TextRange=} textRange
* @return {string}
*/
text(textRange) {
}
/**
* @return {string}
*/
textWithCurrentSuggestion() {
}
/**
* @param {string} text
*/
setText(text) {
}
/**
* @param {number} lineNumber
* @return {string}
*/
line(lineNumber) {
}
newlineAndIndent() {
}
/**
* @param {function(!KeyboardEvent)} handler
*/
addKeyDownHandler(handler) {
}
/**
* @param {?UI.AutocompleteConfig} config
*/
configureAutocomplete(config) {
}
clearAutocomplete() {
}
/**
* @param {number} lineNumber
* @param {number} columnNumber
* @return {!{x: number, y: number}}
*/
visualCoordinates(lineNumber, columnNumber) {
}
/**
* @param {number} lineNumber
* @param {number} columnNumber
* @return {?{startColumn: number, endColumn: number, type: string}}
*/
tokenAtTextPosition(lineNumber, columnNumber) {
}
/**
* @param {string} placeholder
*/
setPlaceholder(placeholder) {}
}
/** @enum {symbol} */
export const Events = {
CursorChanged: Symbol('CursorChanged'),
TextChanged: Symbol('TextChanged'),
SuggestionChanged: Symbol('SuggestionChanged')
};
/* Legacy exported object*/
self.UI = self.UI || {};
/* Legacy exported object*/
UI = UI || {};
/** @interface */
UI.TextEditor = TextEditor;
/** @interface */
UI.TextEditorFactory = TextEditorFactory;
/** @enum {symbol} */
UI.TextEditor.Events = Events;
/**
* @typedef {{
* bracketMatchingSetting: (!Common.Setting|undefined),
* devtoolsAccessibleName: (string|undefined),
* lineNumbers: boolean,
* lineWrapping: boolean,
* mimeType: (string|undefined),
* autoHeight: (boolean|undefined),
* padBottom: (boolean|undefined),
* maxHighlightLength: (number|undefined),
* placeholder: (string|undefined)
* }}
*/
UI.TextEditor.Options;
/**
* @typedef {{
* substituteRangeCallback: ((function(number, number):?TextUtils.TextRange)|undefined),
* tooltipCallback: ((function(number, number):!Promise<?Element>)|undefined),
* suggestionsCallback: ((function(!TextUtils.TextRange, !TextUtils.TextRange, boolean=):?Promise.<!UI.SuggestBox.Suggestions>)|undefined),
* isWordChar: ((function(string):boolean)|undefined),
* anchorBehavior: (UI.GlassPane.AnchorBehavior|undefined)
* }}
*/
UI.AutocompleteConfig;
| bsd-3-clause |
zbyte64/django-hyperadmin | hyperadmin/mediatypes/json.py | 997 | from __future__ import absolute_import
from django import http
from datatap.datataps import JSONDataTap
from hyperadmin.mediatypes.datatap import DataTap
class JSON(DataTap):
recognized_media_types = [
'application/json'
]
def __init__(self, api_request, **kwargs):
kwargs.setdefault('datatap_class', JSONDataTap)
super(JSON, self).__init__(api_request, **kwargs)
JSON.register_with_builtins()
class JSONP(JSON):
recognized_media_types = [
'text/javascript'
]
def get_jsonp_callback(self):
#TODO make configurable
return self.api_request.params['callback']
def serialize(self, content_type, link, state):
if self.detect_redirect(link):
return self.handle_redirect(link, content_type)
content = self.get_content(link, state)
callback = self.get_jsonp_callback()
return http.HttpResponse(u'%s(%s)' % (callback, content), content_type)
JSONP.register_with_builtins()
| bsd-3-clause |
byzhang/blaze | blazetest/src/mathtest/smatsmatadd/DCbHCb.cpp | 4170 | //=================================================================================================
/*!
// \file src/mathtest/smatsmatadd/DCbHCb.cpp
// \brief Source file for the DCbHCb sparse matrix/sparse matrix addition math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DiagonalMatrix.h>
#include <blaze/math/HermitianMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/smatsmatadd/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'DCbHCb'..." << std::endl;
using blazetest::mathtest::NumericB;
try
{
// Matrix type definitions
typedef blaze::DiagonalMatrix< blaze::CompressedMatrix<NumericB> > DCb;
typedef blaze::HermitianMatrix< blaze::CompressedMatrix<NumericB> > HCb;
// Creator type definitions
typedef blazetest::Creator<DCb> CDCb;
typedef blazetest::Creator<HCb> CHCb;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=i; ++j ) {
for( size_t k=0UL; k<=i*i; ++k ) {
RUN_SMATSMATADD_OPERATION_TEST( CDCb( i, j ), CHCb( i, k ) );
}
}
}
// Running tests with large matrices
RUN_SMATSMATADD_OPERATION_TEST( CDCb( 67UL, 7UL ), CHCb( 67UL, 13UL ) );
RUN_SMATSMATADD_OPERATION_TEST( CDCb( 128UL, 16UL ), CHCb( 128UL, 8UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix addition:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| bsd-3-clause |
tdgoodrich/inddgo_pure | lib_graphd/test/WeightedGraphTest.cpp | 3888 | /*
This file is part of INDDGO.
Copyright (C) 2012, Oak Ridge National Laboratory
This product includes software produced by UT-Battelle, LLC under Contract No.
DE-AC05-00OR22725 with the Department of Energy.
This program is free software; you can redistribute it and/or modify
it under the terms of the New BSD 3-clause software license (LICENSE).
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
LICENSE for more details.
For more information please contact the INDDGO developers at:
inddgo-info@googlegroups.com
*/
#include "Log.h"
#include "GraphCreatorFile.h"
#include "VertexWeightedGraph.h"
#include <gtest/gtest.h>
using namespace std;
class VertexWeightedGraphTest : public testing::Test
{
public:
Graph::GraphCreatorFile creator;
Graph::VertexWeightedGraph *wg;
virtual void SetUp(){
//SetUp is called before every test
LOG_INIT("test.log", NULL, 0);
creator.set_file_name("data/x.245.txt");
creator.set_graph_type("DIMACS");
wg = creator.create_vertex_weighted_graph();
}
virtual void TearDown(){
//TearDown is called before every test
LOG_CLOSE();
}
};
TEST_F(VertexWeightedGraphTest, testNumNodes)
{
EXPECT_EQ(23, wg->get_num_nodes());
}
TEST_F(VertexWeightedGraphTest, testNumEdges)
{
EXPECT_EQ(71, wg->get_num_edges());
}
TEST_F(VertexWeightedGraphTest, testGraphType)
{
EXPECT_EQ("DIMACS", wg->get_graph_type());
}
TEST_F(VertexWeightedGraphTest, testGetNode)
{
Graph::Node *n;
n = wg->get_node(19);
list<int> nbrs = n->get_nbrs();
EXPECT_EQ(4, nbrs.size());
}
TEST_F(VertexWeightedGraphTest, testIsEdge)
{
Graph::Node *n;
n = wg->get_node(19);
list<int> nbrs = n->get_nbrs();
EXPECT_EQ(4, nbrs.size());
EXPECT_TRUE(wg->is_edge(19, 10));
EXPECT_TRUE(wg->is_edge(19, 4));
EXPECT_FALSE(wg->is_edge(19, 1));
}
TEST_F(VertexWeightedGraphTest, testGetDegree)
{
EXPECT_EQ(6, wg->get_degree(6));
}
TEST_F(VertexWeightedGraphTest, testNodeNbrs)
{
vector<Graph::Node> n;
int i;
n = wg->get_nodes();
EXPECT_EQ(23, n.size());
list<int> nbrlist = n[10].get_nbrs();
vector<int> nbrs(nbrlist.begin(), nbrlist.end());
EXPECT_EQ(7, nbrs[2]);
nbrlist = n[22].get_nbrs();
nbrs.clear();
nbrs.insert(nbrs.end(), nbrlist.begin(), nbrlist.end());
EXPECT_EQ(13, nbrs[2]);
nbrlist = n[0].get_nbrs();
nbrs.clear();
nbrs.insert(nbrs.end(), nbrlist.begin(), nbrlist.end());
EXPECT_EQ(1, nbrs[0]);
EXPECT_EQ(17, nbrs[6]);
EXPECT_EQ(8, nbrs[3]);
}
TEST_F(VertexWeightedGraphTest, testGetDegrees)
{
vector<int> degree = wg->get_degree();
EXPECT_EQ(4, degree[19]);
}
TEST_F(VertexWeightedGraphTest, testGetNumComponents)
{
EXPECT_EQ(1, wg->get_num_components());
}
TEST_F(VertexWeightedGraphTest, testGetNextLabel)
{
EXPECT_EQ(24, wg->get_next_label());
}
TEST_F(VertexWeightedGraphTest, testSetNextLabel)
{
EXPECT_EQ(24, wg->get_next_label());
wg->set_next_label(140);
EXPECT_EQ(140, wg->get_next_label());
}
TEST_F(VertexWeightedGraphTest, testGetWeight)
{
vector<int> weights = wg->get_weight();
EXPECT_EQ(8, weights[0]);
EXPECT_EQ(8, weights[22]);
EXPECT_EQ(9, weights[14]);
EXPECT_EQ(3, weights[5]);
}
TEST_F(VertexWeightedGraphTest, testSetWeight)
{
vector<int> weights = wg->get_weight();
EXPECT_EQ(8, weights[0]);
EXPECT_EQ(8, weights[22]);
EXPECT_EQ(9, weights[14]);
EXPECT_EQ(3, weights[5]);
weights[5] = 100;
weights[10] = 200;
wg->set_weight(weights);
weights = wg->get_weight();
EXPECT_EQ(8, weights[0]);
EXPECT_EQ(8, weights[22]);
EXPECT_EQ(9, weights[14]);
EXPECT_EQ(100, weights[5]);
EXPECT_EQ(200, weights[10]);
}
| bsd-3-clause |
fraunhoferfokus/particity | portlet_data/src/main/java/de/fraunhofer/fokus/oefit/particity/service/impl/AHOfferLocalServiceImpl.java | 23665 | /*
* Copyright (c) 2015, Fraunhofer FOKUS
* 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 particity nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
*
* @author sma
*/
package de.fraunhofer.fokus.oefit.particity.service.impl;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ArrayUtil;
import de.fraunhofer.fokus.oefit.adhoc.custom.CustomPortalServiceHandler;
import de.fraunhofer.fokus.oefit.adhoc.custom.CustomServiceUtils;
import de.fraunhofer.fokus.oefit.adhoc.custom.E_CategoryType;
import de.fraunhofer.fokus.oefit.adhoc.custom.E_ConfigKey;
import de.fraunhofer.fokus.oefit.adhoc.custom.E_OfferStatus;
import de.fraunhofer.fokus.oefit.adhoc.custom.E_OfferType;
import de.fraunhofer.fokus.oefit.adhoc.custom.E_OfferWorkType;
import de.fraunhofer.fokus.oefit.adhoc.custom.E_OrderType;
import de.fraunhofer.fokus.oefit.adhoc.custom.E_SocialMediaPlugins;
import de.fraunhofer.fokus.oefit.particity.model.AHCatEntries;
import de.fraunhofer.fokus.oefit.particity.model.AHOffer;
import de.fraunhofer.fokus.oefit.particity.service.base.AHOfferLocalServiceBaseImpl;
import de.fraunhofer.fokus.oefit.particity.service.persistence.AHCatEntriesFinderUtil;
import de.fraunhofer.fokus.oefit.particity.service.persistence.AHOfferFinderUtil;
// TODO: Auto-generated Javadoc
/**
* The implementation of the a h offer local service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are
* added, rerun ServiceBuilder to copy their definitions into the
* {@link de.fraunhofer.fokus.oefit.particity.service.AHOfferLocalService}
* interface.
*
* <p>
* This is a local service. Methods of this service will not have security
* checks based on the propagated JAAS credentials because this service can only
* be accessed from within the same VM.
* </p>
*
* @author Brian Wing Shun Chan
* @see de.fraunhofer.fokus.oefit.adhoc.service.base.AHOfferLocalServiceBaseImpl
* @see de.fraunhofer.fokus.oefit.particity.service.AHOfferLocalServiceUtil
*/
public class AHOfferLocalServiceImpl extends AHOfferLocalServiceBaseImpl {
/*
* NOTE FOR DEVELOPERS: Never reference this interface directly. Always use
* {@link de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalServiceUtil}
* to access the a h offer local service.
*/
private static final Log m_objLog = LogFactoryUtil
.getLog(AHOfferLocalServiceImpl.class);
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#addOffer(de.fraunhofer.fokus.oefit.adhoc.custom.E_OfferType, java.lang.String, java.lang.String, java.lang.String, de.fraunhofer.fokus.oefit.adhoc.custom.E_OfferWorkType, long, long, long, long, long, boolean, long, long[])
*/
@Override
public AHOffer addOffer(int type, final String title,
final String descr, final String workTime,
final Integer workType, final long publishDate,
final long expireDate, final long addressId, final long contactId,
final long contact2Id, final boolean agencyContact,
final long orgId, final long[] categories) {
return this.addOffer(null, type, title, descr, workTime, workType,
publishDate, expireDate, addressId, contactId, contact2Id,
agencyContact, orgId, categories);
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#addOffer(java.lang.Long, de.fraunhofer.fokus.oefit.adhoc.custom.E_OfferType, java.lang.String, java.lang.String, java.lang.String, de.fraunhofer.fokus.oefit.adhoc.custom.E_OfferWorkType, long, long, long, long, long, boolean, long, long[])
*/
@Override
public AHOffer addOffer(final Long offerId, int type,
final String title, final String descr, final String workTime,
final Integer workType, final long publishDate,
final long expireDate, final long addressId, final long contactId,
final long contact2Id, final boolean agencyContact,
final long orgId, final long[] categories) {
AHOffer result = null;
try {
if (offerId != null && offerId >= 0) {
try {
result = this.getAHOffer(offerId);
} catch (final PortalException e) {
}
} else {
result = this.createAHOffer(CounterLocalServiceUtil
.increment(AHOffer.class.getName()));
}
if (result != null) {
final long now = CustomServiceUtils.time();
result.setAdressId(addressId);
result.setContactId(contactId);
result.setExpires(expireDate);
result.setDescription(descr);
// result.setRegionId(regionId);
result.setTitle(title);
result.setType(type);
result.setPublish(publishDate);
result.setWorkTime(workTime);
result.setUpdated(now);
result.setSndContactId(contact2Id);
result.setContactAgency(agencyContact);
result.setSocialStatus(0);
if (workType != null) {
result.setWorkType(workType);
}
if (offerId == null || offerId < 0) {
result.setOrgId(orgId);
result.setCreated(now);
result.setStatus(E_OfferStatus.NEW.getIntValue());
if (categories != null && categories.length > 0) {
this.getAHOfferPersistence().addAHCatEntrieses(
result.getPrimaryKey(), categories);
}
} else {
result.setStatus(E_OfferStatus.CHANGED.getIntValue());
// TODO - evaluate whether it is worth the computation or
// whether a batch removeAll/addAll would be more efficient
final List<AHCatEntries> entries = this
.getCategoriesByOffer(offerId, null);
final List<Long> entryIds = new LinkedList<Long>();
if (entries != null && entries.size() > 0) {
for (final AHCatEntries entry : entries) {
entryIds.add(entry.getItemId());
}
}
if (categories != null && categories.length > 0) {
for (int i = 0; i < categories.length; i++) {
if (!entryIds.contains(categories[i])) {
this.getAHOfferPersistence().addAHCatEntries(
offerId, categories[i]);
}
}
if (entries != null && entries.size() > 0) {
final List<Long> newEntries = Arrays
.asList(ArrayUtil.toArray(categories));
for (final Long entryId : entryIds) {
if (!newEntries.contains(entryId)) {
this.getAHOfferPersistence()
.removeAHCatEntries(offerId,
entryId);
}
}
}
} else if (entries.size() > 0) {
// remove all
this.getAHOfferPersistence().removeAHCatEntrieses(
offerId, entries);
}
}
// set valid, if it does not require additional input or check by mgmt and moderation is disabled
if (!result.isContactAgency() && !CustomPortalServiceHandler.isConfigEnabled(E_ConfigKey.MODERATE_OFFERS)) {
result.setStatus(E_OfferStatus.VALIDATED.getIntValue());
}
result = this.updateAHOffer(result);
}
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#addSocialStatus(java.lang.Long, de.fraunhofer.fokus.oefit.adhoc.custom.E_SocialMediaPlugins)
*/
@Override
public void addSocialStatus(final Long offerId,
final int smBitmask) {
try {
final AHOffer offer = this.getAHOffer(offerId);
if (offer != null) {
offer.setSocialStatus(smBitmask | offer.getSocialStatus());
this.updateAHOffer(offer);
}
} catch (final Throwable t) {
m_objLog.error(t);
}
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#countNewOffer()
*/
@Override
public int countNewOffer() {
int result = 0;
try {
result += this.getAHOfferPersistence().countBystatus(
E_OfferStatus.CHANGED.getIntValue());
result += this.getAHOfferPersistence().countBystatus(
E_OfferStatus.NEW.getIntValue());
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#countOfferByAddress(long)
*/
@Override
public int countOfferByAddress(final long addrId) {
int result = -1;
try {
result = this.getAHOfferPersistence().countByaddress(addrId);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#countOfferByCategoryId(java.lang.Long[])
*/
@Override
public Integer countOfferByCategoryId(final Long[] ids) {
Integer result = null;
try {
result = AHOfferFinderUtil.countOfferByCategories(
E_OfferStatus.VALIDATED.getIntValue(), ids);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#countOfferByCategoryItems(java.lang.String[])
*/
@Override
public Integer countOfferByCategoryItems(final String[] categoryItems) {
Integer result = 0;
try {
result = AHOfferFinderUtil.countOfferByCategoryitems(
E_OfferStatus.VALIDATED.getIntValue(), categoryItems);
} catch (final SystemException e) {
result = 0;
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#countOfferByOfferTypes(int[])
*/
@Override
public Integer countOfferByOfferTypes(final int[] types) {
Integer result = null;
try {
result = AHOfferFinderUtil.countOfferByOfferTypes(
E_OfferStatus.VALIDATED.getIntValue(), types);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#countOfferByTypesAndCItemsAndOrg(java.lang.String, java.lang.String, long)
*/
@Override
public Integer countOfferByTypesAndCItemsAndOrg(final String categoryItems,
final String types, final long orgId, Float lat, Float lon, Integer dist) {
Integer result = null;
try {
result = AHOfferFinderUtil.countOfferByTypesAndItemsAndOrg(
E_OfferStatus.VALIDATED.getIntValue(), types, categoryItems, orgId, lat, lon, dist);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#countOffersForOrganization(long)
*/
@Override
public int countOffersForOrganization(final long orgId) {
int result = 0;
try {
result = this.getAHOfferPersistence().countByorg(orgId);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#countPublishedOffers(long)
*/
@Override
public Integer countPublishedOffers(final long orgId) {
Integer result = null;
try {
final long millis = CustomServiceUtils.time();
if (orgId >= 0) {
result = this.getAHOfferPersistence()
.countByorgAndstatusAndDate(orgId,
E_OfferStatus.VALIDATED.getIntValue(), millis,
millis);
} else {
result = this.getAHOfferPersistence().countBystatusAndDate(
E_OfferStatus.VALIDATED.getIntValue(), millis, millis);
}
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#deleteOffersByOrg(long)
*/
@Override
public void deleteOffersByOrg(final long orgId) {
try {
this.getAHOfferPersistence().removeByorg(orgId);
} catch (final SystemException e) {
m_objLog.error(e);
}
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#findExpiredOffersForOrg(long, long, long)
*/
@Override
public List<AHOffer> findExpiredOffersForOrg(final long orgId,
final long startTime, final long endTime) {
List<AHOffer> result = null;
try {
result = AHOfferFinderUtil.getExpiredOffersByOrg(orgId, startTime,
endTime);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getCategoriesByOffer(long, de.fraunhofer.fokus.oefit.adhoc.custom.E_CategoryType)
*/
@Override
public List<AHCatEntries> getCategoriesByOffer(final long offerId,
final Integer type) {
List<AHCatEntries> result = new LinkedList<AHCatEntries>();
try {
result = AHCatEntriesFinderUtil.getCategoriesByOffer(offerId, type);
// result = getAHOfferPersistence().getAHCatEntrieses(offerId);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getCategoriesByOfferAsLong(long, de.fraunhofer.fokus.oefit.adhoc.custom.E_CategoryType)
*/
@Override
public Long[] getCategoriesByOfferAsLong(final long offerId,
final Integer type) {
final List<AHCatEntries> categories = this.getCategoriesByOffer(
offerId, type);
final Long[] result = new Long[categories.size()];
for (int i = 0; i < categories.size(); i++) {
result[i] = categories.get(i).getItemId();
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getCategoriesByOfferAsString(long, de.fraunhofer.fokus.oefit.adhoc.custom.E_CategoryType)
*/
@Override
public String getCategoriesByOfferAsString(final long offerId,
final Integer type) {
final List<AHCatEntries> categories = this.getCategoriesByOffer(
offerId, type);
final StringBuffer strCategories = new StringBuffer();
if (categories != null && categories.size() > 0) {
strCategories.append(categories.get(0).getName());
for (int i = 1; i < categories.size(); i++) {
strCategories.append(", ").append(categories.get(i).getName());
}
}
return strCategories.toString();
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getLastOfferForOrganization(long)
*/
@Override
public AHOffer getLastOfferForOrganization(final long orgId) {
AHOffer result = null;
try {
final List<AHOffer> offer = this.getAHOfferPersistence().findByorg(
orgId, 0, 1);
if (offer != null && offer.size() > 0) {
result = offer.get(0);
}
} catch (final Throwable t) {
m_objLog.warn(t);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getNewlyPublishedOffers(long)
*/
@Override
public List<AHOffer> getNewlyPublishedOffers(final long publishStartTime) {
List<AHOffer> result = new LinkedList<AHOffer>();
try {
result = AHOfferFinderUtil
.getNewlyPublishedOffers(publishStartTime);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getOfferByCategoryId(java.lang.Long[], int, int)
*/
@Override
public List<AHOffer> getOfferByCategoryId(final Long[] ids,
final int start, final int end) {
List<AHOffer> result = null;
try {
result = AHOfferFinderUtil.getOfferByCategories(
E_OfferStatus.VALIDATED.getIntValue(), ids, start, end);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getOfferByCategoryItems(java.lang.String[], int, int)
*/
@Override
public List<AHOffer> getOfferByCategoryItems(final String[] categoryItems,
final int start, final int end) {
List<AHOffer> result = null;
try {
result = AHOfferFinderUtil.getOfferByCategoryitems(
E_OfferStatus.VALIDATED.getIntValue(), categoryItems, start, end);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getOfferByOfferTypes(int[])
*/
@Override
public Integer getOfferByOfferTypes(final int[] types) {
Integer result = null;
try {
result = AHOfferFinderUtil.countOfferByOfferTypes(
E_OfferStatus.VALIDATED.getIntValue(), types);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getOfferByOfferTypes(int[], int, int)
*/
@Override
public List<AHOffer> getOfferByOfferTypes(final int[] types,
final int start, final int end) {
List<AHOffer> result = null;
try {
result = AHOfferFinderUtil.getOfferByOfferTypes(
E_OfferStatus.VALIDATED.getIntValue(), types, start, end);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getOfferByTypesAndCItemsAndOrg(java.lang.String, java.lang.String, long, int, int)
*/
@Override
public List<AHOffer> getOfferByTypesAndCItemsAndOrg(
final String categoryItems, final String types, final long orgId,
final int start, final int end, Float lat, Float lon, Integer dist) {
List<AHOffer> result = null;
try {
result = AHOfferFinderUtil.getOfferByTypesAndItemsAndOrg(
E_OfferStatus.VALIDATED.getIntValue(), types, categoryItems, orgId,
start, end, lat, lon, dist);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getOffers(int, int, java.lang.String, de.fraunhofer.fokus.oefit.adhoc.custom.E_OrderType)
*/
@Override
public List<AHOffer> getOffers(final int start, final int end,
final String column, final String order) {
List<AHOffer> result = null;
try {
result = AHOfferFinderUtil.getOffersWithCustomOrder(column, order,
start, end);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getOffersForOrganization(long)
*/
@Override
public List<AHOffer> getOffersForOrganization(final long orgId) {
List<AHOffer> result = new LinkedList<AHOffer>();
try {
result = this.getAHOfferPersistence().findByorg(orgId);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getOffersForOrganization(long, int, int, java.lang.String, de.fraunhofer.fokus.oefit.adhoc.custom.E_OrderType)
*/
@Override
public List<AHOffer> getOffersForOrganization(final long orgId,
final int start, final int end, final String column,
final String order) {
List<AHOffer> result = null;
try {
result = AHOfferFinderUtil.getOffersByOrgWithCustomOrder(orgId,
column, order, start, end);
// m_objLog.debug("Looking up organisations sorted by "+column.getColName()+" in order "+order.toString()+" from "+start+", to "+end);
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#getPublishedOffers(int, int, long)
*/
@Override
public List<AHOffer> getPublishedOffers(final int start, final int end,
final long orgId) {
List<AHOffer> result = null;
try {
final long millis = CustomServiceUtils.time();
if (orgId >= 0) {
result = this.getAHOfferPersistence()
.findByorgAndstatusAndDate(orgId,
E_OfferStatus.VALIDATED.getIntValue(), millis,
millis, start, end);
} else {
result = this.getAHOfferPersistence().findBystatusAndDate(
E_OfferStatus.VALIDATED.getIntValue(), millis, millis,
start, end);
/*
* if (result.size() == 0) {
* m_objLog.info("No results! Looking for misbehaviour ... ");
* long currentTime = System.currentTimeMillis(); List<AHOffer>
* offers = getAHOffers(QueryUtil.ALL_POS, QueryUtil.ALL_POS);
* for (AHOffer offer: offers) { if (offer.getStatus() ==
* E_OfferStatus.VALIDATED.getIntValue()) { long pubTime =
* offer.getPublish(); long expTime = offer.getExpires(); if
* (pubTime >= currentTime && expTime <= currentTime) {
* m_objLog.
* info("Got VALID offer "+offer.getTitle()+" with pubTime "
* +pubTime+", expTime "+expTime+", currenTime "+currentTime); }
* else m_objLog.info("Got INVALID offer "+offer.getTitle()+
* " with pubTime "
* +pubTime+", expTime "+expTime+", currenTime "+currentTime); }
* } }
*/
}
} catch (final SystemException e) {
m_objLog.error(e);
}
return result;
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#setOfferStatus(long, de.fraunhofer.fokus.oefit.adhoc.custom.E_OfferStatus)
*/
@Override
public void setOfferStatus(final long offerId, final Integer status) {
try {
final AHOffer offer = this.getAHOffer(offerId);
if (offer != null && status != null) {
offer.setStatus(status);
this.updateAHOffer(offer);
}
} catch (final Throwable t) {
m_objLog.error(t);
}
}
/* (non-Javadoc)
* @see de.fraunhofer.fokus.oefit.adhoc.service.AHOfferLocalService#setSndContact(java.lang.Long, long, de.fraunhofer.fokus.oefit.adhoc.custom.E_OfferStatus)
*/
@Override
public void setSndContact(final Long offerId, final long contactId,
final Integer newStatus) {
try {
final AHOffer offer = this.getAHOffer(offerId);
if (offer != null) {
if (newStatus != null) {
offer.setStatus(newStatus);
}
if (contactId >= 0) {
offer.setSndContactId(contactId);
}
this.updateAHOffer(offer);
}
} catch (final Throwable t) {
m_objLog.error(t);
}
}
}
| bsd-3-clause |
hukumonline/yii | sample4/simplesaml.1.5/modules/saml2/lib/Auth/Source/SP.php | 8908 | <?php
/**
* SAML 2.0 SP authentication client.
*
* Note: This authentication source is depreceated. You should
* use saml:sp instead.
*
* Example:
* 'example-openidp' => array(
* 'saml2:SP',
* 'idp' => 'https://openidp.feide.no',
* ),
*
* @package simpleSAMLphp
* @version $Id$
*/
class sspmod_saml2_Auth_Source_SP extends SimpleSAML_Auth_Source {
/**
* The identifier for the stage where we have sent a discovery service request.
*/
const STAGE_DISCO = 'saml2:SP-DiscoSent';
/**
* The identifier for the stage where we have sent a SSO request.
*/
const STAGE_SENT = 'saml2:SP-SSOSent';
/**
* The string used to identify our logout state.
*/
const STAGE_LOGOUTSENT = 'saml2:SP-LogoutSent';
/**
* The key of the AuthId field in the state.
*/
const AUTHID = 'saml2:AuthId';
/**
* The key for the IdP entity id in the logout state.
*/
const LOGOUT_IDP = 'saml2:SP-Logout-IdP';
/**
* The key for the NameID in the logout state.
*/
const LOGOUT_NAMEID = 'saml2:SP-Logout-NameID';
/**
* The key for the SessionIndex in the logout state.
*/
const LOGOUT_SESSIONINDEX = 'saml2:SP-Logout-SessionIndex';
/**
* The metadata for this SP.
*
* @var SimpleSAML_Configuration
*/
private $metadata;
/**
* The entity id of this SP.
*/
private $entityId;
/**
* The entity id of the IdP we connect to.
*/
private $idp;
/**
* Constructor for SAML 2.0 SP authentication source.
*
* @param array $info Information about this authentication source.
* @param array $config Configuration.
*/
public function __construct($info, $config) {
assert('is_array($info)');
assert('is_array($config)');
/* Call the parent constructor first, as required by the interface. */
parent::__construct($info, $config);
/* For compatibility with code that assumes that $metadata->getString('entityid') gives the entity id. */
if (array_key_exists('entityId', $config)) {
$config['entityid'] = $config['entityId'];
} else {
$config['entityid'] = SimpleSAML_Module::getModuleURL('saml2/sp/metadata.php?source=' . urlencode($this->authId));
}
/* For backwards-compatibility with configuration in saml20-sp-hosted. */
try {
$metadataHandler = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$oldMetadata = $metadataHandler->getMetaData($config['entityid'], 'saml20-sp-hosted');
SimpleSAML_Logger::warning('Depreceated metadata for ' . var_export($config['entityid'], TRUE) .
' in saml20-sp-hosted. The metadata in should be moved into authsources.php.');
$config = array_merge($oldMetadata, $config);
} catch (Exception $e) {};
$this->metadata = SimpleSAML_Configuration::loadFromArray($config, 'authsources[' . var_export($this->authId, TRUE) . ']');
$this->entityId = $this->metadata->getString('entityid');
$this->idp = $this->metadata->getString('idp', NULL);
}
/**
* Start login.
*
* This function saves the information about the login, and redirects to the IdP.
*
* @param array &$state Information about the current authentication.
*/
public function authenticate(&$state) {
assert('is_array($state)');
/* We are going to need the authId in order to retrieve this authentication source later. */
$state[self::AUTHID] = $this->authId;
if ($this->idp === NULL) {
$this->initDisco($state);
}
$this->initSSO($this->idp, $state);
}
/**
* Send authentication request to specified IdP.
*
* @param string $idp The IdP we should send the request to.
* @param array $state Our state array.
*/
public function initDisco($state) {
assert('is_array($state)');
$id = SimpleSAML_Auth_State::saveState($state, self::STAGE_DISCO);
$config = SimpleSAML_Configuration::getInstance();
$discoURL = $config->getString('idpdisco.url.saml20', NULL);
if ($discoURL === NULL) {
/* Fallback to internal discovery service. */
$discoURL = SimpleSAML_Module::getModuleURL('saml2/disco.php');
}
$returnTo = SimpleSAML_Module::getModuleURL('saml2/sp/discoresp.php');
$returnTo = SimpleSAML_Utilities::addURLparameter($returnTo, array('AuthID' => $id));
SimpleSAML_Utilities::redirect($discoURL, array(
'entityID' => $this->entityId,
'return' => $returnTo,
'returnIDParam' => 'idpentityid')
);
}
/**
* Send authentication request to specified IdP.
*
* @param string $idp The IdP we should send the request to.
* @param array $state Our state array.
*/
public function initSSO($idp, $state) {
assert('is_string($idp)');
assert('is_array($state)');
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$idpMetadata = $metadata->getMetaDataConfig($idp, 'saml20-idp-remote');
$ar = sspmod_saml2_Message::buildAuthnRequest($this->metadata, $idpMetadata);
$ar->setAssertionConsumerServiceURL(SimpleSAML_Module::getModuleURL('saml2/sp/acs.php'));
$ar->setProtocolBinding(SAML2_Const::BINDING_HTTP_POST);
$id = SimpleSAML_Auth_State::saveState($state, self::STAGE_SENT);
$ar->setRelayState($id);
$b = new SAML2_HTTPRedirect();
$b->setDestination(sspmod_SAML2_Message::getDebugDestination());
$b->send($ar);
assert('FALSE');
}
/**
* Retrieve the entity id of this SP.
*
* @return string Entity id of this SP.
*/
public function getEntityId() {
return $this->entityId;
}
/**
* Retrieve the metadata for this SP.
*
* @return SimpleSAML_Configuration The metadata, as a configuration object.
*/
public function getMetadata() {
return $this->metadata;
}
/**
* Retrieve the NameIDFormat used by this SP.
*
* @return string NameIDFormat used by this SP.
*/
public function getNameIDFormat() {
return $this->metadata->getString('NameIDFormat', 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient');
}
/**
* Check if the IdP entity id is allowed to authenticate users for this authentication source.
*
* @param string $idpEntityId The entity id of the IdP.
* @return boolean TRUE if it is valid, FALSE if not.
*/
public function isIdPValid($idpEntityId) {
assert('is_string($idpEntityId)');
if ($this->idp === NULL) {
/* No IdP configured - all are allowed. */
return TRUE;
}
if ($this->idp === $idpEntityId) {
return TRUE;
}
return FALSE;
}
/**
* Handle logout operation.
*
* @param array $state The logout state.
*/
public function logout(&$state) {
assert('is_array($state)');
assert('array_key_exists(self::LOGOUT_IDP, $state)');
assert('array_key_exists(self::LOGOUT_NAMEID, $state)');
assert('array_key_exists(self::LOGOUT_SESSIONINDEX, $state)');
$id = SimpleSAML_Auth_State::saveState($state, self::STAGE_LOGOUTSENT);
$idp = $state[self::LOGOUT_IDP];
$nameId = $state[self::LOGOUT_NAMEID];
$sessionIndex = $state[self::LOGOUT_SESSIONINDEX];
if (array_key_exists('value', $nameId)) {
/*
* This session was saved by an old version of simpleSAMLphp.
* Convert to the new NameId format.
*
* TODO: Remove this conversion once every session should use the new format.
*/
$nameId['Value'] = $nameId['value'];
unset($nameId['value']);
}
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$idpMetadata = $metadata->getMetaDataConfig($idp, 'saml20-idp-remote');
$lr = sspmod_saml2_Message::buildLogoutRequest($this->metadata, $idpMetadata);
$lr->setNameId($nameId);
$lr->setSessionIndex($sessionIndex);
$lr->setRelayState($id);
$b = new SAML2_HTTPRedirect();
$b->setDestination(sspmod_SAML2_Message::getDebugDestination());
$b->send($lr);
assert('FALSE');
}
/**
* Called when we receive a logout request.
*
* @param string $idpEntityId Entity id of the IdP.
*/
public function onLogout($idpEntityId) {
assert('is_string($idpEntityId)');
/* Call the logout callback we registered in onProcessingCompleted(). */
$this->callLogoutCallback($idpEntityId);
}
/**
* Called when we have completed the procssing chain.
*
* @param array $authProcState The processing chain state.
*/
public static function onProcessingCompleted(array $authProcState) {
assert('array_key_exists("saml2:sp:IdP", $authProcState)');
assert('array_key_exists("saml2:sp:State", $authProcState)');
assert('array_key_exists("Attributes", $authProcState)');
$idp = $authProcState['saml2:sp:IdP'];
$state = $authProcState['saml2:sp:State'];
$sourceId = $state[sspmod_saml2_Auth_Source_SP::AUTHID];
$source = SimpleSAML_Auth_Source::getById($sourceId);
if ($source === NULL) {
throw new Exception('Could not find authentication source with id ' . $sourceId);
}
/* Register a callback that we can call if we receive a logout request from the IdP. */
$source->addLogoutCallback($idp, $state);
$state['Attributes'] = $authProcState['Attributes'];
SimpleSAML_Auth_Source::completeAuth($state);
}
}
?> | bsd-3-clause |
nwjs/chromium.src | ui/wm/core/shadow_controller.cc | 12358 | // 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 "ui/wm/core/shadow_controller.h"
#include <utility>
#include "base/check.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/containers/flat_set.h"
#include "base/macros.h"
#include "base/no_destructor.h"
#include "base/scoped_multi_source_observation.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/env.h"
#include "ui/aura/env_observer.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
#include "ui/base/class_property.h"
#include "ui/base/ui_base_types.h"
#include "ui/compositor/layer.h"
#include "ui/compositor_extra/shadow.h"
#include "ui/wm/core/shadow_controller_delegate.h"
#include "ui/wm/core/shadow_types.h"
#include "ui/wm/core/window_util.h"
#include "ui/wm/public/activation_client.h"
using std::make_pair;
DEFINE_UI_CLASS_PROPERTY_TYPE(ui::Shadow*)
DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(ui::Shadow, kShadowLayerKey, nullptr)
namespace wm {
namespace {
int GetShadowElevationForActiveState(aura::Window* window) {
int elevation = window->GetProperty(kShadowElevationKey);
if (elevation != kShadowElevationDefault)
return elevation;
if (IsActiveWindow(window))
return kShadowElevationActiveWindow;
return GetDefaultShadowElevationForWindow(window);
}
// Returns the shadow style to be applied to |losing_active| when it is losing
// active to |gaining_active|. |gaining_active| may be of a type that hides when
// inactive, and as such we do not want to render |losing_active| as inactive.
int GetShadowElevationForWindowLosingActive(aura::Window* losing_active,
aura::Window* gaining_active) {
if (gaining_active && GetHideOnDeactivate(gaining_active)) {
if (base::Contains(GetTransientChildren(losing_active), gaining_active))
return kShadowElevationActiveWindow;
}
return kShadowElevationInactiveWindow;
}
} // namespace
// ShadowController::Impl ------------------------------------------------------
// Real implementation of the ShadowController. ShadowController observes
// ActivationChangeObserver, which are per ActivationClient, where as there is
// only a single Impl (as it observes all window creation by way of an
// EnvObserver).
class ShadowController::Impl :
public aura::EnvObserver,
public aura::WindowObserver,
public base::RefCounted<Impl> {
public:
// Returns the singleton instance for the specified Env.
static Impl* GetInstance(aura::Env* env);
Impl(const Impl&) = delete;
Impl& operator=(const Impl&) = delete;
void set_delegate(std::unique_ptr<ShadowControllerDelegate> delegate) {
delegate_ = std::move(delegate);
}
bool IsShadowVisibleForWindow(aura::Window* window);
void UpdateShadowForWindow(aura::Window* window);
// aura::EnvObserver override:
void OnWindowInitialized(aura::Window* window) override;
// aura::WindowObserver overrides:
void OnWindowParentChanged(aura::Window* window,
aura::Window* parent) override;
void OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) override;
void OnWindowVisibilityChanging(aura::Window* window, bool visible) override;
void OnWindowBoundsChanged(aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
ui::PropertyChangeReason reason) override;
void OnWindowDestroyed(aura::Window* window) override;
private:
friend class base::RefCounted<Impl>;
friend class ShadowController;
explicit Impl(aura::Env* env);
~Impl() override;
static base::flat_set<Impl*>* GetInstances();
// Forwarded from ShadowController.
void OnWindowActivated(ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active);
// Checks if |window| is visible and contains a property requesting a shadow.
bool ShouldShowShadowForWindow(aura::Window* window) const;
// Updates the shadow for windows when activation changes.
void HandleWindowActivationChange(aura::Window* gaining_active,
aura::Window* losing_active);
// Shows or hides |window|'s shadow as needed (creating the shadow if
// necessary).
void HandlePossibleShadowVisibilityChange(aura::Window* window);
// Creates a new shadow for |window| and stores it with the |kShadowLayerKey|
// key.
// The shadow's bounds are initialized and it is added to the window's layer.
void CreateShadowForWindow(aura::Window* window);
aura::Env* const env_;
base::ScopedMultiSourceObservation<aura::Window, aura::WindowObserver>
observation_manager_{this};
std::unique_ptr<ShadowControllerDelegate> delegate_;
};
// static
ShadowController::Impl* ShadowController::Impl::GetInstance(aura::Env* env) {
for (Impl* impl : *GetInstances()) {
if (impl->env_ == env)
return impl;
}
return new Impl(env);
}
bool ShadowController::Impl::IsShadowVisibleForWindow(aura::Window* window) {
if (!observation_manager_.IsObservingSource(window))
return false;
ui::Shadow* shadow = GetShadowForWindow(window);
return shadow && shadow->layer()->visible();
}
void ShadowController::Impl::UpdateShadowForWindow(aura::Window* window) {
DCHECK(observation_manager_.IsObservingSource(window));
HandlePossibleShadowVisibilityChange(window);
}
void ShadowController::Impl::OnWindowInitialized(aura::Window* window) {
// During initialization, the window can't reliably tell whether it will be a
// root window. That must be checked in the first visibility change
DCHECK(!window->parent());
DCHECK(!window->TargetVisibility());
observation_manager_.AddObservation(window);
}
void ShadowController::Impl::OnWindowParentChanged(aura::Window* window,
aura::Window* parent) {
if (parent && window->IsVisible())
HandlePossibleShadowVisibilityChange(window);
}
void ShadowController::Impl::OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) {
bool shadow_will_change = key == kShadowElevationKey &&
window->GetProperty(kShadowElevationKey) != old;
if (key == aura::client::kShowStateKey) {
shadow_will_change = window->GetProperty(aura::client::kShowStateKey) !=
static_cast<ui::WindowShowState>(old);
}
// Check the target visibility. IsVisible() may return false if a parent layer
// is hidden, but |this| only observes calls to Show()/Hide() on |window|.
if (shadow_will_change && window->TargetVisibility())
HandlePossibleShadowVisibilityChange(window);
}
void ShadowController::Impl::OnWindowVisibilityChanging(aura::Window* window,
bool visible) {
// At the time of the first visibility change, |window| will give a correct
// answer for whether or not it is a root window. If it is, don't bother
// observing: a shadow should never be added. Root windows can only have
// shadows in the WindowServer (where a corresponding aura::Window may no
// longer be a root window). Without this check, a second shadow is added,
// which clips to the root window bounds; filling any rounded corners the
// window may have.
if (window->IsRootWindow()) {
observation_manager_.RemoveObservation(window);
return;
}
HandlePossibleShadowVisibilityChange(window);
}
void ShadowController::Impl::OnWindowBoundsChanged(
aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
ui::PropertyChangeReason reason) {
ui::Shadow* shadow = GetShadowForWindow(window);
if (shadow && window->GetProperty(aura::client::kUseWindowBoundsForShadow))
shadow->SetContentBounds(gfx::Rect(new_bounds.size()));
}
void ShadowController::Impl::OnWindowDestroyed(aura::Window* window) {
window->ClearProperty(kShadowLayerKey);
observation_manager_.RemoveObservation(window);
}
void ShadowController::Impl::OnWindowActivated(ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) {
if (gained_active) {
ui::Shadow* shadow = GetShadowForWindow(gained_active);
if (shadow)
shadow->SetElevation(GetShadowElevationForActiveState(gained_active));
}
if (lost_active) {
ui::Shadow* shadow = GetShadowForWindow(lost_active);
if (shadow && GetShadowElevationConvertDefault(lost_active) ==
kShadowElevationInactiveWindow) {
shadow->SetElevation(
GetShadowElevationForWindowLosingActive(lost_active, gained_active));
}
}
}
bool ShadowController::Impl::ShouldShowShadowForWindow(
aura::Window* window) const {
if (delegate_) {
const bool should_show = delegate_->ShouldShowShadowForWindow(window);
if (should_show)
DCHECK(GetShadowElevationConvertDefault(window) > 0);
return should_show;
}
ui::WindowShowState show_state =
window->GetProperty(aura::client::kShowStateKey);
if (show_state == ui::SHOW_STATE_FULLSCREEN ||
show_state == ui::SHOW_STATE_MAXIMIZED) {
return false;
}
return GetShadowElevationConvertDefault(window) > 0;
}
void ShadowController::Impl::HandlePossibleShadowVisibilityChange(
aura::Window* window) {
const bool should_show = ShouldShowShadowForWindow(window);
ui::Shadow* shadow = GetShadowForWindow(window);
if (shadow) {
shadow->SetElevation(GetShadowElevationForActiveState(window));
shadow->layer()->SetVisible(should_show);
} else if (should_show) {
CreateShadowForWindow(window);
}
}
void ShadowController::Impl::CreateShadowForWindow(aura::Window* window) {
DCHECK(!window->IsRootWindow());
ui::Shadow* shadow = new ui::Shadow();
window->SetProperty(kShadowLayerKey, shadow);
int corner_radius = window->GetProperty(aura::client::kWindowCornerRadiusKey);
if (corner_radius >= 0)
shadow->SetRoundedCornerRadius(corner_radius);
shadow->Init(GetShadowElevationForActiveState(window));
shadow->SetContentBounds(gfx::Rect(window->bounds().size()));
shadow->layer()->SetVisible(ShouldShowShadowForWindow(window));
window->layer()->Add(shadow->layer());
window->layer()->StackAtBottom(shadow->layer());
}
ShadowController::Impl::Impl(aura::Env* env)
: env_(env), observation_manager_(this) {
GetInstances()->insert(this);
env_->AddObserver(this);
}
ShadowController::Impl::~Impl() {
env_->RemoveObserver(this);
GetInstances()->erase(this);
}
// static
base::flat_set<ShadowController::Impl*>*
ShadowController::Impl::GetInstances() {
static base::NoDestructor<base::flat_set<Impl*>> impls;
return impls.get();
}
// ShadowController ------------------------------------------------------------
ui::Shadow* ShadowController::GetShadowForWindow(aura::Window* window) {
return window->GetProperty(kShadowLayerKey);
}
ShadowController::ShadowController(
ActivationClient* activation_client,
std::unique_ptr<ShadowControllerDelegate> delegate,
aura::Env* env)
: activation_client_(activation_client),
impl_(Impl::GetInstance(env ? env : aura::Env::GetInstance())) {
// Watch for window activation changes.
activation_client_->AddObserver(this);
if (delegate)
impl_->set_delegate(std::move(delegate));
}
ShadowController::~ShadowController() {
activation_client_->RemoveObserver(this);
}
bool ShadowController::IsShadowVisibleForWindow(aura::Window* window) {
return impl_->IsShadowVisibleForWindow(window);
}
void ShadowController::UpdateShadowForWindow(aura::Window* window) {
impl_->UpdateShadowForWindow(window);
}
void ShadowController::OnWindowActivated(ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) {
impl_->OnWindowActivated(reason, gained_active, lost_active);
}
} // namespace wm
| bsd-3-clause |
vivyly/fancastic_17 | fancastic_17/config/local.py | 1253 | # -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# Mail settings
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend')
# End mail settings
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
}
# end django-debug-toolbar
# Your local stuff: Below this line define 3rd party libary settings
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
#NOSE_ARGS = [
# '--with-coverage',
# '--cover-package=myapp1, myapp2',
# '--cover-inclusive',
#]
| bsd-3-clause |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractGodofabcBlogspotCom.py | 869 | def extractGodofabcBlogspotCom(item):
'''
Parser for 'godofabc.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('RE:Yandere', 'RE:Yandere', 'translated'),
('Synthesis', 'Synthesis', 'translated'),
('These Dangerous Girls Placed Me Into Jeopardy', 'These Dangerous Girls Placed Me Into Jeopardy', 'translated'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | bsd-3-clause |
hung101/kbs | frontend/models/RefStatusMouMaoAntarabangsa.php | 2393 | <?php
namespace app\models;
use Yii;
use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;
/**
* This is the model class for table "tbl_ref_status_mou_mao_antarabangsa".
*
* @property integer $id
* @property string $desc
* @property integer $aktif
* @property integer $created_by
* @property integer $updated_by
* @property string $created
* @property string $updated
*/
class RefStatusMouMaoAntarabangsa extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tbl_ref_status_mou_mao_antarabangsa';
}
public function behaviors()
{
return [
'bedezign\yii2\audit\AuditTrailBehavior',
[
'class' => \yii\behaviors\BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
[
'class' => \yii\behaviors\TimestampBehavior::className(),
'createdAtAttribute' => 'created',
'updatedAtAttribute' => 'updated',
'value' => new \yii\db\Expression('NOW()'),
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['desc'], 'required', 'message' => GeneralMessage::yii_validation_required],
[['aktif', 'created_by', 'updated_by'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
[['created', 'updated'], 'safe'],
[['desc'], 'string', 'max' => 80, 'tooLong' => GeneralMessage::yii_validation_string_max],
[['desc'], function ($attribute, $params) {
if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) {
$this->addError($attribute, GeneralMessage::yii_validation_xss);
}
}],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => GeneralLabel::id,
'desc' => GeneralLabel::desc,
'aktif' => GeneralLabel::aktif,
'created_by' => GeneralLabel::created_by,
'updated_by' => GeneralLabel::updated_by,
'created' => GeneralLabel::created,
'updated' => GeneralLabel::updated,
];
}
}
| bsd-3-clause |
chillu/silverstripe-drupal-blog-importer | tests/DrupalBlogUserBulkLoaderTest.php | 1309 | <?php
class DrupalBlogUserBulkLoaderTest extends SapphireTest
{
protected $usesDatabase = true;
protected $requiredExtensions = array(
'Member' => array('DrupalMemberExtension'),
'BlogEntry' => array('DrupalBlogEntryExtension'),
);
public function testImport()
{
$loader = new DrupalBlogUserBulkLoader();
$result = $loader->load(BASE_PATH . '/drupal-blog-importer/tests/fixtures/users.csv');
$this->assertEquals(3, $result->CreatedCount());
$this->assertEquals(0, $result->UpdatedCount());
$created = $result->Created();
$this->assertContains('user1', $created->column('Nickname'));
$this->assertContains('user2', $created->column('Nickname'));
$this->assertContains('user3', $created->column('Nickname'));
$this->assertContains('201', $created->column('DrupalUid'));
$this->assertContains('202', $created->column('DrupalUid'));
$this->assertContains('203', $created->column('DrupalUid'));
$this->assertContains('John', $created->column('FirstName'));
$this->assertContains('Jane', $created->column('FirstName'));
$this->assertContains('Jack', $created->column('FirstName'));
$this->assertContains('Doe Smith', $created->column('Surname'));
}
}
| bsd-3-clause |
jaredwilkening/goprotobuf | proto/clone_test.go | 2700 | // Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2011 Google Inc. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto_test
import (
"log"
"testing"
"code.google.com/p/goprotobuf/proto"
pb "./testdata"
)
var cloneTestMessage = &pb.MyMessage{
Count: proto.Int32(42),
Name: proto.String("Dave"),
Pet: []string{"bunny", "kitty", "horsey"},
Inner: &pb.InnerMessage{
Host: proto.String("niles"),
Port: proto.Int32(9099),
Connected: proto.Bool(true),
},
Others: []*pb.OtherMessage{
&pb.OtherMessage{
Value: []byte("some bytes"),
},
},
RepBytes: [][]byte{[]byte("sham"), []byte("wow")},
}
func init() {
ext := &pb.Ext{
Data: proto.String("extension"),
}
if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil {
log.Fatalf("SetExtension: %v", err)
}
}
func TestClone(t *testing.T) {
m := proto.Clone(cloneTestMessage).(*pb.MyMessage)
if !proto.Equal(m, cloneTestMessage) {
t.Errorf("Clone(%v) = %v", cloneTestMessage, m)
}
// Verify it was a deep copy.
*m.Inner.Port++
if proto.Equal(m, cloneTestMessage) {
t.Error("Mutating clone changed the original")
}
}
| bsd-3-clause |
Bysmyyr/chromium-crosswalk | chrome/android/java/src/org/chromium/chrome/browser/preferences/Preferences.java | 10843 | // 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.
package org.chromium.chrome.browser.preferences;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceFragment.OnPreferenceStartFragmentCallback;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.base.library_loader.ProcessInitException;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeApplication;
import org.chromium.chrome.browser.help.HelpAndFeedback;
import org.chromium.chrome.browser.profiles.Profile;
/**
* The Chrome settings activity.
*
* This activity displays a single Fragment, typically a PreferenceFragment. As the user navigates
* through settings, a separate Preferences activity is created for each screen. Thus each fragment
* may freely modify its activity's action bar or title. This mimics the behavior of
* android.preference.PreferenceActivity.
*/
public class Preferences extends AppCompatActivity implements
OnPreferenceStartFragmentCallback {
public static final String EXTRA_SHOW_FRAGMENT = "show_fragment";
public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS = "show_fragment_args";
public static final String EXTRA_DISPLAY_HOME_AS_UP = "display_home_as_up";
private static final String TAG = "Preferences";
/** The current instance of Preferences in the resumed state, if any. */
private static Preferences sResumedInstance;
/** Whether this activity has been created for the first time but not yet resumed. */
private boolean mIsNewlyCreated;
private static boolean sActivityNotExportedChecked;
@SuppressFBWarnings("DM_EXIT")
@SuppressLint("InlinedApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
ensureActivityNotExported();
// The browser process must be started here because this Activity may be started explicitly
// from Android notifications, when Android is restoring Preferences after Chrome was
// killed, or for tests. This should happen before super.onCreate() because it might
// recreate a fragment, and a fragment might depend on the native library.
try {
((ChromeApplication) getApplication()).startBrowserProcessesAndLoadLibrariesSync(true);
} catch (ProcessInitException e) {
Log.e(TAG, "Failed to start browser process.", e);
// This can only ever happen, if at all, when the activity is started from an Android
// notification (or in tests). As such we don't want to show an error messsage to the
// user. The application is completely broken at this point, so close it down
// completely (not just the activity).
System.exit(-1);
return;
}
super.onCreate(savedInstanceState);
mIsNewlyCreated = savedInstanceState == null;
String initialFragment = getIntent().getStringExtra(EXTRA_SHOW_FRAGMENT);
Bundle initialArguments = getIntent().getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
boolean displayHomeAsUp = getIntent().getBooleanExtra(EXTRA_DISPLAY_HOME_AS_UP, true);
if (displayHomeAsUp) getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// This must be called before the fragment transaction below.
workAroundPlatformBugs();
// If savedInstanceState is non-null, then the activity is being
// recreated and super.onCreate() has already recreated the fragment.
if (savedInstanceState == null) {
if (initialFragment == null) initialFragment = MainPreferences.class.getName();
Fragment fragment = Fragment.instantiate(this, initialFragment, initialArguments);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, fragment)
.commit();
}
if (checkPermission(Manifest.permission.NFC, Process.myPid(), Process.myUid())
== PackageManager.PERMISSION_GRANTED) {
// Disable Android Beam on JB and later devices.
// In ICS it does nothing - i.e. we will send a Play Store link if NFC is used.
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter != null) nfcAdapter.setNdefPushMessage(null, this);
}
Resources res = getResources();
ApiCompatibilityUtils.setTaskDescription(this, res.getString(R.string.app_name),
BitmapFactory.decodeResource(res, R.mipmap.app_icon),
ApiCompatibilityUtils.getColor(res, R.color.default_primary_color));
}
// OnPreferenceStartFragmentCallback:
@Override
public boolean onPreferenceStartFragment(PreferenceFragment preferenceFragment,
Preference preference) {
startFragment(preference.getFragment(), preference.getExtras());
return true;
}
/**
* Starts a new Preferences activity showing the desired fragment.
*
* @param fragmentClass The Class of the fragment to show.
* @param args Arguments to pass to Fragment.instantiate(), or null.
*/
public void startFragment(String fragmentClass, Bundle args) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(this, getClass());
intent.putExtra(EXTRA_SHOW_FRAGMENT, fragmentClass);
intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
startActivity(intent);
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Fragment fragment = getFragmentManager().findFragmentById(android.R.id.content);
if (fragment instanceof PreferenceFragment && fragment.getView() != null) {
// Set list view padding to 0 so dividers are the full width of the screen.
fragment.getView().findViewById(android.R.id.list).setPadding(0, 0, 0, 0);
}
}
}
@Override
protected void onResume() {
super.onResume();
// Prevent the user from interacting with multiple instances of Preferences at the same time
// (e.g. in multi-instance mode on a Samsung device), which would cause many fun bugs.
if (sResumedInstance != null && !mIsNewlyCreated) {
// This activity was unpaused or recreated while another instance of Preferences was
// already showing. The existing instance takes precedence.
finish();
} else {
// This activity was newly created and takes precedence over sResumedInstance.
if (sResumedInstance != null) sResumedInstance.finish();
sResumedInstance = this;
mIsNewlyCreated = false;
}
}
@Override
protected void onPause() {
super.onPause();
if (sResumedInstance == this) sResumedInstance = null;
ChromeApplication.flushPersistentData();
}
/**
* Returns the fragment showing as this activity's main content, typically a PreferenceFragment.
* This does not include DialogFragments or other Fragments shown on top of the main content.
*/
@VisibleForTesting
public Fragment getFragmentForTest() {
return getFragmentManager().findFragmentById(android.R.id.content);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// By default, every screen in Settings shows a "Help & feedback" menu item.
MenuItem help = menu.add(
Menu.NONE, R.id.menu_id_help_general, Menu.CATEGORY_SECONDARY, R.string.menu_help);
help.setIcon(R.drawable.ic_help_and_feedback);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (menu.size() == 1) {
MenuItem item = menu.getItem(0);
if (item.getIcon() != null) item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
} else if (item.getItemId() == R.id.menu_id_help_general) {
HelpAndFeedback.getInstance(this).show(this, getString(R.string.help_context_settings),
Profile.getLastUsedProfile(), null);
return true;
}
return super.onOptionsItemSelected(item);
}
private void ensureActivityNotExported() {
if (sActivityNotExportedChecked) return;
sActivityNotExportedChecked = true;
try {
ActivityInfo activityInfo = getPackageManager().getActivityInfo(getComponentName(), 0);
// If Preferences is exported, then it's vulnerable to a fragment injection exploit:
// http://securityintelligence.com/new-vulnerability-android-framework-fragment-injection
if (activityInfo.exported) {
throw new IllegalStateException("Preferences must not be exported.");
}
} catch (NameNotFoundException ex) {
// Something terribly wrong has happened.
throw new RuntimeException(ex);
}
}
private void workAroundPlatformBugs() {
// Workaround for an Android bug where the fragment's view may not be attached to the view
// hierarchy. http://b/18525402
getSupportActionBar();
// Workaround for HTC One S bug which causes all the text in settings to turn white.
// This must be called after setContentView().
// https://code.google.com/p/android/issues/detail?id=78819
ViewCompat.postOnAnimation(getWindow().getDecorView(), new Runnable() {
@Override
public void run() {
setTheme(R.style.PreferencesTheme);
}
});
}
}
| bsd-3-clause |
vnesek/nmote-xr | src/main/java/com/nmote/nanohttp/NanoServlet.java | 358 | /*
* Copyright (c) Nmote Ltd. 2003-2014. All rights reserved.
* See LICENSE doc in a root of project folder for additional information.
*/
package com.nmote.nanohttp;
import java.io.IOException;
public interface NanoServlet {
boolean canProcess(NanoRequest nanoRequest);
void process(NanoRequest nanoRequest) throws IOException;
}
| bsd-3-clause |
liuxulei/zend_project | angulr/index.php | 41 | <?php
echo 'this is new folder.';
exit; | bsd-3-clause |
gamersmafia/gamersmafia | app/models/term.rb | 37521 | # -*- encoding : utf-8 -*-
class Term < ActiveRecord::Base
VALID_TAXONOMIES = %w(
BazarDistrict
Clan
ContentsTag
DownloadsCategory
EventsCategory
Game
GamePublisher
GamingPlatform
Homepage
ImagesCategory
NewsCategory
TopicsCategory
TutorialsCategory
)
acts_as_rootable
acts_as_tree :order => 'name'
has_slug :name
file_column :header_image
file_column :square_image
before_save :check_no_parent_if_contents_tag
before_save :check_references_to_ancestors
before_save :check_taxonomy
before_save :copy_parent_attrs
# VALIDATES siempre los últimos
validates_format_of :slug, :with => /^[a-z0-9_.-]{0,50}$/
validates_format_of :name, :with => /^.{1,100}$/
plain_text :name, :description
validates_uniqueness_of :name, :scope => [:parent_id, :taxonomy]
validates_uniqueness_of :slug, :scope => [:parent_id, :taxonomy]
def self.subscribed_users_per_tag
rows = User.db_query(
"SELECT
entity_id,
COUNT(*) AS cnt
FROM user_interests a
JOIN terms b
ON a.entity_type_class = 'Term'
AND a.entity_id = b.id
AND b.taxonomy = 'ContentsTag'
GROUP BY entity_id")
zero_tags = Term.with_taxonomy("ContentsTag").count - rows.size
(rows.collect{|row| row['cnt'].to_i } + [0]*zero_tags).percentile(0.99) || 0
end
# Returns the term associated with a game
def self.game_term(game)
Term.with_taxonomy("Game").find_by_game_id!(game.id)
end
def self.delete_empty_content_tags_terms
Term.contents_tags.find(:all, :conditions => 'contents_count = 0').each do |t|
next if t.contents_terms.count > 0 || t.users_contents_tags.count > 0
t.destroy
end and nil
end
def self.taxonomies
VALID_TAXONOMIES
end
def to_param
self.slug
end
def to_s
"id: '#{self.id}' slug: '#{self.slug}' name: '#{self.name}'" +
" parent: '#{self.parent_id}' root_id: '#{self.root_id}'"
end
def check_taxonomy
if self.taxonomy && !self.class.taxonomies.include?(self.taxonomy)
self.errors.add(
"term",
"Taxonomía '#{self.taxonomy}' incorrecta. Taxonomías válidas:" +
" #{self.class.taxonomies.join(', ')}")
false
else
true
end
end
def self.final_decision_made(decision)
case decision.decision_type_class
when "CreateTag"
user = User.find(decision.context[:initiating_user_id] || Ias.jabba.id)
if decision.final_decision_choice.name == Decision::BINARY_YES
decision.context[:initial_contents].each do |content_id|
content = Content.find_by_id(content_id.to_i)
if content.nil?
Rails.logger.error(
"'#{content_id}' is not a valid content id for a new tag." +
" Skipping..")
next
end
UsersContentsTag.tag_content(
content, user, decision.context[:tag_name], delete_missing=false)
tag = Term.with_taxonomy("ContentsTag").find_by_name(
decision.context[:tag_name])
decision.context[:result] = (
"<a href=\"/tags/#{tag.code}\">Ver tag</a>")
decision.save
end
user.notifications.create({
:sender_user_id => Ias.mrman.id,
:type_id => Notification::DECISION_RESULT,
:description => (
"¡Enhorabuena! Tu solicitud para crear el tag" +
" '#{decision.context[:tag_name]}' ha sido aceptada." +
" <a href=\"/decisiones/#{decision.id}\">Más información</a>."),
})
else # no
user.notifications.create({
:sender_user_id => Ias.mrman.id,
:type_id => Notification::DECISION_RESULT,
:description => (
"Tu solicitud para crear el tag '#{decision.context[:tag_name]}'" +
" ha sido rechazada. <a href=\"/decisiones/#{decision.id}\">Más" +
" información</a>."),
})
end
else
raise ("final decision made on unknown type" +
" (#{decision.decision_type_class})")
end
end
def self.find_taxonomy(id, taxonomy)
raise "Taxonomy can't be nil" if taxonomy.nil?
Term.with_taxonomy(taxonomy).find(:first, :conditions => ["id = ?", id])
end
def self.find_taxonomy_by_code(code, taxonomy)
# Solo para taxonomías toplevel
Term.find(:first, :conditions => ['id = root_id AND code = ? AND taxonomy = ?', code, taxonomy])
end
# Devuelve los ids de los hijos de la categoría actual o de la categoría obj de forma recursiva incluido el id de obj
def all_children_ids(opts={})
cats = [self.id]
conds = []
conds << opts[:cond] if opts[:cond].to_s != ''
conds << "taxonomy = #{User.connection.quote(opts[:taxonomy])}" if opts[:taxonomy]
cond = ''
cond = " AND #{conds.join(' AND ')}" if conds.size > 0
if self.id == self.root_id then # shortcut
db_query("SELECT id FROM terms WHERE root_id = #{self.id} AND id <> #{self.id} #{cond}").each { |dbc| cats<< dbc['id'].to_i }
else # hay que ir preguntando categoría por categoría
if conds.size > 0
self.children.find(:all, :conditions => cond[4..-1]).each { |child| cats.concat(child.all_children_ids(opts)) }
else
self.children.find(:all).each { |child| cats.concat(child.all_children_ids(opts)) }
end
end
cats.uniq
end
def self.taxonomy_from_class_name(cls_name)
"#{ActiveSupport::Inflector::pluralize(cls_name)}Category"
end
def get_ancestors
# devuelve los ascendientes. en [0] el padre directo y en el último el root
path = []
parent = self.parent
while parent do
path<< parent
parent = parent.parent
end
path
end
def add_sibling(sibling_term)
raise "sibling_term must be a term but is a #{sibling_term.class.name}" unless sibling_term.class.name == 'Term'
@siblings ||= []
@siblings<< sibling_term
end
private
def check_no_parent_if_contents_tag
!(self.taxonomy == "ContentsTag" && !self.parent_id.nil?)
end
def check_references_to_ancestors
if !self.new_record?
if self.parent_id_changed?
return false if self.parent_id == self.id # para evitar bucles infinitos
self.root_id = parent_id.nil? ? self.id : self.class.find(parent_id).root_id
self.class.find(:all, :conditions => "id IN (#{self.all_children_ids.join(',')})").each do |child|
next if child.id == self.id
child.root_id = self.root_id
child.save
end
end
end
true
end
public
# OLD
belongs_to :game
belongs_to :bazar_district
belongs_to :gaming_platform
belongs_to :clan
scope :portal_root_term, lambda { |portal|
taxonomy = case portal.class.name
when "BazarPortal"
"Homepage"
when "ArenaPortal"
"Homepage"
when "BazarDistrictPortal"
"BazarDistrict"
when "FactionsPortal"
Game.find_by_slug(portal.code) ? "Game" : "GamingPlatform"
when "ClansPortal"
"Clan"
else
raise "Unknown portal type '#{portal.type}' for portal '#{portal.code}'"
end
{:conditions => "taxonomy = '#{taxonomy}' AND slug = '#{portal.code}'"}
}
scope :with_contents, :conditions => "contents_count > 0"
scope :contents_tags, :conditions => "taxonomy = 'ContentsTag'"
scope :with_taxonomy, lambda { |taxonomy| {:conditions => "taxonomy = '#{taxonomy}'"}}
scope :with_taxonomies, lambda { |taxonomies|
joined_taxonomies = taxonomies.collect{|t| "'#{t}'"}.join(", ")
{:conditions => "taxonomy IN (#{joined_taxonomies})"}
}
scope :editable_taxonomies,
{:conditions => "taxonomy IN ('Game', 'GamingPlatform', 'BazarDistrict')"}
scope :in_category, lambda { |t| {
:conditions => ['id IN (
SELECT term_id
FROM contents_terms
WHERE content_id IN (
SELECT content_id
FROM contents_terms
WHERE term_id IN (?)))',
t.all_children_ids]}
}
has_many :contents_terms, :dependent => :destroy
has_many :contents, :through => :contents_terms
has_many :users_contents_tags #, :dependent => :destroy
has_many :tagged_contents, :through => :users_contents_tags, :source => :content
belongs_to :last_updated_item, :class_name => 'Content', :foreign_key => 'last_updated_item_id'
# before_save :set_slug
acts_as_rootable
acts_as_tree :order => 'name'
has_slug :name
before_destroy :sanity_check
before_save :check_references_to_ancestors
before_save :copy_parent_attrs
# VALIDATES siempre los últimos
validates_format_of :slug, :with => /^[a-z0-9_.-]{0,50}$/
validates_format_of :name, :with => /^.{1,100}$/
plain_text :name, :description
validates_uniqueness_of :name, :scope => [:game_id, :bazar_district_id, :gaming_platform_id, :clan_id, :taxonomy, :parent_id]
validates_uniqueness_of :slug, :scope => [:game_id, :bazar_district_id, :gaming_platform_id, :clan_id, :taxonomy, :parent_id]
def orphan?
self.contents.count == 0
end
def contents_tagged_count
raise "Invalid taxonomy" unless self.taxonomy == 'ContentsTag'
User.db_query("SELECT count(distinct(content_id)) FROM users_contents_tags WHERE term_id = #{self.id}")[0]['count'].to_i
end
def sanity_check
true # return false if self.contents_count > 25
end
def copy_parent_attrs
return true if self.id == self.root_id
par = self.parent
self.game_id = par.game_id
self.bazar_district_id = par.bazar_district_id
self.gaming_platform_id = par.gaming_platform_id
self.clan_id = par.clan_id
if par.taxonomy && par.taxonomy.include?("Category")
self.taxonomy = par.taxonomy
end
true
end
def code
# TODO temp
slug
end
def add_content_type_mask(content_type)
@content_type_mask = content_type
end
def set_slug
if self.slug.nil? || self.slug.to_s == ''
self.slug = self.name.bare.downcase
# TODO esto no comprueba si el slug está repetido
end
true
end
def import_mode
@_import_mode || false
end
def set_import_mode
@_import_mode = true
end
def link(content, normal_op=true)
raise "TypeError, arg is #{content.class.name}" unless content.class.name == 'Content'
# dupcheck, don't link twice.
if !self.contents.find(:first, :conditions => ['contents.id = ?', content.id]).nil?
Rails.logger.warn("#{content} is already linked to #{self}")
return true
end
if (Cms::CATEGORIES_TERMS_CONTENTS.include?(content.content_type.name) &&
!self.taxonomy.include?("Category"))
Rails.logger.warn(
"#{self} is a root term but #{content} requires a category" +
" term.")
return false if normal_op
# Exceptional behavior
taxo = "#{ActiveSupport::Inflector::pluralize(content.content_type.name)}Category"
t = self.children.find(:first, :conditions => "taxonomy = '#{taxo}'")
t = self.children.create(:name => 'General', :taxonomy => taxo) if t.nil?
t.link(content, normal_op)
elsif Cms::ROOT_TERMS_CONTENTS.include?(content.content_type.name) && self.taxonomy && self.taxonomy.index('Category')
Rails.logger.warn(
"Current term has taxonomy: #{self.taxonomy} but the specific content" +
" #{content} can only be linked to root terms.")
return false if normal_op
self.root.link(content, normal_op)
end
ct = self.contents_terms.create(:content_id => content.id)
if normal_op # TODO quitar esto despues de 2009.1
self.resolve_last_updated_item
# PERF esto hacerlo en accion secundaria?
term = self
while term
term.update_attributes({
:contents_count => term.contents_count + 1,
:comments_count => term.comments_count + content.comments_count})
term = term.parent
end
if self.id == self.root_id || self.taxonomy.include?('Category')
content.url = nil
Routing.gmurl(content)
end
end
true
end
def unlink(content)
raise "TypeError" unless content.class.name == 'Content'
self.contents_terms.find(:all, :conditions => ['content_id = ?', content.id]).each do |ct|
ct.destroy
end
# PERF esto hacerlo en accion secundaria?
o = self
while o
Term.decrement_counter(:contents_count, o.id)
User.db_query("UPDATE terms SET comments_count = comments_count - #{content.comments_count}")
o = o.parent
end
self.resolve_last_updated_item
true
end
def self.find_taxonomy(id, taxonomy)
sql_tax = taxonomy.nil? ? 'IS NULL' : "= #{User.connection.quote(taxonomy)}"
Term.find(:first, :conditions => ["id = ? AND taxonomy #{sql_tax}", id])
end
def self.find_taxonomy_by_code(code, taxonomy)
# Solo para taxonomías toplevel
Term.find(:first, :conditions => ['id = root_id AND code = ? AND taxonomy = ?', code, taxonomy])
end
def self.toplevel(options={})
conditions = 'id = root_id'
if options[:clan_id]
conditions << ' AND clan_id '
conditions << (options[:clan_id].nil? ? 'IS NULL' : " = #{options[:clan_id].to_i}")
end
conditions << " AND slug = #{User.connection.quote(options[:slug])}" if options[:slug]
conditions << " AND id = #{options[:id].to_i}" if options[:id]
conditions << " AND game_id = #{options[:game_id].to_i}" if options[:game_id]
conditions << " AND gaming_platform_id = #{options[:gaming_platform_id].to_i}" if options[:gaming_platform_id]
conditions << " AND bazar_district_id = #{options[:bazar_district_id].to_i}" if options[:bazar_district_id]
Term.find(:all, :conditions => conditions, :order => 'lower(name)')
end
def self.single_toplevel(opts={})
raise "Invalid single_toplevel, opts must be Hash!" if opts.class.name != 'Hash'
self.toplevel(opts)[0]
end
# Devuelve los ids de los hijos de la categoría actual o de la categoría obj de forma recursiva incluido el id de obj
def all_children_ids(opts={})
cats = [self.id]
conds = []
conds << opts[:cond] if opts[:cond].to_s != ''
conds << "taxonomy = #{User.connection.quote(opts[:taxonomy])}" if opts[:taxonomy]
cond = ''
cond = " AND #{conds.join(' AND ')}" if conds.size > 0
if self.id == self.root_id then # shortcut
db_query("SELECT id FROM terms WHERE root_id = #{self.id} AND id <> #{self.id} #{cond}").each { |dbc| cats<< dbc['id'].to_i }
else # hay que ir preguntando categoría por categoría
if conds.size > 0
self.children.find(:all, :conditions => cond[4..-1]).each { |child| cats.concat(child.all_children_ids(opts)) }
else
self.children.find(:all).each { |child| cats.concat(child.all_children_ids(opts)) }
end
end
cats.uniq
end
# devuelve portales relacionados con el término actual
def get_related_portals
portals = [GmPortal.new]
if self.game_id || self.gaming_platform_id
f = Faction.find_by_code(self.root.slug)
if f
portals += Portal.find(:all, :conditions => ['id in (SELECT portal_id from factions_portals where faction_id = ?)', f.id])
end
elsif self.bazar_district_id
portals << self.bazar_district
elsif self.clan_id
portals << ClansPortal.find_by_clan_id(self.clan_id)
else # PERF devolvemos todos por contents como funthings
portals += Portal.find(:all, :conditions => 'type <> \'ClansPortal\'')
end
portals
end
def recalculate_counters
recalculate_contents_count
last = self.get_or_resolve_last_updated_item
if last && last.state == Cms::DELETED
self.last_updated_item_id = nil
# self.save
self.get_or_resolve_last_updated_item
end
end
def recalculate_contents_count
newc = ContentsTerm.count(
:conditions => ["term_id IN (?)", self.all_children_ids(self)])
self.contents_count = newc
self.save
end
# Finds the last updated item id within this term and updates the
# last_updated_item_id attribute with whatever is found recursively up to the
# root.
def resolve_last_updated_item
last_content = Content.published.in_term_tree(self).find(
:first, :order => "updated_on DESC")
if last_content
self.last_updated_item_id = last_content.id
else
self.last_updated_item_id = nil
end
self.save
self.parent.resolve_last_updated_item if self.parent
end
# Returns the last updated item linked to this term. If the attribute is nil
# it will call resolve_last_updated_item.
def get_or_resolve_last_updated_item
self.resolve_last_updated_item if self.last_updated_item_id.nil?
self.last_updated_item ? self.last_updated_item.real_content : nil
end
def last_published_content(cls_name, opts={})
# opts: user_id
conds = []
conds << "user_id = #{opts[:user_id].to_i}" if opts[:user_id]
conds << opts[:conditions] if opts[:conditions]
cond = ''
cond = "#{conds.join(' AND ')}" if conds.size > 0
if cls_name
cat_ids = self.all_children_ids(:taxonomy => Term.taxonomy_from_class_name(cls_name))
else
cat_ids = self.all_children_ids
end
Content.in_term_ids(cat_ids).published.find(
:first, :conditions => cond, :order => "created_on DESC")
end
def can_be_destroyed?
# primera linea es para categorias no de primer nivel
# segunda es para categorias de primer nivel
((self.root_id != self.id && self.contents_count == 0) || \
self.root_id == self.id && (self.game_id || self.gaming_platform_id) && Faction.find_by_code(self.code).nil?)
end
def self.taxonomy_from_class_name(cls_name)
"#{ActiveSupport::Inflector::pluralize(cls_name)}Category"
end
# valid opts keys: cls_name
def contents_count(opts={})
# TODO perf optimizar mas, si el tag tiene el mismo taxonomy que el solicitado
sql_cond = opts[:conditions] ? " AND #{opts[:conditions]}" : ''
if !opts[:cls_name].nil?
taxo = self.class.taxonomy_from_class_name(opts[:cls_name])
User.db_query("SELECT count(*) FROM (SELECT content_id
FROM contents_terms a
JOIN terms b on a.term_id = b.id
JOIN contents on a.content_id = contents.id
WHERE (((a.term_id IN (#{all_children_ids(:taxonomy => taxo).join(',')})
AND b.taxonomy = #{User.connection.quote(taxo)})
OR a.term_id = #{self.id})
#{sql_cond})
GROUP BY content_id
) as foo")[0]['count'].to_i
elsif self.taxonomy
User.db_query("SELECT count(*) FROM (SELECT content_id
FROM contents_terms a
JOIN terms b on a.term_id = b.id
JOIN contents on a.content_id = contents.id
WHERE (((a.term_id IN (#{all_children_ids(:taxonomy => self.taxonomy).join(',')})
AND b.taxonomy = #{User.connection.quote(self.taxonomy)})
OR a.term_id = #{self.id})
#{sql_cond})
GROUP BY content_id
) as foo")[0]['count'].to_i
else # shortcut, show everything
if self.attributes['contents_count'].nil?
self.recalculate_counters
self.reload
self.attributes['contents_count']
end
self.attributes['contents_count']
end
end
def reset_contents_urls
# TODO PERF más inteligencia
self.find(:published, :treemode => true).each do |rc|
uniq = rc.unique_content
User.db_query("UPDATE contents SET url = NULL, portal_id = NULL WHERE id = #{uniq.id}")
uniq.reload
Routing.gmurl(uniq)
# self.children.each { |child| child.reset_contents}
end
end
# Busca contenidos asociados a este término o a uno de sus hijos
def find(*args)
args = _add_cats_ids_cond(*args)
res = Content.find(*args)
if res.kind_of?(Array)
res.uniq.collect { |cont| cont.real_content }
elsif res
res.real_content
end
end
def method_missing(method_id, *args)
begin
super
rescue NoMethodError
if Cms::CONTENTS_WITH_CATEGORIES.include?(ActiveSupport::Inflector::camelize(method_id.to_s))
TermContentProxy.new(ActiveSupport::Inflector::camelize(method_id.to_s), self)
elsif Cms::CONTENTS_WITH_CATEGORIES.include?(ActiveSupport::Inflector::camelize(ActiveSupport::Inflector::singularize(method_id.to_s)))
TermContentProxy.new(ActiveSupport::Inflector::camelize(ActiveSupport::Inflector::singularize(method_id.to_s)), self)
else
raise "No se que hacer con metodo #{method_id}"
end
end
end
def respond_to?(method_id, include_priv = false)
if Cms::CONTENTS_WITH_CATEGORIES.include?(ActiveSupport::Inflector::camelize(method_id.to_s))
true
elsif Cms::CONTENTS_WITH_CATEGORIES.include?(ActiveSupport::Inflector::camelize(ActiveSupport::Inflector::singularize(method_id.to_s)))
true
else
super
end
end
# Cuenta imágenes asociadas a esta categoría o a una de sus hijas
# TODO se puede optimizar usando caches en categorías para images
def count(*args)
args = _add_cats_ids_cond(*args)
opts = args.pop
opts.delete(:order) if opts[:order]
args.push(opts)
if opts[:joins]
if opts[:conditions] && opts[:conditions].kind_of?(Array)
opts[:conditions] = ActiveRecord::Base.send( "sanitize_sql_array", opts[:conditions])
end
opts[:joins] << " join contents_terms on contents.id = contents_terms.content_id " unless opts[:joins].include?('contents_terms')
Content.count_by_sql("SELECT count(*) FROM (SELECT contents.id FROM contents #{opts[:joins]} WHERE #{opts[:conditions]} GROUP BY contents.id) AS foo")
else
self.contents.count(*args)
end
end
# acepta keys: treemode (true: incluye categorías de hijos)
def _add_cats_ids_cond(*args)
@_add_cats_ids_done = true
options = {:treemode => true}.merge(args.last.is_a?(Hash) ? args.pop : {}) # copypasted de extract_options_from_args!(args)
@siblings ||= []
if options[:treemode]
@_cache_cats_ids ||= (self.all_children_ids + [self.id])
@siblings.each { |s| @_cache_cats_ids += s.all_children_ids }
# options[:conditions] = (options[:conditions]) ? ' AND ' : ''
new_cond = "term_id IN (#{@_cache_cats_ids.join(',')})"
else
new_cond = "term_id IN (#{([self.id] + @siblings.collect { |s| s.id }).join(',')})"
end
# si el primer arg es un id caso especial!
if args.reverse.first.kind_of?(Fixnum)
nargs = args.reverse
theid = nargs.pop
nargs.push(:first)
raise "find(id) a traves de term sin haber especificado content_type" unless options[:content_type]
new_cond << " AND #{ActiveSupport::Inflector::tableize(options[:content_type])}.id = #{theid}"
args = nargs
end
if options[:content_type].nil? && options[:content_type_id].nil? && self.taxonomy.to_s.index('Category')
options[:content_type] = Cms.extract_content_name_from_taxonomy(self.taxonomy)
end
if options[:content_type].nil? && options[:content_type_id].nil? && @content_type_mask
options[:content_type] = @content_type_mask
end
if options[:content_type]
new_cond << " AND contents.content_type_id = #{ContentType.find_by_name(options[:content_type]).id}"
options[:joins] = "JOIN #{ActiveSupport::Inflector::tableize(options[:content_type])} ON #{ActiveSupport::Inflector::tableize(options[:content_type])}.unique_content_id = contents.id"
end
if options[:content_type_id]
new_cond << " AND contents.content_type_id = #{options[:content_type_id]}"
ct = ContentType.find(options[:content_type_id])
options[:joins] = "JOIN #{ActiveSupport::Inflector::tableize(ct.name)} ON #{ActiveSupport::Inflector::tableize(ct.name)}.unique_content_id = contents.id"
#options[:include] ||= []
#options[:include] << :contents
end
options[:joins] ||= ''
options[:joins] <<= " JOIN contents_terms on contents.id = contents_terms.content_id "
options.delete :treemode
options.delete :content_type
options.delete :content_type_id
if options[:conditions].kind_of?(Array)
options[:conditions][0] = "#{options[:conditions][0]} AND #{new_cond}"
elsif options[:conditions] then
options[:conditions] = "#{options[:conditions]} AND #{new_cond}"
else
options[:conditions] = "#{new_cond}"
end
args.push(options)
agfirst = args.first
if agfirst.is_a?(Symbol) && [:drafts, :published, :deleted, :pending].include?(agfirst) then
options = args.last.is_a?(Hash) ? args.pop : {} # copypasted de extract_options_from_args!(args)
new_cond = "contents.state = #{Cms.const_get(agfirst.to_s.upcase)}"
if options[:conditions].kind_of?(Array)
options[:conditions][0] = "#{options[:conditions][0]} AND #{new_cond} "
elsif options[:conditions].to_s != '' then
options[:conditions] = "#{options[:conditions]} AND #{new_cond} "
else
options[:conditions] = new_cond
end
options[:order] = "contents.created_on DESC" unless options[:order]
args[0] = :all
args.push(options)
end
args
end
def random(limit=3)
cat_ids = self.all_children_ids
self.class.items_class.find(:all, :conditions => "state = #{Cms::PUBLISHED} and #{ActiveSupport::Inflector.underscore(self.class.name)}_id in (#{cat_ids.join(',')})", :order => 'RANDOM()', :limit => limit)
end
def most_popular_authors(opts)
q_add = opts[:conditions] ? " AND #{opts[:conditions]}" : ''
opts[:limit] ||= 5
dbitems = User.db_query("SELECT count(contents.id),
contents.user_id
from #{ActiveSupport::Inflector::tableize(opts[:content_type])}
JOIN contents on #{ActiveSupport::Inflector::tableize(opts[:content_type])}.unique_content_id = contents.id
WHERE contents.state = #{Cms::PUBLISHED}#{q_add}
GROUP BY contents.user_id
ORDER BY sum((coalesce(hits_anonymous, 0) + coalesce(hits_registered * 2, 0)+ coalesce(cache_comments_count * 10, 0) + coalesce(cache_rated_times * 20, 0))) desc
limit #{opts[:limit]}")
dbitems.collect { |dbitem| [User.find(dbitem['user_id']), dbitem['count'].to_i] }
end
def most_rated_items(opts)
raise "content_type unspecified" unless opts[:content_type] || opts[:joins]
opts = {:limit => 5}.merge(opts)
self.find(:published,
:content_type => opts[:content_type],
:conditions => "cache_rated_times > 1",
:order => 'coalesce(cache_weighted_rank, 0) DESC',
:limit => opts[:limit])
end
def most_popular_items(opts)
opts = {:limit => 3}.merge(opts)
raise "content_type unspecified" unless opts[:content_type]
self.find(:published,
:content_type => opts[:content_type],
:conditions => "cache_rated_times > 1",
:order => '(coalesce(hits_anonymous, 0) + coalesce(hits_registered * 2, 0)+ coalesce(cache_comments_count * 10, 0) + coalesce(cache_rated_times * 20, 0)) DESC',
:limit => opts[:limit])
end
def comments_count
# TODO perf
User.db_query("SELECT SUM(A.comments_count)
FROM contents A
JOIN contents_terms B ON A.id = B.content_id
WHERE B.term_id IN (#{all_children_ids.join(',')})
AND A.state = #{Cms::PUBLISHED}")[0]['sum'].to_i
end
def last_created_items(limit = 3) # TODO esta ya sobra me parece, mirar en tutoriales
self.find(:published,
:order => 'created_on DESC',
:limit => limit)
end
def random_item
# TODO PERF usar campo random_id
self.find(:published,
:order => 'random()')
end
def last_updated_items(opts={})
opts = {:limit => 5, :order => 'updated_on DESC'}.merge(opts)
self.find(:published, opts)
end
def last_updated_children(opts={})
opts = {:limit => 5}.merge(opts)
sql_cond = opts[:conditions] ? " AND #{opts[:conditions]}" : ''
Content.find_by_sql("SELECT *
FROM contents
WHERE id IN (SELECT last_updated_item_id
FROM terms WHERE id IN (SELECT id FROM terms WHERE parent_id = #{self.id})#{sql_cond})
ORDER BY updated_on DESC
LIMIT #{opts[:limit]}").collect { |c| c.terms.find(:all, :conditions => "1 = 1 #{sql_cond}")[0] }.compact.sort_by { |e| e.name.downcase }
end
# TODO tests
def most_active_users(taxonomy, time_interval='1 month')
return all_time_users(taxonomy, time_interval)
end
def all_time_users(taxonomy, time_interval='1 month')
raise "unsupported" unless taxonomy == 'TopicsCategory'
q_time = time_interval ? " AND created_on > (now() - '#{time_interval}'::interval)" : ''
tbl = {}
User.db_query("SELECT count(*), user_id
FROM contents
WHERE contents.id in (SELECT content_id
FROM contents_terms
WHERE term_id IN (#{all_children_ids(:taxonomy => taxonomy).join(',')}))
#{q_time}
GROUP BY user_id HAVING count(*) > 2
ORDER BY count(*) DESC").each do |t|
tbl[t['user_id'].to_i] = {:karma_sum => Karma::KPS_CREATE['Topic'] * t['count'].to_i,
:topics => t['count'].to_i,
:comments => 0}
end
User.db_query("SELECT count(*), user_id
FROM comments
WHERE comments.content_id in (SELECT content_id
FROM contents_terms
WHERE term_id IN (#{all_children_ids(:taxonomy => taxonomy).join(',')}))
#{q_time}
GROUP BY user_id HAVING count(*) > 2
ORDER BY count(*) DESC").each do |c|
tbl[c['user_id'].to_i] = {:karma_sum => 0, :topics => 0, :comments => 0} unless tbl[c['user_id'].to_i]
tbl[c['user_id'].to_i][:karma_sum] += Karma::KPS_CREATE['Comment'] * c['count'].to_i
tbl[c['user_id'].to_i][:comments] += c['count'].to_i
end
first = nil
second = nil
third = nil
fourth = nil
fifth = nil
inverted = {}
tbl.keys.each do |u|
inverted[tbl[u][:karma_sum]] ||= []
inverted[tbl[u][:karma_sum]] << [u, tbl[u]]
end
inverted.keys.sort.reverse.each do |kps|
break if fifth
inverted[kps].each do |row|
break if fifth
if first.nil?
first = row
elsif second.nil?
second = row
elsif third.nil?
third = row
elsif fourth.nil?
fourth = row
else
fifth = row
end
end
end
# NOTA: tb contamos comentarios de hace más de 3 meses en el top 3 de comentarios
# buscamos el total de karma generado por este topic
max = first ? first[1][:karma_sum] : 1 # no es 0 para no dividir por 0
result = []
if first
first[1][:relative_pcent] = 1.0
result<< [User.find(first[0]), first[1]]
end
if second
second[1][:relative_pcent] = second[1][:karma_sum].to_f / max
result<< [User.find(second[0]), second[1]]
end
if third
third[1][:relative_pcent] = third[1][:karma_sum].to_f / max
result<< [User.find(third[0]), third[1]]
end
if fourth
fourth[1][:relative_pcent] = fourth[1][:karma_sum].to_f / max
result<< [User.find(fourth[0]), fourth[1]]
end
if fifth
fifth[1][:relative_pcent] = fifth[1][:karma_sum].to_f / max
result<< [User.find(fifth[0]), fifth[1]]
end
result
end
def most_active_items(content_type)
# TODO per hit
# TODO no filtramos
self.find(:published,
:conditions => "contents.updated_on > now() - '3 months'::interval",
:content_type => content_type,
:order => '(contents.comments_count / extract (epoch from (now() - contents.created_on))) desc',
:limit => 5)
end
def top_contributors(opts)
total = User.db_query("SELECT count(DISTINCT(A.id))
FROM contents A
JOIN contents_terms B ON A.id = B.content_id
AND B.term_id IN (#{all_children_ids(opts.pass_sym(:taxonomy)).join(',')})
WHERE state = #{Cms::PUBLISHED}")[0]['count'].to_f
# TODO tests
# devuelve el usuario que más contenidos ha aportado a la categoría
User.db_query("SELECT user_id, count(DISTINCT(A.id))
FROM contents A
JOIN contents_terms B ON A.id = B.content_id
AND B.term_id IN (#{all_children_ids(opts.pass_sym(:taxonomy)).join(',')})
WHERE state = #{Cms::PUBLISHED}
GROUP BY user_id
ORDER BY count(A.id) DESC
LIMIT #{opts[:limit]}").collect do |dbr|
{:user => User.find(dbr['user_id'].to_i),
:count => dbr['count'].to_i,
:pcent => dbr['count'].to_i / total}
end
end
def get_ancestors
# devuelve los ascendientes. en [0] el padre directo y en el último el root
path = []
parent = self.parent
while parent do
path<< parent
parent = parent.parent
end
path
end
def self.find_by_toplevel_group_code(code)
case code
when 'gm'
Term.single_toplevel(:slug => 'gm').children.find(:all, :order => 'lower(name)')
when 'juegos'
Term.find(:all, :conditions => 'id = root_id AND game_id IS NOT NULL', :order => 'lower(name)')
when 'plataformas'
Term.find(:all, :conditions => 'id = root_id AND gaming_platform_id IS NOT NULL', :order => 'lower(name)')
when 'arena'
Term.single_toplevel(:slug => 'arena').children.find(:all, :order => 'lower(name)')
when 'bazar'
Term.find(:all, :conditions => 'id = root_id AND bazar_district_id IS NOT NULL', :order => 'lower(name)')
else
raise "toplevel group code '#{code}' unknown"
end
end
def add_sibling(sibling_term)
raise "sibling_term must be a term but is a #{sibling_term.class.name}" unless sibling_term.class.name == 'Term'
@siblings ||= []
@siblings<< sibling_term
end
private
def check_references_to_ancestors
if !self.new_record?
if self.parent_id_changed?
return false if self.parent_id == self.id # para evitar bucles infinitos
self.root_id = parent_id.nil? ? self.id : self.class.find(parent_id).root_id
self.class.find(:all, :conditions => "id IN (#{self.all_children_ids.join(',')})").each do |child|
next if child.id == self.id
child.root_id = self.root_id
child.save
end
end
self.delay.reset_contents_urls if self.root_id_changed?
end
true
end
def self.content_types_from_root(root_term)
raise "Root term isn't really root, bastard!" unless root_term.id == root_term.root_id
sql_conds = Cms::CATEGORIES_TERMS_CONTENTS.collect { |s| "'#{s}'"}
if root_term.game_id
ContentType.find(:all, :conditions => "name in (#{sql_conds.join(',')})", :order => 'lower(name)')
elsif root_term.gaming_platform_id
ContentType.find(:all, :conditions => "name in (#{sql_conds.join(',')})", :order => 'lower(name)')
elsif root_term.clan_id
ContentType.find(:all, :conditions => "name in (#{sql_conds.join(',')})", :order => 'lower(name)')
elsif root_term.bazar_district_id
ContentType.find(:all, :conditions => "name in (#{sql_conds.join(',')})", :order => 'lower(name)')
elsif root_term.clan_id
else # especial
ContentType.find(:all, :conditions => "name in (#{sql_conds.join(',')})", :order => 'lower(name)')
end
end
end
class TermContentProxy
def initialize(content_name, term)
@cls_name = content_name
@term = term
end
def method_missing(method_id, *args)
begin
super
rescue NoMethodError
opts = args.last.is_a?(Hash) ? args.pop : {}
opts[:content_type] = @cls_name
#args.push(opts)
# args = @term._add_cats_ids_cond(*args)
# opts = args.last.is_a?(Hash) ? args.pop : {}
if method_id == :count # && opts[:joins]
opts.delete :joins
opts.delete :order
end
args.push(opts)
begin
res = @term.send(method_id, *args)
res
rescue ArgumentError
@term.send(method_id)
end
end
end
end
| bsd-3-clause |
rsalmaso/django-cms | cms/signals/apphook.py | 1381 | import logging
import sys
from django.core.management import color_style
from django.core.signals import request_finished
from django.urls import clear_url_caches
from cms.utils.apphook_reload import mark_urlconf_as_changed
logger = logging.getLogger(__name__)
DISPATCH_UID = 'cms-restart'
def trigger_server_restart(**kwargs):
"""
Marks the URLs as stale so that they can be reloaded.
"""
mark_urlconf_as_changed()
def set_restart_trigger():
request_finished.connect(trigger_restart, dispatch_uid=DISPATCH_UID)
def trigger_restart(**kwargs):
from cms.signals import urls_need_reloading
request_finished.disconnect(trigger_restart, dispatch_uid=DISPATCH_UID)
urls_need_reloading.send(sender=None)
def debug_server_restart(**kwargs):
from cms.appresolver import clear_app_resolvers
if 'runserver' in sys.argv or 'server' in sys.argv:
clear_app_resolvers()
clear_url_caches()
import cms.urls
try:
reload(cms.urls)
except NameError: #python3
from imp import reload
reload(cms.urls)
if not 'test' in sys.argv:
msg = 'Application url changed and urls_need_reloading signal fired. ' \
'Please reload the urls.py or restart the server.\n'
styles = color_style()
msg = styles.NOTICE(msg)
sys.stderr.write(msg)
| bsd-3-clause |
mural/spm | db4oj/src/main/java/com/db4o/foundation/List4.java | 1521 | /* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2010 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. */
package com.db4o.foundation;
import com.db4o.types.*;
/**
* simplest possible linked list
*
* @exclude
*/
public final class List4<T> implements Unversioned
{
// TODO: encapsulate field access
/**
* next element in list
*/
public List4<T> _next;
/**
* carried object
*/
public T _element;
/**
* db4o constructor to be able to store objects of this class
*/
public List4() {}
public List4(T element) {
_element = element;
}
public List4(List4<T> next, T element) {
_next = next;
_element = element;
}
boolean holds(T obj) {
if(obj == null){
return _element == null;
}
return obj.equals(_element);
}
public static int size(List4<?> list) {
int counter = 0;
List4 nextList = list;
while(nextList != null){
counter++;
nextList = nextList._next;
}
return counter;
}
}
| bsd-3-clause |
hung101/kbs | frontend/views/ref-bahagian-kemudahan/index.php | 1459 | <?php
use yii\helpers\Html;
use yii\grid\GridView;
use app\models\general\GeneralLabel;
/* @var $this yii\web\View Atlet::findOne($id)*/
/* @var $searchModel frontend\models\RefBahagianKemudahanSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Bahagian Kemudahan';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ref-bahagian-kemudahan-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Tambah Bahagian Kemudahan', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
[
'attribute' => 'desc',
'filterInputOptions' => [
'class' => 'form-control',
'placeholder' => GeneralLabel::filter.' '.GeneralLabel::desc,
]
],
//'aktif',
[
'attribute' => 'aktif',
'value' => function ($model) {
return $model->aktif == 1 ? GeneralLabel::yes : GeneralLabel::no;
},
],
// ,
// ,
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
| bsd-3-clause |
fallenwood/libhare | tests/net/event_loop_test.cc | 927 | #include <hare/base/thread.h>
#include <hare/net/event_loop.h>
#include <cassert>
#include <cstdio>
#include <functional>
#include <unistd.h>
using namespace hare;
using namespace hare::net;
EventLoop *g_loop;
void callback() {
printf("callback(): pid = %d, tid = %d\n", getpid(), CurrentThread::tid());
EventLoop anotherLoop;
}
void threadFunc() {
printf("threadFunc(): pid = %d, tid = %d\n", getpid(), CurrentThread::tid());
assert(EventLoop::getEventLoopOfCurrentThread() == nullptr);
EventLoop loop;
assert(EventLoop::getEventLoopOfCurrentThread() == &loop);
loop.runAfter(1.0, callback);
loop.loop();
}
int main() {
printf("main(): pid = %d, tid = %d\n", getpid(), CurrentThread::tid());
assert(EventLoop::getEventLoopOfCurrentThread() == nullptr);
EventLoop loop;
assert(EventLoop::getEventLoopOfCurrentThread() == &loop);
Thread thread(threadFunc);
thread.start();
loop.loop();
}
| bsd-3-clause |
yjhu/wowewe | models/GiftboxCategory.php | 1178 | <?php
namespace app\models;
use Yii;
/**
* This is the model class for table "giftbox_category".
*
* @property integer $id
* @property string $content
* @property integer $quantity
* @property integer $remaining
*/
class GiftboxCategory extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'giftbox_category';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['quantity', 'remaining'], 'integer'],
[['content'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'content' => 'Content',
'quantity' => 'Quantity',
'remaining' => 'Remaining',
];
}
public static function getRemainingList() {
$ids = [];
$categories = self::find()->all();
foreach ($categories as $category) {
if ($category->quantity - $category->remaining > 0) {
$ids[] = $category->id;
}
}
return $ids;
}
}
| bsd-3-clause |
FernandoMauricio/portal-senac | modules/manut_transporte/views/manutencao-admin-acompanhamento/create.php | 534 | <?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\modules\manut_transporte\models\ManutencaoAdminAcompanhamento */
$this->title = 'Create Manutencao Admin Acompanhamento';
$this->params['breadcrumbs'][] = ['label' => 'Manutencao Admin Acompanhamento', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="manutencao-admin-acompanhamento-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| bsd-3-clause |
chamindar2002/htl-bkng | views/dashboard/index.php | 33108 | <div class="row">
<div class="col-lg-12">
<h1 class="page-header">Dashboard</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-3 col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-comments fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge">26</div>
<div>New Comments!</div>
</div>
</div>
</div>
<a href="#">
<div class="panel-footer">
<span class="pull-left">View Details</span>
<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-green">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-tasks fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge">12</div>
<div>New Tasks!</div>
</div>
</div>
</div>
<a href="#">
<div class="panel-footer">
<span class="pull-left">View Details</span>
<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-yellow">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-shopping-cart fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge">124</div>
<div>New Orders!</div>
</div>
</div>
</div>
<a href="#">
<div class="panel-footer">
<span class="pull-left">View Details</span>
<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-red">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-support fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge">13</div>
<div>Support Tickets!</div>
</div>
</div>
</div>
<a href="#">
<div class="panel-footer">
<span class="pull-left">View Details</span>
<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-8">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-bar-chart-o fa-fw"></i> Area Chart Example
<div class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
Actions
<span class="caret"></span>
</button>
<ul class="dropdown-menu pull-right" role="menu">
<li><a href="#">Action</a>
</li>
<li><a href="#">Another action</a>
</li>
<li><a href="#">Something else here</a>
</li>
<li class="divider"></li>
<li><a href="#">Separated link</a>
</li>
</ul>
</div>
</div>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div id="morris-area-chart"></div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-bar-chart-o fa-fw"></i> Bar Chart Example
<div class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
Actions
<span class="caret"></span>
</button>
<ul class="dropdown-menu pull-right" role="menu">
<li><a href="#">Action</a>
</li>
<li><a href="#">Another action</a>
</li>
<li><a href="#">Something else here</a>
</li>
<li class="divider"></li>
<li><a href="#">Separated link</a>
</li>
</ul>
</div>
</div>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="row">
<div class="col-lg-4">
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Time</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>3326</td>
<td>10/21/2013</td>
<td>3:29 PM</td>
<td>$321.33</td>
</tr>
<tr>
<td>3325</td>
<td>10/21/2013</td>
<td>3:20 PM</td>
<td>$234.34</td>
</tr>
<tr>
<td>3324</td>
<td>10/21/2013</td>
<td>3:03 PM</td>
<td>$724.17</td>
</tr>
<tr>
<td>3323</td>
<td>10/21/2013</td>
<td>3:00 PM</td>
<td>$23.71</td>
</tr>
<tr>
<td>3322</td>
<td>10/21/2013</td>
<td>2:49 PM</td>
<td>$8345.23</td>
</tr>
<tr>
<td>3321</td>
<td>10/21/2013</td>
<td>2:23 PM</td>
<td>$245.12</td>
</tr>
<tr>
<td>3320</td>
<td>10/21/2013</td>
<td>2:15 PM</td>
<td>$5663.54</td>
</tr>
<tr>
<td>3319</td>
<td>10/21/2013</td>
<td>2:13 PM</td>
<td>$943.45</td>
</tr>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.col-lg-4 (nested) -->
<div class="col-lg-8">
<div id="morris-bar-chart"></div>
</div>
<!-- /.col-lg-8 (nested) -->
</div>
<!-- /.row -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-clock-o fa-fw"></i> Responsive Timeline
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<ul class="timeline">
<li>
<div class="timeline-badge"><i class="fa fa-check"></i>
</div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">Lorem ipsum dolor</h4>
<p><small class="text-muted"><i class="fa fa-clock-o"></i> 11 hours ago via Twitter</small>
</p>
</div>
<div class="timeline-body">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Libero laboriosam dolor perspiciatis omnis exercitationem. Beatae, officia pariatur? Est cum veniam excepturi. Maiores praesentium, porro voluptas suscipit facere rem dicta, debitis.</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-badge warning"><i class="fa fa-credit-card"></i>
</div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">Lorem ipsum dolor</h4>
</div>
<div class="timeline-body">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Autem dolorem quibusdam, tenetur commodi provident cumque magni voluptatem libero, quis rerum. Fugiat esse debitis optio, tempore. Animi officiis alias, officia repellendus.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium maiores odit qui est tempora eos, nostrum provident explicabo dignissimos debitis vel! Adipisci eius voluptates, ad aut recusandae minus eaque facere.</p>
</div>
</div>
</li>
<li>
<div class="timeline-badge danger"><i class="fa fa-bomb"></i>
</div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">Lorem ipsum dolor</h4>
</div>
<div class="timeline-body">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus numquam facilis enim eaque, tenetur nam id qui vel velit similique nihil iure molestias aliquam, voluptatem totam quaerat, magni commodi quisquam.</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">Lorem ipsum dolor</h4>
</div>
<div class="timeline-body">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates est quaerat asperiores sapiente, eligendi, nihil. Itaque quos, alias sapiente rerum quas odit! Aperiam officiis quidem delectus libero, omnis ut debitis!</p>
</div>
</div>
</li>
<li>
<div class="timeline-badge info"><i class="fa fa-save"></i>
</div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">Lorem ipsum dolor</h4>
</div>
<div class="timeline-body">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nobis minus modi quam ipsum alias at est molestiae excepturi delectus nesciunt, quibusdam debitis amet, beatae consequuntur impedit nulla qui! Laborum, atque.</p>
<hr>
<div class="btn-group">
<button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-gear"></i> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Action</a>
</li>
<li><a href="#">Another action</a>
</li>
<li><a href="#">Something else here</a>
</li>
<li class="divider"></li>
<li><a href="#">Separated link</a>
</li>
</ul>
</div>
</div>
</div>
</li>
<li>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">Lorem ipsum dolor</h4>
</div>
<div class="timeline-body">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi fuga odio quibusdam. Iure expedita, incidunt unde quis nam! Quod, quisquam. Officia quam qui adipisci quas consequuntur nostrum sequi. Consequuntur, commodi.</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-badge success"><i class="fa fa-graduation-cap"></i>
</div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">Lorem ipsum dolor</h4>
</div>
<div class="timeline-body">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt obcaecati, quaerat tempore officia voluptas debitis consectetur culpa amet, accusamus dolorum fugiat, animi dicta aperiam, enim incidunt quisquam maxime neque eaque.</p>
</div>
</div>
</li>
</ul>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-8 -->
<div class="col-lg-4">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-bell fa-fw"></i> Notifications Panel
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="list-group">
<a href="#" class="list-group-item">
<i class="fa fa-comment fa-fw"></i> New Comment
<span class="pull-right text-muted small"><em>4 minutes ago</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-twitter fa-fw"></i> 3 New Followers
<span class="pull-right text-muted small"><em>12 minutes ago</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-envelope fa-fw"></i> Message Sent
<span class="pull-right text-muted small"><em>27 minutes ago</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-tasks fa-fw"></i> New Task
<span class="pull-right text-muted small"><em>43 minutes ago</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-upload fa-fw"></i> Server Rebooted
<span class="pull-right text-muted small"><em>11:32 AM</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-bolt fa-fw"></i> Server Crashed!
<span class="pull-right text-muted small"><em>11:13 AM</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-warning fa-fw"></i> Server Not Responding
<span class="pull-right text-muted small"><em>10:57 AM</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-shopping-cart fa-fw"></i> New Order Placed
<span class="pull-right text-muted small"><em>9:49 AM</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-money fa-fw"></i> Payment Received
<span class="pull-right text-muted small"><em>Yesterday</em>
</span>
</a>
</div>
<!-- /.list-group -->
<a href="#" class="btn btn-default btn-block">View All Alerts</a>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-bar-chart-o fa-fw"></i> Donut Chart Example
</div>
<div class="panel-body">
<div id="morris-donut-chart"></div>
<a href="#" class="btn btn-default btn-block">View Details</a>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
<div class="chat-panel panel panel-default">
<div class="panel-heading">
<i class="fa fa-comments fa-fw"></i> Chat
<div class="btn-group pull-right">
<button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-chevron-down"></i>
</button>
<ul class="dropdown-menu slidedown">
<li>
<a href="#">
<i class="fa fa-refresh fa-fw"></i> Refresh
</a>
</li>
<li>
<a href="#">
<i class="fa fa-check-circle fa-fw"></i> Available
</a>
</li>
<li>
<a href="#">
<i class="fa fa-times fa-fw"></i> Busy
</a>
</li>
<li>
<a href="#">
<i class="fa fa-clock-o fa-fw"></i> Away
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<i class="fa fa-sign-out fa-fw"></i> Sign Out
</a>
</li>
</ul>
</div>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<ul class="chat">
<li class="left clearfix">
<span class="chat-img pull-left">
<img src="http://placehold.it/50/55C1E7/fff" alt="User Avatar" class="img-circle" />
</span>
<div class="chat-body clearfix">
<div class="header">
<strong class="primary-font">Jack Sparrow</strong>
<small class="pull-right text-muted">
<i class="fa fa-clock-o fa-fw"></i> 12 mins ago
</small>
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur bibendum ornare dolor, quis ullamcorper ligula sodales.
</p>
</div>
</li>
<li class="right clearfix">
<span class="chat-img pull-right">
<img src="http://placehold.it/50/FA6F57/fff" alt="User Avatar" class="img-circle" />
</span>
<div class="chat-body clearfix">
<div class="header">
<small class=" text-muted">
<i class="fa fa-clock-o fa-fw"></i> 13 mins ago</small>
<strong class="pull-right primary-font">Bhaumik Patel</strong>
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur bibendum ornare dolor, quis ullamcorper ligula sodales.
</p>
</div>
</li>
<li class="left clearfix">
<span class="chat-img pull-left">
<img src="http://placehold.it/50/55C1E7/fff" alt="User Avatar" class="img-circle" />
</span>
<div class="chat-body clearfix">
<div class="header">
<strong class="primary-font">Jack Sparrow</strong>
<small class="pull-right text-muted">
<i class="fa fa-clock-o fa-fw"></i> 14 mins ago</small>
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur bibendum ornare dolor, quis ullamcorper ligula sodales.
</p>
</div>
</li>
<li class="right clearfix">
<span class="chat-img pull-right">
<img src="http://placehold.it/50/FA6F57/fff" alt="User Avatar" class="img-circle" />
</span>
<div class="chat-body clearfix">
<div class="header">
<small class=" text-muted">
<i class="fa fa-clock-o fa-fw"></i> 15 mins ago</small>
<strong class="pull-right primary-font">Bhaumik Patel</strong>
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur bibendum ornare dolor, quis ullamcorper ligula sodales.
</p>
</div>
</li>
</ul>
</div>
<!-- /.panel-body -->
<div class="panel-footer">
<div class="input-group">
<input id="btn-input" type="text" class="form-control input-sm" placeholder="Type your message here..." />
<span class="input-group-btn">
<button class="btn btn-warning btn-sm" id="btn-chat">
Send
</button>
</span>
</div>
</div>
<!-- /.panel-footer -->
</div>
<!-- /.panel .chat-panel -->
</div>
<!-- /.col-lg-4 -->
</div>
<!-- /.row --> | bsd-3-clause |
gingerwfms/ginger-wfms | module/Application/src/Application/ModuleInclusion/Service/PluginHandlerFactory.php | 1032 | <?php
/*
* This file is part of the codeliner/ginger-wfms package.
* (c) Alexander Miertsch <kontakt@codeliner.ws>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Application\ModuleInclusion\Service;
use Application\ModuleInclusion\PluginHandler;
use Application\ModuleInclusion\ModuleIncludeManager;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
/**
* ServiceFactory for PluginHandler
*
* @author Alexander Miertsch <kontakt@codeliner.ws>
*/
class PluginHandlerFactory implements FactoryInterface
{
/**
* Create a new instance of PluginHandler
*
* @param ServiceLocatorInterface $serviceLocator
*
* @return PluginHandler
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$pluginHandler = new PluginHandler($serviceLocator->get('module_include_manager'));
return $pluginHandler;
}
}
| bsd-3-clause |
menudoproblema/SubscriptionFramework | tests/subscription/test_signals.py | 3817 | import unittest
from subscription.signals import Signal
from subscription.signals.accumulators import *
def handler_none(*args, **kwargs):
return None
def handler_true(*args, **kwargs):
return True
def handler_false(*args, **kwargs):
return False
def handler_zero(*args, **kwargs):
return 0
def handler_one(*args, **kwargs):
return 1
def handler_two(*args, **kwargs):
return 2
class SignalTest(unittest.TestCase):
def test_signal(self):
signal = Signal()
self.assertEqual(signal.has_handlers(), False)
signal.connect(handler_none)
self.assertEqual(signal.has_handlers(), True)
self.assertEqual(signal.count_handlers(), 1)
signal.connect(handler_true)
self.assertEqual(signal.has_handlers(), True)
self.assertEqual(signal.count_handlers(), 2)
signal.connect(handler_false)
self.assertEqual(signal.has_handlers(), True)
self.assertEqual(signal.count_handlers(), 3)
signal.disconnect(handler_false)
self.assertEqual(signal.has_handlers(), True)
self.assertEqual(signal.count_handlers(), 2)
signal.clear()
self.assertEqual(signal.has_handlers(), False)
self.assertEqual(signal.count_handlers(), 0)
del signal
def test_get_accumulator(self):
signal = Signal()
is_instance = isinstance(signal.get_accumulator(), DefaultAccumulator)
self.assertTrue(is_instance)
del signal
signal = Signal(accumulator=SumAccumulator)
is_instance = isinstance(signal.get_accumulator(), SumAccumulator)
self.assertTrue(is_instance)
del signal
def test_noneaccumulator(self):
signal = Signal(accumulator=NoneAccumulator)
signal.connect(handler_none)
signal.connect(handler_true)
signal.connect(handler_false)
val = signal.emit()
self.assertEqual(val, None)
del signal
def test_sumaccumulator(self):
signal = Signal(accumulator=SumAccumulator)
signal.connect(handler_zero)
signal.connect(handler_one)
signal.connect(handler_two)
val = signal.emit()
self.assertEqual(val, 3)
del signal
def test_anyacceptaccumulator(self):
signal = Signal(accumulator=AnyAcceptAccumulator)
signal.connect(handler_false)
signal.connect(handler_zero)
val = signal.emit()
self.assertEqual(val, False)
signal.clear()
signal.connect(handler_false)
signal.connect(handler_two)
signal.connect(handler_zero)
val = signal.emit()
self.assertEqual(val, 2)
del signal
def test_allacceptaccumulator(self):
signal = Signal(accumulator=AllAcceptAccumulator)
signal.connect(handler_one)
signal.connect(handler_two)
val = signal.emit()
self.assertEqual(val, True)
signal.clear()
signal.connect(handler_zero)
signal.connect(handler_two)
signal.connect(handler_one)
val = signal.emit()
self.assertEqual(val, 0)
del signal
def test_lastvalueaccumulator(self):
signal = Signal(accumulator=LastValueAccumulator)
signal.connect(handler_one)
signal.connect(handler_two)
val = signal.emit()
# Signal don't guarantee the order of execution
self.assertTrue(val in (1, 2,))
del signal
def test_valuelistaccumulator(self):
signal = Signal(accumulator=ValueListAccumulator)
signal.connect(handler_one)
signal.connect(handler_two)
val = signal.emit()
val = list(val)
val.sort()
self.assertEqual(val, [1, 2, ])
del signal
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
brucewu0329/pcl | visualization/src/vtk/pcl_context_item.cpp | 7226 | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2012-, Open Perception, 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:
*
* * 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 copyright holder(s) 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.
*
*/
#include <vtkObjectFactory.h>
#include <vtkSmartPointer.h>
#include <vtkContext2D.h>
#include <vtkImageData.h>
#include <vtkPen.h>
#include <vtkBrush.h>
#include <pcl/visualization/vtk/pcl_context_item.h>
namespace pcl
{
namespace visualization
{
// Standard VTK macro for *New ()
vtkStandardNewMacro (PCLContextItem);
vtkStandardNewMacro (PCLContextImageItem);
namespace context_items
{
vtkStandardNewMacro (Point);
vtkStandardNewMacro (Line);
vtkStandardNewMacro (Circle);
vtkStandardNewMacro (Disk);
vtkStandardNewMacro (Rectangle);
vtkStandardNewMacro (FilledRectangle);
vtkStandardNewMacro (Points);
vtkStandardNewMacro (Polygon);
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLContextItem::setColors (unsigned char r, unsigned char g, unsigned char b)
{
colors[0] = r; colors[1] = g; colors[2] = b;
}
///////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::PCLContextImageItem::set (float _x, float _y, vtkImageData *_image)
{
x = _x;
y = _y;
image->DeepCopy (_image);
}
///////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::PCLContextImageItem::Paint (vtkContext2D *painter)
{
SetOpacity (1.0);
painter->DrawImage (x, y, image);
return (true);
}
///////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::context_items::Point::set (float x, float y)
{
params.resize (2);
params[0] = x; params[1] = y;
}
///////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::context_items::Circle::set (float x, float y, float radius)
{
params.resize (4);
params[0] = x; params[1] = y; params[2] = radius; params[3] = radius - 1;
}
///////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::context_items::Rectangle::set (float x, float y, float w, float h)
{
params.resize (4);
params[0] = x; params[1] = y; params[2] = w; params[3] = h;
}
///////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::context_items::Line::set (float start_x, float start_y, float end_x, float end_y)
{
params.resize (4);
params[0] = start_x; params[1] = start_y; params[2] = end_x; params[3] = end_y;
}
///////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::context_items::Circle::Paint (vtkContext2D *painter)
{
painter->GetPen ()->SetColor (colors);
painter->GetBrush ()->SetColor (colors);
painter->DrawWedge (params[0], params[1], params[2], params[3], 0.0, 360.0);
return (true);
}
///////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::context_items::Disk::Paint (vtkContext2D *painter)
{
painter->GetBrush ()->SetColor (colors);
painter->GetPen ()->SetColor (colors);
painter->DrawEllipse (params[0], params[1], params[2], params[2]);
return (true);
}
///////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::context_items::Rectangle::Paint (vtkContext2D *painter)
{
painter->GetPen ()->SetColor (colors);
float p[] =
{
params[0], params[1],
params[0]+params[2], params[1],
params[0]+params[2], params[1]+params[3],
params[0], params[1]+params[3],
params[0], params[1]
};
painter->DrawPoly (p, 5);
return (true);
}
///////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::context_items::FilledRectangle::Paint (vtkContext2D *painter)
{
painter->GetBrush ()->SetColor (colors);
painter->GetPen ()->SetColor (colors);
painter->DrawRect (params[0], params[1], params[2], params[3]);
return (true);
}
///////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::context_items::Line::Paint (vtkContext2D *painter)
{
painter->GetPen ()->SetColor (colors);
painter->DrawLine (params[0], params[1], params[2], params[3]);
return (true);
}
///////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::context_items::Polygon::Paint (vtkContext2D *painter)
{
painter->GetBrush ()->SetColor (colors);
painter->GetPen ()->SetColor (colors);
painter->DrawPolygon (¶ms[0], static_cast<int> (params.size () / 2));
return (true);
}
///////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::context_items::Point::Paint (vtkContext2D *painter)
{
painter->GetPen ()->SetColor (colors);
painter->DrawPoint (params[0], params[1]);
return (true);
}
///////////////////////////////////////////////////////////////////////////////////////////
bool
pcl::visualization::context_items::Points::Paint (vtkContext2D *painter)
{
painter->GetPen ()->SetColor (colors);
painter->DrawPoints (¶ms[0], static_cast<int> (params.size () / 2));
return (true);
}
///////////////////////////////////////////////////////////////////////////////////////////
pcl::visualization::PCLContextImageItem::PCLContextImageItem ()
{
image = vtkSmartPointer<vtkImageData>::New ();
}
| bsd-3-clause |
liupdhc/yii2-liuxy-demo | modules/components/assets/frontend/PageScriptAsset.php | 1348 | <?php
/**
* Created by PhpStorm.
* User: liu
* Date: 2015/12/26
* Time: 20:28
*/
namespace modules\components\assets\frontend;
use Yii;
use liuxy\frontend\assets\AbstractAsset;
/**
* Class PageScriptAsset
* @package modules\components\assets\frontend
*/
class PageScriptAsset extends AbstractAsset
{
/**
* 注册单个JS至页面
* @param $view \yii\web\View
* @param $js string
*/
public static function registerJsFile($view, $js) {
if (is_array($js)) {
foreach($js as $item) {
$file = Yii::getAlias('@webroot/static').'/scripts/pages/'.$js.'.js';
if (file_exists($file)) {
$view->registerJsFile(Yii::getAlias('@web/static').'/scripts/pages/'.$item.'.js?'.static::hash($file),
['depends'=>['modules\components\assets\frontend\BaseScriptAsset']]);
}
unset($file);
}
} else {
$file = Yii::getAlias('@webroot/static').'/scripts/pages/'.$js.'.js';
if (file_exists($file)) {
$view->registerJsFile(Yii::getAlias('@web/static').'/scripts/pages/'.$js.'.js?'.static::hash($file),
['depends'=>['modules\components\assets\frontend\BaseScriptAsset']]);
}
unset($file);
}
}
} | bsd-3-clause |
codebutler/savagesvg | src/SharpVectorCss/SharpVectors/Dom/Css/CssStyleSheet.cs | 6763 | using System;
using System.Xml;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections;
using SharpVectors.Dom.Stylesheets;
namespace SharpVectors.Dom.Css
{
/// <summary>
/// The CSSStyleSheet interface is a concrete interface used to represent a CSS style sheet i.e., a style sheet whose content type is "text/css".
/// </summary>
/// <developer>niklas@protocol7.com</developer>
/// <completed>80</completed>
public class CssStyleSheet: StyleSheet, ICssStyleSheet
{
#region Constructors
/// <summary>
/// Constructor for CssStyleSheet
/// </summary>
/// <param name="pi">The XML processing instruction that references the stylesheet</param>
/// <param name="origin">The type of stylesheet</param>
internal CssStyleSheet(XmlProcessingInstruction pi, CssStyleSheetType origin) : base(pi)
{
Origin = origin;
}
/// <summary>
/// Constructor for CssStyleSheet
/// </summary>
/// <param name="styleElement">The XML style element that references the stylesheet</param>
/// <param name="origin">The type of stylesheet</param>
internal CssStyleSheet(XmlElement styleElement, CssStyleSheetType origin) : base(styleElement)
{
Origin = origin;
}
/// <summary>
/// Constructor for CssStyleSheet
/// </summary>
/// <param name="ownerNode">The node that owns this stylesheet. E.g. used for getting the BaseUri</param>
/// <param name="href">The URL of the stylesheet</param>
/// <param name="title">The title of the stylesheet</param>
/// <param name="media">List of medias for the stylesheet</param>
/// <param name="ownerRule">The rule (e.g. ImportRule) that referenced this stylesheet</param>
/// <param name="origin">The type of stylesheet</param>
public CssStyleSheet(XmlNode ownerNode, string href, string title, string media, CssRule ownerRule, CssStyleSheetType origin) : base(ownerNode, href, "text/css", title, media)
{
Origin = origin;
this.ownerRule = ownerRule;
}
#endregion
#region Public methods
/// <summary>
/// Used to find matching style rules in the cascading order
/// </summary>
/// <param name="elt">The element to find styles for</param>
/// <param name="pseudoElt">The pseudo-element to find styles for</param>
/// <param name="ml">The medialist that the document is using</param>
/// <param name="csd">A CssStyleDeclaration that holds the collected styles</param>
protected internal override void GetStylesForElement(XmlElement elt, string pseudoElt, MediaList ml, CssCollectedStyleDeclaration csd)
{
if(((MediaList)Media).Matches(ml))
{
((CssRuleList)CssRules).GetStylesForElement(elt, pseudoElt, ml, csd);
}
}
#endregion
#region Private methods
private string StringReplaceEvaluator(Match match)
{
alReplacedStrings.Add(match.Value);
return "\"<<<" + (alReplacedStrings.Count-1) + ">>>\"";
}
private string PreProcessContent()
{
if(SheetContent != null && SheetContent.Length > 0)
{
// "escape" strings, eg: "foo" => "<<<number>>>"
Regex re = new Regex(@"(""(.|\n)*?[^\\]"")|('(.|\n)*?[^\\]')");
string s = re.Replace(SheetContent, new MatchEvaluator(StringReplaceEvaluator));
ReplacedStrings = (string[])alReplacedStrings.ToArray(s.GetType());
alReplacedStrings.Clear();
// remove comments
Regex reComment = new Regex(@"(//.*)|(/\*(.|\n)*?\*/)");
s = reComment.Replace(s, String.Empty);
return s;
}
else
{
return "";
}
}
#endregion
#region Private fields
private readonly CssStyleSheetType Origin;
private ArrayList alReplacedStrings = new ArrayList();
private string[] ReplacedStrings;
#endregion
#region Implementation of ICssStyleSheet
/// <summary>
/// Used to delete a rule from the style sheet.
/// </summary>
/// <param name="index">The index within the style sheet's rule list of the rule to remove.</param>
/// <exception cref="DomException">INDEX_SIZE_ERR: Raised if the specified index does not correspond to a rule in the style sheet's rule list.</exception>
/// <exception cref="DomException">NO_MODIFICATION_ALLOWED_ERR: Raised if this style sheet is readonly.</exception>
public void DeleteRule(ulong index)
{
((CssRuleList)CssRules).DeleteRule(index);
}
/// <summary>
/// Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade.
/// </summary>
/// <param name="rule">The parsable text representing the rule. For rule sets this contains both the selector and the style declaration. For at-rules, this specifies both the at-identifier and the rule content.</param>
/// <param name="index">The index within the style sheet's rule list of the rule before which to insert the specified rule. If the specified index is equal to the length of the style sheet's rule collection, the rule will be added to the end of the style sheet.</param>
/// <returns>The index within the style sheet's rule collection of the newly inserted rule.</returns>
/// <exception cref="DomException">INDEX_SIZE_ERR: Raised if the specified index does not correspond to a rule in the style sheet's rule list.</exception>
/// <exception cref="DomException">NO_MODIFICATION_ALLOWED_ERR: Raised if this style sheet is readonly.</exception>
/// <exception cref="DomException">HIERARCHY_REQUEST_ERR: Raised if the rule cannot be inserted at the specified index e.g. if an @import rule is inserted after a standard rule set or other at-rule.</exception>
/// <exception cref="DomException">SYNTAX_ERR: Raised if the specified rule has a syntax error and is unparsable.</exception>
public ulong InsertRule(string rule, ulong index)
{
throw new NotImplementedException("CssStyleSheet.InsertRule()");
//return ((CssRuleList)CssRules).InsertRule(rule, index);
}
private CssRuleList cssRules = null;
/// <summary>
/// The list of all CSS rules contained within the style sheet. This includes both rule sets and at-rules.
/// </summary>
public ICssRuleList CssRules
{
get
{
if(cssRules == null)
{
string css = PreProcessContent();
cssRules = new CssRuleList(ref css, this, ReplacedStrings, Origin);
}
return cssRules;
}
set
{
throw new NotImplementedException();
}
}
private CssRule ownerRule;
/// <summary>
/// If this style sheet comes from an @import rule, the ownerRule attribute will contain the CSSImportRule. In that case, the ownerNode attribute in the StyleSheet interface will be null. If the style sheet comes from an element or a processing instruction, the ownerRule attribute will be null and the ownerNode attribute will contain the Node.
/// </summary>
public ICssRule OwnerRule
{
get
{
return ownerRule;
}
}
#endregion
}
}
| bsd-3-clause |
OWASP/django-DefectDojo | dojo/management/commands/system_settings.py | 1039 | from django.core.management.base import BaseCommand
from dojo.models import System_Settings
class Command(BaseCommand):
help = 'Updates product grade calculation'
def handle(self, *args, **options):
code = """def grade_product(crit, high, med, low):
health=100
if crit > 0:
health = 40
health = health - ((crit - 1) * 5)
if high > 0:
if health == 100:
health = 60
health = health - ((high - 1) * 3)
if med > 0:
if health == 100:
health = 80
health = health - ((med - 1) * 2)
if low > 0:
if health == 100:
health = 95
health = health - low
if health < 5:
health = 5
return health
"""
system_settings = System_Settings.objects.get(id=1)
system_settings.product_grade = code
system_settings.save()
| bsd-3-clause |
smcgov/ohana-api-smc | db/migrate/20140328042108_create_faxes.rb | 262 | class CreateFaxes < ActiveRecord::Migration
def change
create_table :faxes do |t|
t.belongs_to :location, null: false
t.text :number, null: false
t.text :department
t.timestamps
end
add_index :faxes, :location_id
end
end
| bsd-3-clause |
AlexanderFabisch/cythonwrapper | pywrap/cython.py | 6134 | import os
import sys
from .defaultconfig import Config
from .exporter import CythonDeclarationExporter, CythonImplementationExporter
from .parser import Parser, Includes, TypeInfo
from .ast import postprocess_asts
from .templates import render
from .utils import make_header, file_ending, hidden_stdout, hidden_stderr
def load_config(custom_config):
"""Load configuration.
Parameters
----------
custom_config : str
Name of the configuration file, must have the file ending ".py"
"""
if custom_config is None:
return Config()
if not os.path.exists(custom_config):
raise ValueError("Configuration file '%s' does not exist."
% custom_config)
parts = custom_config.split(os.sep)
path = os.sep.join(parts[:-1])
filename = parts[-1]
module = _derive_module_name_from(filename)
sys.path.insert(0, path)
imported_module = __import__(module)
sys.path.pop(0)
return imported_module.config
def make_cython_wrapper(filenames, sources, modulename=None, target=".",
config=Config(), incdirs=(), compiler_flags=("-O3",),
verbose=0):
"""Make Cython wrapper for C++ files.
Parameters
----------
filenames : list of strings or string
C++ files
sources : list of strings
C++ source files that have to be compiled
modulename : string, optional (default: name of the only header)
Name of the module
target : string, optional (default: ".")
Target directory
config : Config, optional (default: defaultconfig.Config())
Configuration
incdirs : list, optional (default: [])
Include directories
compiler_flags : list, optional (default: ["-O3"])
Flags that will be passed directly to the compiler when building the
extension
verbose : int, optional (default: 0)
Verbosity level
Returns
-------
results : dict
Mapping from filename to generated file content
"""
if isinstance(filenames, str):
filenames = [filenames]
if len(filenames) == 1 and modulename is None:
modulename = _derive_module_name_from(filenames[0])
if modulename is None:
raise ValueError("Please give a module name when there are multiple "
"C++ files that you want to wrap.")
for incdir in incdirs:
if not os.path.exists(incdir):
raise ValueError("Include directory '%s' does not exist." % incdir)
for filename in filenames:
if file_ending(filename) not in config.cpp_header_endings:
raise ValueError("'%s' does not seem to be a header file which is "
"required." % filename)
if not os.path.exists(filename):
raise ValueError("File '%s' does not exist" % filename)
includes, type_info, asts = _parse_files(
filenames, config, incdirs, verbose)
postprocess_asts(asts)
results = dict(
[_make_extension(modulename, asts, includes, type_info, config),
_make_declarations(asts, includes, config),
_make_setup(sources, modulename, target, incdirs, compiler_flags,
config)]
)
if verbose >= 2:
for filename in sorted(results.keys()):
print(make_header("Exporting file '%s':" % filename))
print(results[filename])
return results
def _derive_module_name_from(filename):
filename = filename.split(os.sep)[-1]
return filename.split(".")[0]
def _parse_files(filenames, config, incdirs, verbose):
includes = Includes()
type_info = TypeInfo(config)
asts = []
for filename in filenames:
parser = Parser(filename, includes, type_info, incdirs, verbose)
asts.append(parser.parse())
return includes, type_info, asts
def _make_extension(modulename, asts, includes, type_info, config):
cie = CythonImplementationExporter(includes, type_info, config)
for ast in asts:
ast.accept(cie)
pyx_filename = modulename + "." + config.pyx_file_ending
body = cie.export()
extension = includes.implementations_import() + body
return pyx_filename, extension
def _make_declarations(asts, includes, config):
cde = CythonDeclarationExporter(includes, config)
for ast in asts:
ast.accept(cde)
body = cde.export()
declarations = includes.declarations_import() + body
for decl in config.additional_declerations:
declarations += decl
pxd_filename = "_declarations." + config.pxd_file_ending
return pxd_filename, declarations
def _make_setup(sources, modulename, target, incdirs, compiler_flags, config):
sourcedir = os.path.relpath(".", start=target)
source_relpaths = [os.path.relpath(filename, start=target)
for filename in sources]
return "setup.py", render("setup", filenames=source_relpaths,
module=modulename, sourcedir=sourcedir,
incdirs=incdirs, compiler_flags=compiler_flags,
library_dirs=config.library_dirs,
libraries=config.libraries)
def write_files(files, target="."):
"""Write files.
Parameters
----------
files : dict
Mapping from file name to content
target : string, optional (default: '.')
Target directory
"""
for filename, content in files.items():
outputfile = os.path.join(target, filename)
with open(outputfile, "w") as f:
f.write(content)
def run_setup(setuppy_name="setup.py", hide_errors=False):
"""Run setup script to build extension.
Parameters
----------
setuppy_name : str, optional (default: 'setup.py')
Setup script name
hide_errors : bool, optional (default: False)
Hide output to stderr
"""
cmd = "python %s build_ext --inplace" % setuppy_name
with hidden_stdout():
if hide_errors:
with hidden_stderr():
os.system(cmd)
else:
os.system(cmd)
| bsd-3-clause |
cvsuser-chromium/chromium | cc/resources/scoped_resource_unittest.cc | 4305 | // Copyright 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 "cc/resources/scoped_resource.h"
#include "cc/output/renderer.h"
#include "cc/test/fake_output_surface.h"
#include "cc/test/fake_output_surface_client.h"
#include "cc/test/tiled_layer_test_common.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace cc {
namespace {
TEST(ScopedResourceTest, NewScopedResource) {
FakeOutputSurfaceClient output_surface_client;
scoped_ptr<OutputSurface> output_surface(FakeOutputSurface::Create3d());
CHECK(output_surface->BindToClient(&output_surface_client));
scoped_ptr<ResourceProvider> resource_provider(
ResourceProvider::Create(output_surface.get(), NULL, 0, false, 1));
scoped_ptr<ScopedResource> texture =
ScopedResource::create(resource_provider.get());
// New scoped textures do not hold a texture yet.
EXPECT_EQ(0u, texture->id());
// New scoped textures do not have a size yet.
EXPECT_EQ(gfx::Size(), texture->size());
EXPECT_EQ(0u, texture->bytes());
}
TEST(ScopedResourceTest, CreateScopedResource) {
FakeOutputSurfaceClient output_surface_client;
scoped_ptr<OutputSurface> output_surface(FakeOutputSurface::Create3d());
CHECK(output_surface->BindToClient(&output_surface_client));
scoped_ptr<ResourceProvider> resource_provider(
ResourceProvider::Create(output_surface.get(), NULL, 0, false, 1));
scoped_ptr<ScopedResource> texture =
ScopedResource::create(resource_provider.get());
texture->Allocate(gfx::Size(30, 30),
ResourceProvider::TextureUsageAny,
RGBA_8888);
// The texture has an allocated byte-size now.
size_t expected_bytes = 30 * 30 * 4;
EXPECT_EQ(expected_bytes, texture->bytes());
EXPECT_LT(0u, texture->id());
EXPECT_EQ(static_cast<unsigned>(RGBA_8888), texture->format());
EXPECT_EQ(gfx::Size(30, 30), texture->size());
}
TEST(ScopedResourceTest, ScopedResourceIsDeleted) {
FakeOutputSurfaceClient output_surface_client;
scoped_ptr<OutputSurface> output_surface(FakeOutputSurface::Create3d());
CHECK(output_surface->BindToClient(&output_surface_client));
scoped_ptr<ResourceProvider> resource_provider(
ResourceProvider::Create(output_surface.get(), NULL, 0, false, 1));
{
scoped_ptr<ScopedResource> texture =
ScopedResource::create(resource_provider.get());
EXPECT_EQ(0u, resource_provider->num_resources());
texture->Allocate(gfx::Size(30, 30),
ResourceProvider::TextureUsageAny,
RGBA_8888);
EXPECT_LT(0u, texture->id());
EXPECT_EQ(1u, resource_provider->num_resources());
}
EXPECT_EQ(0u, resource_provider->num_resources());
{
scoped_ptr<ScopedResource> texture =
ScopedResource::create(resource_provider.get());
EXPECT_EQ(0u, resource_provider->num_resources());
texture->Allocate(gfx::Size(30, 30),
ResourceProvider::TextureUsageAny,
RGBA_8888);
EXPECT_LT(0u, texture->id());
EXPECT_EQ(1u, resource_provider->num_resources());
texture->Free();
EXPECT_EQ(0u, resource_provider->num_resources());
}
}
TEST(ScopedResourceTest, LeakScopedResource) {
FakeOutputSurfaceClient output_surface_client;
scoped_ptr<OutputSurface> output_surface(FakeOutputSurface::Create3d());
CHECK(output_surface->BindToClient(&output_surface_client));
scoped_ptr<ResourceProvider> resource_provider(
ResourceProvider::Create(output_surface.get(), NULL, 0, false, 1));
{
scoped_ptr<ScopedResource> texture =
ScopedResource::create(resource_provider.get());
EXPECT_EQ(0u, resource_provider->num_resources());
texture->Allocate(gfx::Size(30, 30),
ResourceProvider::TextureUsageAny,
RGBA_8888);
EXPECT_LT(0u, texture->id());
EXPECT_EQ(1u, resource_provider->num_resources());
texture->Leak();
EXPECT_EQ(0u, texture->id());
EXPECT_EQ(1u, resource_provider->num_resources());
texture->Free();
EXPECT_EQ(0u, texture->id());
EXPECT_EQ(1u, resource_provider->num_resources());
}
EXPECT_EQ(1u, resource_provider->num_resources());
}
} // namespace
} // namespace cc
| bsd-3-clause |
cedriclaunay/gaffer | src/GafferImageBindings/FormatPlugBinding.cpp | 4207 | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012-2013, Image Engine Design 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:
//
// * 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 John Haddon nor the names of
// any other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "boost/format.hpp"
#include "GafferBindings/Serialisation.h"
#include "GafferBindings/ValuePlugBinding.h"
#include "GafferBindings/TypedPlugBinding.h"
#include "GafferImage/FormatPlug.h"
#include "GafferImageBindings/FormatBinding.h"
#include "GafferImageBindings/FormatPlugBinding.h"
using namespace std;
using namespace boost::python;
using namespace Gaffer;
using namespace GafferBindings;
using namespace GafferImage;
using namespace GafferImageBindings;
namespace
{
class FormatPlugSerialiser : public GafferBindings::ValuePlugSerialiser
{
public :
virtual void moduleDependencies( const Gaffer::GraphComponent *graphComponent, std::set<std::string> &modules ) const
{
ValuePlugSerialiser::moduleDependencies( graphComponent, modules );
modules.insert( "IECore" );
}
virtual std::string constructor( const Gaffer::GraphComponent *graphComponent ) const
{
object o( GraphComponentPtr( const_cast<GraphComponent *>( graphComponent ) ) );
std::string r = extract<std::string>( o.attr( "__repr__" )() );
return r;
}
virtual std::string postConstructor( const Gaffer::GraphComponent *graphComponent, const std::string &identifier, const Serialisation &serialisation ) const
{
std::string result;
const Plug *plug = static_cast<const Plug *>( graphComponent );
if( plug->node()->typeId() == static_cast<IECore::TypeId>(ScriptNodeTypeId) )
{
// If this is the default format plug then write out all of the formats.
/// \todo Why do we do this? Unfortunately it's very hard to tell because
/// there are no unit tests for it. Why don't we allow the config files to
/// just recreate the formats next time?
vector<string> names;
GafferImage::Format::formatNames( names );
for( vector<string>::const_iterator it = names.begin(), eIt = names.end(); it != eIt; ++it )
{
result +=
"GafferImage.Format.registerFormat( " +
formatRepr( Format::getFormat( *it ) ) +
", \"" + *it + "\" )\n";
}
}
result += ValuePlugSerialiser::postConstructor( graphComponent, identifier, serialisation );
return result;
}
};
} // namespace
void GafferImageBindings::bindFormatPlug()
{
TypedPlugClass<FormatPlug>();
Serialisation::registerSerialiser( static_cast<IECore::TypeId>(FormatPlugTypeId), new FormatPlugSerialiser );
}
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s02/CWE762_Mismatched_Memory_Management_Routines__delete_array_wchar_t_realloc_42.cpp | 3401 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_wchar_t_realloc_42.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml
Template File: sources-sinks-42.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: realloc Allocate data using realloc()
* GoodSource: Allocate data using new []
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete []
* Flow Variant: 42 Data flow: data returned from one function to another in the same source file
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_wchar_t_realloc_42
{
#ifndef OMITBAD
static wchar_t * badSource(wchar_t * data)
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (wchar_t *)realloc(data, 100*sizeof(wchar_t));
if (data == NULL) {exit(-1);}
return data;
}
void bad()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
data = badSource(data);
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static wchar_t * goodG2BSource(wchar_t * data)
{
/* FIX: Allocate memory using new [] */
data = new wchar_t[100];
return data;
}
static void goodG2B()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
data = goodG2BSource(data);
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
/* goodB2G() uses the BadSource with the GoodSink */
static wchar_t * goodB2GSource(wchar_t * data)
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (wchar_t *)realloc(data, 100*sizeof(wchar_t));
if (data == NULL) {exit(-1);}
return data;
}
static void goodB2G()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
data = goodB2GSource(data);
/* FIX: Free memory using free() */
free(data);
}
void good()
{
goodG2B();
goodB2G();
}
#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 CWE762_Mismatched_Memory_Management_Routines__delete_array_wchar_t_realloc_42; /* 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 |
amanjpro/languages-a-la-carte | ppj/src/main/scala/ast/TreeUtils.scala | 2944 | /*
* Copyright (c) <2015-2016>, see CONTRIBUTORS
* 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 <organization> 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 <COPYRIGHT HOLDER> 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 ch.usi.inf.l3.sana.ppj.ast
import ch.usi.inf.l3.sana
import sana.tiny
import sana.calcj
import sana.primj
import sana.brokenj
import sana.ooj
import sana.arrayj
import sana.arrooj
import sana.robustj
import sana.dynj
import sana.ppj
import tiny.ast.Tree
import primj.ast.{MethodDefApi => _, _}
import ooj.ast.{MethodDefApi => _, _}
import brokenj.ast.BreakApi
import calcj.ast.Constant
import robustj.ast._
import ppj.ast.TreeExtractors._
trait TreeUtils extends robustj.ast.TreeUtils {
override def isValidStatement(e: Tree): Boolean = e match {
case _: SynchronizedApi => true
case _ => super.isValidStatement(e)
}
override def allPathsReturn(expr: Tree): Boolean =
allPathsReturnAux(expr, allPathsReturn)
override protected def allPathsReturnAux(expr: Tree,
recurse: Tree => Boolean): Boolean = expr match {
case s: SynchronizedApi => recurse(s.block)
case _ => super.allPathsReturnAux(expr, recurse)
}
override def isSimpleExpression(tree: Tree): Boolean = tree match {
case _: SynchronizedApi => false
case _ => super.isSimpleExpression(tree)
}
override def canHaveLabel(tree: Tree): Boolean = tree match {
case _: SynchronizedApi => true
case _ => super.isValidStatement(tree)
}
}
object TreeUtils extends TreeUtils
| bsd-3-clause |
Hyperion3360/HyperionRobot2014 | src/org/usfirst/frc3360/Hyperion2014/commands/Canon_ShootTopGoalTeleop.java | 1054 | // RobotBuilder Version: 1.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc3360.Hyperion2014.commands;
import edu.wpi.first.wpilibj.command.CommandGroup;
import org.usfirst.frc3360.Hyperion2014.Robot;
/**
*
*/
public class Canon_ShootTopGoalTeleop extends CommandGroup {
public Canon_ShootTopGoalTeleop() {
//System.out.println("new Canon_ShootTopGoalAutonomous");
addParallel(new CanonAngle_SetShooterAngle(true));
addSequential(new SystemWait(0.8));
addSequential(new CanonShooter_Shoot());
addSequential(new CanonAngle_SetShooterAngle(45), 0.3);
}
}
| bsd-3-clause |
nicksenger/JSchematic | src/js/containers/bondSystems/cyclopentane.js | 4625 | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { createElement, saveState } from '../../actions/index';
import { calcRotation } from '../../utilities/sharedFunctions';
import BasicBond from '../basicBond';
require("../../../css/components/doubleBond.scss");
class Cyclopentane extends Component {
constructor(props){
super(props);
this.state = {
id: 'cyclopentyl',
active: true,
fixedRotation: 0,
lockPositions: null,
ignoreChildren: []
}
}
componentWillMount(){
this.setState(this.props.state ? this.props.state : this.state);
const content = [
{
name: 'singleBond',
type: 'BasicBond',
key: Math.random().toString(36),
elkey: Math.random().toString(36),
inputCoords: {x: 0, y: 0},
refCoords: this.props.inputCoords,
offset: {
azimuth: 0,
origin: "50% 0%"
},
nested: this.props.elkey
},
{
name: 'singleBond',
type: 'BasicBond',
key: Math.random().toString(36),
elkey: Math.random().toString(36),
inputCoords: {x: 0, y: 0},
refCoords: this.props.inputCoords,
offset: {
azimuth: -108,
origin: "50% 0%"
},
nested: this.props.elkey
},
{
name: 'singleBond',
type: 'BasicBond',
key: Math.random().toString(36),
elkey: Math.random().toString(36),
inputCoords: {x: 0, y: 22},
refCoords: this.props.inputCoords,
offset: {
azimuth: -72,
origin: "50% 0%"
},
nested: this.props.elkey
},
{
name: 'singleBond',
type: 'BasicBond',
key: Math.random().toString(36),
elkey: Math.random().toString(36),
inputCoords: {x: 20.9234, y: -6.798},
refCoords: this.props.inputCoords,
offset: {
azimuth: -36,
origin: "50% 0%"
},
nested: this.props.elkey
},
{
name: 'singleBond',
type: 'BasicBond',
key: Math.random().toString(36),
elkey: Math.random().toString(36),
inputCoords: {x: 20.9234, y: 28.798},
refCoords: this.props.inputCoords,
offset: {
azimuth: -144,
origin: "50% 0%"
},
nested: this.props.elkey
},
];
content.forEach(function(item){
this.props.createElement(item);
}.bind(this))
}
componentWillReceiveProps(nextProps){
if (this.props.canvasDown && this.state.active && nextProps.canvasUp){
this.setState({active: false, fixedRotation: calcRotation(this)});
this.props.saveState({elkey: this.props.elkey, state: {...this.state, active: false, fixedRotation: calcRotation(this)}});
}
}
render(){
const components = { BasicBond };
const children = this.props.elements.filter((child) => {
return (child.nested == this.props.elkey);
})
const renderChildren = children.map((element, index) => {
const Type = components[element.type];
if (this.state.ignoreChildren.indexOf(index) == -1){
return <Type name={element.name} key={element.key} elkey={element.elkey} inputCoords={element.inputCoords} refCoords={element.refCoords} offset={element.offset} nested={element.nested}/>
} else {
return <div key={element.key} />
}
})
const azimuth = calcRotation(this);
const offset = this.props.offset;
const elementStyle = {
left: this.props.inputCoords.x - 0.1,
top: this.props.inputCoords.y,
width: this.props.elementSizes[this.props.name].width,
height: this.props.elementSizes[this.props.name].height,
transform: (this.props.nested ? `rotate(${offset.azimuth}deg)` : ((this.props.canvasDown && this.state.active) ? `rotate(${azimuth}deg)` : `rotate(${this.state.fixedRotation}deg)`)),
transformOrigin: '6% 0px'
}
return (
<div className='doubleBond' style={elementStyle}>{renderChildren}</div>
)
}
}
function mapStateToProps({canvasDown, canvasUp, elements, elementSizes, coordinates, highlights}) {
return {canvasDown, canvasUp, elements, elementSizes, coordinates, highlights}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ createElement, saveState }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Cyclopentane);
| bsd-3-clause |
Rusk85/CavemanToolBySapiensworks | src/CavemanTools.Web/CavemanHashStrategy.cs | 857 | using System;
namespace CavemanTools.Web
{
public class CavemanHashStrategy:IHashPassword
{
/// <summary>
/// Creates a hash for a string using salt
/// </summary>
/// <param name="text">Value to hash</param>
/// <param name="salt">Optional random string</param>
/// <returns></returns>
public string Hash(string text, string salt = null)
{
if (salt==null) throw new ArgumentException("Salt is required for this hash");
if (salt.Length%2 != 0)
{
salt=salt.PadRight(salt.Length + 1, '*');
}
var first = salt.Substring(0, salt.Length/2);
var pwd = first + text+salt.Substring(salt.Length/2,salt.Length/2);
return pwd.Sha512();
}
}
} | bsd-3-clause |
mako-framework/framework | src/mako/http/request/Headers.php | 5658 | <?php
/**
* @copyright Frederic G. Østby
* @license http://www.makoframework.com/license
*/
namespace mako\http\request;
use ArrayIterator;
use Countable;
use IteratorAggregate;
use function array_merge;
use function array_values;
use function count;
use function explode;
use function krsort;
use function str_replace;
use function stripos;
use function strpos;
use function strtoupper;
use function substr;
use function trim;
/**
* Headers.
*/
class Headers implements Countable, IteratorAggregate
{
/**
* Headers.
*
* @var array
*/
protected $headers;
/**
* Acceptable content types.
*
* @var array
*/
protected $acceptableContentTypes;
/**
* Acceptable languages.
*
* @var array
*/
protected $acceptableLanguages;
/**
* Acceptable character sets.
*
* @var array
*/
protected $acceptableCharsets;
/**
* Acceptable encodings.
*
* @var array
*/
protected $acceptableEncodings;
/**
* Constructor.
*
* @param array $headers Headers
*/
public function __construct(array $headers = [])
{
$this->headers = $headers;
}
/**
* Returns the numner of headers.
*
* @return int
*/
public function count(): int
{
return count($this->headers);
}
/**
* Retruns an array iterator object.
*
* @return \ArrayIterator
*/
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->headers);
}
/**
* Normalizes header names.
*
* @param string $name Header name
* @return string
*/
protected function normalizeName(string $name): string
{
return strtoupper(str_replace('-', '_', $name));
}
/**
* Adds a header.
*
* @param string $name Header name
* @param string $value Header value
*/
public function add(string $name, string $value): void
{
$this->headers[$this->normalizeName($name)] = $value;
}
/**
* Returns TRUE if the header exists and FALSE if not.
*
* @param string $name Header name
* @return bool
*/
public function has(string $name): bool
{
return isset($this->headers[$this->normalizeName($name)]);
}
/**
* Gets a header value.
*
* @param string $name Header name
* @param mixed $default Default value
* @return mixed
*/
public function get(string $name, $default = null)
{
return $this->headers[$this->normalizeName($name)] ?? $default;
}
/**
* Removes a header.
*
* @param string $name Header name
*/
public function remove(string $name): void
{
unset($this->headers[$this->normalizeName($name)]);
}
/**
* Returns all the headers.
*
* @return array
*/
public function all(): array
{
return $this->headers;
}
/**
* Parses a accpet header and returns the values in descending order of preference.
*
* @param string|null $headerValue Header value
* @return array
*/
protected function parseAcceptHeader(?string $headerValue): array
{
$groupedAccepts = [];
if(empty($headerValue))
{
return $groupedAccepts;
}
// Collect acceptable values
foreach(explode(',', $headerValue) as $accept)
{
$quality = 1;
if(strpos($accept, ';'))
{
// We have a quality so we need to split some more
[$accept, $quality] = explode(';', $accept, 2);
// Strip the "q=" part so that we're left with only the numeric value
$quality = substr(trim($quality), 2);
}
$groupedAccepts[$quality][] = trim($accept);
}
// Sort in descending order of preference
krsort($groupedAccepts);
// Flatten array and return it
return array_merge(...array_values($groupedAccepts));
}
/**
* Returns an array of acceptable content types in descending order of preference.
*
* @param string|null $default Default content type
* @return array
*/
public function getAcceptableContentTypes(?string $default = null): array
{
if(!isset($this->acceptableContentTypes))
{
$this->acceptableContentTypes = $this->parseAcceptHeader($this->get('accept'));
}
return $this->acceptableContentTypes ?: (array) $default;
}
/**
* Returns an array of acceptable content types in descending order of preference.
*
* @param string|null $default Default language
* @return array
*/
public function getAcceptableLanguages(?string $default = null): array
{
if(!isset($this->acceptableLanguages))
{
$this->acceptableLanguages = $this->parseAcceptHeader($this->get('accept-language'));
}
return $this->acceptableLanguages ?: (array) $default;
}
/**
* Returns an array of acceptable content types in descending order of preference.
*
* @param string|null $default Default charset
* @return array
*/
public function getAcceptableCharsets(?string $default = null): array
{
if(!isset($this->acceptableCharsets))
{
$this->acceptableCharsets = $this->parseAcceptHeader($this->get('accept-charset'));
}
return $this->acceptableCharsets ?: (array) $default;
}
/**
* Returns an array of acceptable content types in descending order of preference.
*
* @param string|null $default Default encoding
* @return array
*/
public function getAcceptableEncodings(?string $default = null): array
{
if(!isset($this->acceptableEncodings))
{
$this->acceptableEncodings = $this->parseAcceptHeader($this->get('accept-encoding'));
}
return $this->acceptableEncodings ?: (array) $default;
}
/**
* Returns the bearer token or NULL if there isn't one.
*
* @return string|null
*/
public function getBearerToken(): ?string
{
if(($value = $this->get('authorization')) === null)
{
return null;
}
if(($pos = stripos($value, 'Bearer ')) === false)
{
return null;
}
return substr($value, $pos + 7);
}
}
| bsd-3-clause |
fredd-for/codice | ckeditor/_source/core/htmlparser.js | 6656 | /*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* Creates a {@link CKEDITOR.htmlParser} class instance.
* @class Provides an "event like" system to parse strings of HTML data.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onTagOpen = function( tagName, attributes, selfClosing )
* {
* alert( tagName );
* };
* parser.parse( '<p>Some <b>text</b>.</p>' );
*/
CKEDITOR.htmlParser = function()
{
this._ =
{
htmlPartsRegex : new RegExp( '<(?:(?:\\/([^>]+)>)|(?:!--([\\S|\\s]*?)-->)|(?:([^\\s>]+)\\s*((?:(?:[^"\'>]+)|(?:"[^"]*")|(?:\'[^\']*\'))*)\\/?>))', 'g' )
};
};
(function()
{
var attribsRegex = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g,
emptyAttribs = {checked:1,compact:1,declare:1,defer:1,disabled:1,ismap:1,multiple:1,nohref:1,noresize:1,noshade:1,nowrap:1,readonly:1,selected:1};
CKEDITOR.htmlParser.prototype =
{
/**
* Function to be fired when a tag opener is found. This function
* should be overriden when using this class.
* @param {String} tagName The tag name. The name is guarantted to be
* lowercased.
* @param {Object} attributes An object containing all tag attributes. Each
* property in this object represent and attribute name and its
* value is the attribute value.
* @param {Boolean} selfClosing true if the tag closes itself, false if the
* tag doesn't.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onTagOpen = function( tagName, attributes, selfClosing )
* {
* alert( tagName ); // e.g. "b"
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onTagOpen : function() {},
/**
* Function to be fired when a tag closer is found. This function
* should be overriden when using this class.
* @param {String} tagName The tag name. The name is guarantted to be
* lowercased.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onTagClose = function( tagName )
* {
* alert( tagName ); // e.g. "b"
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onTagClose : function() {},
/**
* Function to be fired when text is found. This function
* should be overriden when using this class.
* @param {String} text The text found.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onText = function( text )
* {
* alert( text ); // e.g. "Hello"
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onText : function() {},
/**
* Function to be fired when CDATA section is found. This function
* should be overriden when using this class.
* @param {String} cdata The CDATA been found.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onCDATA = function( cdata )
* {
* alert( cdata ); // e.g. "var hello;"
* });
* parser.parse( "<script>var hello;</script>" );
*/
onCDATA : function() {},
/**
* Function to be fired when a commend is found. This function
* should be overriden when using this class.
* @param {String} comment The comment text.
* @example
* var parser = new CKEDITOR.htmlParser();
* parser.onComment = function( comment )
* {
* alert( comment ); // e.g. " Example "
* });
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
onComment : function() {},
/**
* Parses text, looking for HTML tokens, like tag openers or closers,
* or comments. This function fires the onTagOpen, onTagClose, onText
* and onComment function during its execution.
* @param {String} html The HTML to be parsed.
* @example
* var parser = new CKEDITOR.htmlParser();
* // The onTagOpen, onTagClose, onText and onComment should be overriden
* // at this point.
* parser.parse( "<!-- Example --><b>Hello</b>" );
*/
parse : function( html )
{
var parts,
tagName,
nextIndex = 0,
cdata; // The collected data inside a CDATA section.
while ( ( parts = this._.htmlPartsRegex.exec( html ) ) )
{
var tagIndex = parts.index;
if ( tagIndex > nextIndex )
{
var text = html.substring( nextIndex, tagIndex );
if ( cdata )
cdata.push( text );
else
this.onText( text );
}
nextIndex = this._.htmlPartsRegex.lastIndex;
/*
"parts" is an array with the following items:
0 : The entire match for opening/closing tags and comments.
1 : Group filled with the tag name for closing tags.
2 : Group filled with the comment text.
3 : Group filled with the tag name for opening tags.
4 : Group filled with the attributes part of opening tags.
*/
// Closing tag
if ( ( tagName = parts[ 1 ] ) )
{
tagName = tagName.toLowerCase();
if ( cdata && CKEDITOR.dtd.$cdata[ tagName ] )
{
// Send the CDATA data.
this.onCDATA( cdata.join('') );
cdata = null;
}
if ( !cdata )
{
this.onTagClose( tagName );
continue;
}
}
// If CDATA is enabled, just save the raw match.
if ( cdata )
{
cdata.push( parts[ 0 ] );
continue;
}
// Opening tag
if ( ( tagName = parts[ 3 ] ) )
{
tagName = tagName.toLowerCase();
// There are some tag names that can break things, so let's
// simply ignore them when parsing. (#5224)
if ( /="/.test( tagName ) )
continue;
var attribs = {},
attribMatch,
attribsPart = parts[ 4 ],
selfClosing = !!( attribsPart && attribsPart.charAt( attribsPart.length - 1 ) == '/' );
if ( attribsPart )
{
while ( ( attribMatch = attribsRegex.exec( attribsPart ) ) )
{
var attName = attribMatch[1].toLowerCase(),
attValue = attribMatch[2] || attribMatch[3] || attribMatch[4] || '';
if ( !attValue && emptyAttribs[ attName ] )
attribs[ attName ] = attName;
else
attribs[ attName ] = attValue;
}
}
this.onTagOpen( tagName, attribs, selfClosing );
// Open CDATA mode when finding the appropriate tags.
if ( !cdata && CKEDITOR.dtd.$cdata[ tagName ] )
cdata = [];
continue;
}
// Comment
if ( ( tagName = parts[ 2 ] ) )
this.onComment( tagName );
}
if ( html.length > nextIndex )
this.onText( html.substring( nextIndex, html.length ) );
}
};
})();
| bsd-3-clause |
Workday/OpenFrame | chrome/browser/ui/android/infobars/infobar_android.cc | 2673 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/android/infobars/infobar_android.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/strings/string_util.h"
#include "chrome/browser/android/resource_mapper.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "components/infobars/core/infobar.h"
#include "components/infobars/core/infobar_delegate.h"
#include "jni/InfoBar_jni.h"
// InfoBarAndroid -------------------------------------------------------------
InfoBarAndroid::InfoBarAndroid(scoped_ptr<infobars::InfoBarDelegate> delegate)
: infobars::InfoBar(delegate.Pass()) {
}
InfoBarAndroid::~InfoBarAndroid() {
if (!java_info_bar_.is_null()) {
JNIEnv* env = base::android::AttachCurrentThread();
Java_InfoBar_onNativeDestroyed(env, java_info_bar_.obj());
}
}
void InfoBarAndroid::ReassignJavaInfoBar(InfoBarAndroid* replacement) {
DCHECK(replacement);
if (!java_info_bar_.is_null()) {
replacement->SetJavaInfoBar(java_info_bar_);
java_info_bar_.Reset();
}
}
void InfoBarAndroid::SetJavaInfoBar(
const base::android::JavaRef<jobject>& java_info_bar) {
DCHECK(java_info_bar_.is_null());
java_info_bar_.Reset(java_info_bar);
JNIEnv* env = base::android::AttachCurrentThread();
Java_InfoBar_setNativeInfoBar(env, java_info_bar.obj(),
reinterpret_cast<intptr_t>(this));
}
jobject InfoBarAndroid::GetJavaInfoBar() {
return java_info_bar_.obj();
}
bool InfoBarAndroid::HasSetJavaInfoBar() const {
return !java_info_bar_.is_null();
}
void InfoBarAndroid::OnButtonClicked(JNIEnv* env,
const JavaParamRef<jobject>& obj,
jint action) {
ProcessButton(action);
}
void InfoBarAndroid::OnCloseButtonClicked(JNIEnv* env,
const JavaParamRef<jobject>& obj) {
if (!owner())
return; // We're closing; don't call anything, it might access the owner.
delegate()->InfoBarDismissed();
RemoveSelf();
}
void InfoBarAndroid::CloseJavaInfoBar() {
if (!java_info_bar_.is_null()) {
JNIEnv* env = base::android::AttachCurrentThread();
Java_InfoBar_closeInfoBar(env, java_info_bar_.obj());
}
}
int InfoBarAndroid::GetEnumeratedIconId() {
return ResourceMapper::MapFromChromiumId(delegate()->GetIconId());
}
// Native JNI methods ---------------------------------------------------------
bool RegisterNativeInfoBar(JNIEnv* env) {
return RegisterNativesImpl(env);
}
| bsd-3-clause |
amanjpro/languages-a-la-carte | dynj/src/main/scala/ast/operators.scala | 1843 | /*
* Copyright (c) <2015-2016>, see CONTRIBUTORS
* 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 <organization> 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 <COPYRIGHT HOLDER> 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 ch.usi.inf.l3.sana.dynj.ast
import ch.usi.inf.l3.sana.calcj
import calcj.ast.operators.BOp
object operators {
/** A binary operator for `instanceof` operator in Java */
object InstanceOf extends BOp {
override def toString: String = "instanceof"
}
}
| bsd-3-clause |
sebcrozet/ncollide | src/shape/shape.rs | 5722 | // Queries.
use crate::bounding_volume::{BoundingSphere, AABB};
use crate::math::{Isometry, Vector};
use crate::query::{PointQuery, RayCast};
use crate::shape::{CompositeShape, ConvexPolyhedron, DeformableShape, FeatureId, SupportMap};
use downcast_rs::Downcast;
use na::{self, RealField, Unit};
use std::ops::Deref;
use std::sync::Arc;
pub trait ShapeClone<N: RealField> {
/// Construct an `Arc` that refers to a uniquely-owned copy of `self`
fn clone_arc(&self) -> Arc<dyn Shape<N>>;
}
impl<N: RealField, T: 'static + Shape<N> + Clone> ShapeClone<N> for T {
fn clone_arc(&self) -> Arc<dyn Shape<N>> {
Arc::new(self.clone())
}
}
/// Trait implemented by all shapes supported by ncollide.
///
/// This allows dynamic inspection of the shape capabilities.
pub trait Shape<N: RealField>: Send + Sync + Downcast + ShapeClone<N> {
/// The AABB of `self` transformed by `m`.
fn aabb(&self, m: &Isometry<N>) -> AABB<N>;
/// The AABB of `self`.
#[inline]
fn local_aabb(&self) -> AABB<N> {
self.aabb(&Isometry::identity())
}
/// The bounding sphere of `self` transformed by `m`.
#[inline]
fn bounding_sphere(&self, m: &Isometry<N>) -> BoundingSphere<N> {
let aabb = self.aabb(m);
BoundingSphere::new(aabb.center(), aabb.half_extents().norm())
}
/// The bounding sphere of `self`.
#[inline]
fn local_bounding_sphere(&self) -> BoundingSphere<N> {
let aabb = self.local_aabb();
BoundingSphere::new(aabb.center(), aabb.half_extents().norm())
}
/// Check if if the feature `_feature` of the `i-th` subshape of `self` transformed by `m` has a tangent
/// cone that contains `dir` at the point `pt`.
// NOTE: for the moment, we assume the tangent cone is the same for the whole feature.
fn tangent_cone_contains_dir(
&self,
_feature: FeatureId,
_m: &Isometry<N>,
_deformations: Option<&[N]>,
_dir: &Unit<Vector<N>>,
) -> bool;
/// Returns the id of the subshape containing the specified feature.
///
/// If several subshape contains the same feature, any one is returned.
fn subshape_containing_feature(&self, _i: FeatureId) -> usize {
0
}
/// The `RayCast` implementation of `self`.
#[inline]
fn as_ray_cast(&self) -> Option<&dyn RayCast<N>> {
None
}
/// The `PointQuery` implementation of `self`.
#[inline]
fn as_point_query(&self) -> Option<&dyn PointQuery<N>> {
None
}
/// The convex polyhedron representation of `self` if applicable.
#[inline]
fn as_convex_polyhedron(&self) -> Option<&dyn ConvexPolyhedron<N>> {
None
}
/// The support mapping of `self` if applicable.
#[inline]
fn as_support_map(&self) -> Option<&dyn SupportMap<N>> {
None
}
/// The composite shape representation of `self` if applicable.
#[inline]
fn as_composite_shape(&self) -> Option<&dyn CompositeShape<N>> {
None
}
/// The deformable shape representation of `self` if applicable.
#[inline]
fn as_deformable_shape(&self) -> Option<&dyn DeformableShape<N>> {
None
}
/// The mutable deformable shape representation of `self` if applicable.
#[inline]
fn as_deformable_shape_mut(&mut self) -> Option<&mut dyn DeformableShape<N>> {
None
}
/// Whether `self` uses a convex polyhedron representation.
#[inline]
fn is_convex_polyhedron(&self) -> bool {
self.as_convex_polyhedron().is_some()
}
/// Whether `self` uses a support-mapping based representation.
#[inline]
fn is_support_map(&self) -> bool {
self.as_support_map().is_some()
}
/// Whether `self` uses a composite shape-based representation.
#[inline]
fn is_composite_shape(&self) -> bool {
self.as_composite_shape().is_some()
}
/// Whether `self` uses a composite shape-based representation.
#[inline]
fn is_deformable_shape(&self) -> bool {
self.as_deformable_shape().is_some()
}
}
impl_downcast!(Shape<N> where N: RealField);
/// Trait for casting shapes to its exact represetation.
impl<N: RealField> dyn Shape<N> {
/// Tests if this shape has a specific type `T`.
#[inline]
pub fn is_shape<T: Shape<N>>(&self) -> bool {
self.is::<T>()
}
/// Performs the cast.
#[inline]
pub fn as_shape<T: Shape<N>>(&self) -> Option<&T> {
self.downcast_ref()
}
}
/// A shared handle to an abstract shape.
///
/// This can be mutated using COW.
#[derive(Clone)]
pub struct ShapeHandle<N: RealField>(Arc<dyn Shape<N>>);
impl<N: RealField> ShapeHandle<N> {
/// Creates a sharable shape handle from a shape.
#[inline]
pub fn new<S: Shape<N>>(shape: S) -> ShapeHandle<N> {
ShapeHandle(Arc::new(shape))
}
/// Creates a sharable shape handle from a shape trait object.
pub fn from_arc(shape: Arc<dyn Shape<N>>) -> ShapeHandle<N> {
ShapeHandle(shape)
}
/// Gets a reference the `Arc` refcounted shape object.
pub fn as_arc(&self) -> &Arc<dyn Shape<N>> {
&self.0
}
pub(crate) fn make_mut(&mut self) -> &mut dyn Shape<N> {
if Arc::get_mut(&mut self.0).is_none() {
let unique_self = self.0.clone_arc();
self.0 = unique_self;
}
Arc::get_mut(&mut self.0).unwrap()
}
}
impl<N: RealField> AsRef<dyn Shape<N>> for ShapeHandle<N> {
#[inline]
fn as_ref(&self) -> &dyn Shape<N> {
&*self.0
}
}
impl<N: RealField> Deref for ShapeHandle<N> {
type Target = dyn Shape<N>;
#[inline]
fn deref(&self) -> &dyn Shape<N> {
&*self.0
}
}
| bsd-3-clause |
qcscine/utilities | src/Utils/Utils/Scf/ConvergenceAccelerators/FockDiis.cpp | 3870 | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#include "FockDiis.h"
#include <Eigen/QR>
#include <algorithm>
namespace Scine {
namespace Utils {
FockDiis::FockDiis() {
setSubspaceSize(5);
}
void FockDiis::setUnrestricted(bool b) {
unrestricted_ = b;
diisError_.setUnrestricted(b);
}
void FockDiis::setSubspaceSize(int n) {
bool resizeNeeded = n != subspaceSize_;
subspaceSize_ = n;
if (resizeNeeded)
resizeMembers();
}
void FockDiis::setNAOs(int n) {
bool resizeNeeded = n != nAOs_;
nAOs_ = n;
if (resizeNeeded)
resizeMembers();
}
void FockDiis::resizeMembers() {
fockMatrices.resize(subspaceSize_);
diisError_.resize(subspaceSize_);
diisStepErrors_.resize(subspaceSize_);
overlap = Eigen::MatrixXd::Zero(nAOs_, nAOs_);
B = Eigen::MatrixXd::Ones(subspaceSize_ + 1, subspaceSize_ + 1) * (-1);
B(0, 0) = 0;
rhs = Eigen::VectorXd::Zero(subspaceSize_ + 1);
rhs(0) = -1;
restart();
}
void FockDiis::setOverlapMatrix(const Eigen::MatrixXd& S) {
overlap = S.selfadjointView<Eigen::Lower>();
restart();
}
void FockDiis::restart() {
C = Eigen::VectorXd::Zero(subspaceSize_ + 1);
iterationNo_ = 0;
index_ = 0;
}
void FockDiis::addMatrices(const SpinAdaptedMatrix& F, const DensityMatrix& P) {
iterationNo_++;
lastAdded_ = index_;
fockMatrices[index_] = F;
diisError_.setErrorFromMatrices(index_, F, P, overlap);
diisStepErrors_[index_] = std::sqrt(diisError_.getError(index_, index_)) / nAOs_;
updateBMatrix();
index_ = (index_ + 1) % subspaceSize_;
}
void FockDiis::updateBMatrix() {
int activeSize = iterationNo_ > subspaceSize_ ? subspaceSize_ : iterationNo_;
// Bii element
B(lastAdded_ + 1, lastAdded_ + 1) = diisError_.getError(lastAdded_, lastAdded_);
// Bij elements
for (int i = 1; i < activeSize + 1; i++) {
if (i == lastAdded_ + 1)
continue;
B(lastAdded_ + 1, i) = diisError_.getError(lastAdded_, i - 1);
B(i, lastAdded_ + 1) = B(lastAdded_ + 1, i);
}
}
SpinAdaptedMatrix FockDiis::getMixedFockMatrix() {
if (iterationNo_ > subspaceSize_)
iterationNo_ = subspaceSize_;
// If we have only one Fock matrix
if (iterationNo_ < 2) {
return fockMatrices[0];
}
C.head(iterationNo_ + 1) =
B.block(0, 0, iterationNo_ + 1, iterationNo_ + 1).colPivHouseholderQr().solve(rhs.head(iterationNo_ + 1));
return calculateLinearCombination();
}
SpinAdaptedMatrix FockDiis::calculateLinearCombination() {
if (unrestricted_) {
Eigen::MatrixXd FAlpha = Eigen::MatrixXd::Zero(nAOs_, nAOs_);
Eigen::MatrixXd FBeta = Eigen::MatrixXd::Zero(nAOs_, nAOs_);
for (int i = 0; i < iterationNo_; i++) {
FAlpha += C(i + 1) * fockMatrices[i].alphaMatrix();
FBeta += C(i + 1) * fockMatrices[i].betaMatrix();
}
return SpinAdaptedMatrix::createUnrestricted(std::move(FAlpha), std::move(FBeta));
}
else {
Eigen::MatrixXd Fsol = Eigen::MatrixXd::Zero(nAOs_, nAOs_);
for (int i = 0; i < iterationNo_; i++)
Fsol += C(i + 1) * fockMatrices[i].restrictedMatrix();
return SpinAdaptedMatrix::createRestricted(std::move(Fsol));
}
}
double FockDiis::getMaxError() const {
int activeSize = iterationNo_ > subspaceSize_ ? subspaceSize_ : iterationNo_;
auto maxIter = std::max_element(diisStepErrors_.begin(), diisStepErrors_.begin() + activeSize);
return *maxIter;
}
double FockDiis::getMinError() const {
int activeSize = iterationNo_ > subspaceSize_ ? subspaceSize_ : iterationNo_;
auto minIter = std::min_element(diisStepErrors_.begin(), diisStepErrors_.begin() + activeSize);
return *minIter;
}
double FockDiis::getLastError() const {
return diisStepErrors_[lastAdded_];
}
} // namespace Utils
} // namespace Scine
| bsd-3-clause |
mateka/dmexl | dmexlib/src/main/java/pl/edu/mimuw/dmexlib/utils/TreeFuture.java | 1401 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pl.edu.mimuw.dmexlib.utils;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
*
* @author matek
*/
public class TreeFuture<T> implements Future<T> {
public TreeFuture(Future<T> task, Future<T> left, Future<T> right) {
this.node = task;
this.left = left;
this.right = right;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
left.cancel(mayInterruptIfRunning);
right.cancel(mayInterruptIfRunning);
return node.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return left.isCancelled() && right.isCancelled() && node.isCancelled();
}
@Override
public boolean isDone() {
return left.isDone() && right.isDone() && node.isDone();
}
@Override
public T get() throws ExecutionException, InterruptedException {
return node.get();
}
@Override
public T get(long timeout, TimeUnit unit) throws ExecutionException, TimeoutException, InterruptedException {
return node.get(timeout, unit);
}
private Future<T> node;
private Future<T> left;
private Future<T> right;
}
| bsd-3-clause |
iphoting/healthchecks | hc/api/tests/test_create_check.py | 9867 | from datetime import timedelta as td
import json
from hc.api.models import Channel, Check
from hc.test import BaseTestCase
class CreateCheckTestCase(BaseTestCase):
URL = "/api/v1/checks/"
def post(self, data, expect_fragment=None):
if "api_key" not in data:
data["api_key"] = "X" * 32
r = self.client.post(self.URL, data, content_type="application/json")
if expect_fragment:
self.assertEqual(r.status_code, 400)
self.assertIn(expect_fragment, r.json()["error"])
return r
def test_it_works(self):
r = self.post({"name": "Foo", "tags": "bar,baz", "timeout": 3600, "grace": 60})
self.assertEqual(r.status_code, 201)
self.assertEqual(r["Access-Control-Allow-Origin"], "*")
doc = r.json()
assert "ping_url" in doc
self.assertEqual(doc["name"], "Foo")
self.assertEqual(doc["tags"], "bar,baz")
self.assertEqual(doc["last_ping"], None)
self.assertEqual(doc["n_pings"], 0)
self.assertEqual(doc["methods"], "")
self.assertTrue("schedule" not in doc)
self.assertTrue("tz" not in doc)
check = Check.objects.get()
self.assertEqual(check.name, "Foo")
self.assertEqual(check.tags, "bar,baz")
self.assertEqual(check.methods, "")
self.assertEqual(check.timeout.total_seconds(), 3600)
self.assertEqual(check.grace.total_seconds(), 60)
self.assertEqual(check.project, self.project)
def test_it_handles_options(self):
r = self.client.options(self.URL)
self.assertEqual(r.status_code, 204)
self.assertIn("POST", r["Access-Control-Allow-Methods"])
def test_30_days_works(self):
r = self.post({"name": "Foo", "timeout": 2592000, "grace": 2592000})
self.assertEqual(r.status_code, 201)
check = Check.objects.get()
self.assertEqual(check.timeout.total_seconds(), 2592000)
self.assertEqual(check.grace.total_seconds(), 2592000)
def test_it_accepts_api_key_in_header(self):
payload = json.dumps({"name": "Foo"})
r = self.client.post(
self.URL, payload, content_type="application/json", HTTP_X_API_KEY="X" * 32
)
self.assertEqual(r.status_code, 201)
def test_it_assigns_channels(self):
channel = Channel.objects.create(project=self.project)
r = self.post({"channels": "*"})
self.assertEqual(r.status_code, 201)
check = Check.objects.get()
self.assertEqual(check.channel_set.get(), channel)
def test_it_sets_channel_by_name(self):
channel = Channel.objects.create(project=self.project, name="alerts")
r = self.post({"channels": "alerts"})
self.assertEqual(r.status_code, 201)
check = Check.objects.get()
assigned_channel = check.channel_set.get()
self.assertEqual(assigned_channel, channel)
def test_it_sets_channel_by_name_formatted_as_uuid(self):
name = "102eaa82-a274-4b15-a499-c1bb6bbcd7b6"
channel = Channel.objects.create(project=self.project, name=name)
r = self.post({"channels": name})
self.assertEqual(r.status_code, 201)
check = Check.objects.get()
assigned_channel = check.channel_set.get()
self.assertEqual(assigned_channel, channel)
def test_it_handles_channel_lookup_by_name_with_no_results(self):
r = self.post({"channels": "abc"})
self.assertEqual(r.status_code, 400)
self.assertEqual(r.json()["error"], "invalid channel identifier: abc")
# The check should not have been saved
self.assertFalse(Check.objects.exists())
def test_it_handles_channel_lookup_by_name_with_multiple_results(self):
Channel.objects.create(project=self.project, name="foo")
Channel.objects.create(project=self.project, name="foo")
r = self.post({"channels": "foo"})
self.assertEqual(r.status_code, 400)
self.assertEqual(r.json()["error"], "non-unique channel identifier: foo")
# The check should not have been saved
self.assertFalse(Check.objects.exists())
def test_it_rejects_multiple_empty_channel_names(self):
Channel.objects.create(project=self.project, name="")
r = self.post({"channels": ","})
self.assertEqual(r.status_code, 400)
self.assertEqual(r.json()["error"], "empty channel identifier")
# The check should not have been saved
self.assertFalse(Check.objects.exists())
def test_it_supports_unique_name(self):
check = Check.objects.create(project=self.project, name="Foo")
r = self.post({"name": "Foo", "tags": "bar", "unique": ["name"]})
# Expect 200 instead of 201
self.assertEqual(r.status_code, 200)
# And there should be only one check in the database:
self.assertEqual(Check.objects.count(), 1)
# The tags field should have a value now:
check.refresh_from_db()
self.assertEqual(check.tags, "bar")
def test_it_supports_unique_tags(self):
Check.objects.create(project=self.project, tags="foo")
r = self.post({"tags": "foo", "unique": ["tags"]})
# Expect 200 instead of 201
self.assertEqual(r.status_code, 200)
# And there should be only one check in the database:
self.assertEqual(Check.objects.count(), 1)
def test_it_supports_unique_timeout(self):
Check.objects.create(project=self.project, timeout=td(seconds=123))
r = self.post({"timeout": 123, "unique": ["timeout"]})
# Expect 200 instead of 201
self.assertEqual(r.status_code, 200)
# And there should be only one check in the database:
self.assertEqual(Check.objects.count(), 1)
def test_it_supports_unique_grace(self):
Check.objects.create(project=self.project, grace=td(seconds=123))
r = self.post({"grace": 123, "unique": ["grace"]})
# Expect 200 instead of 201
self.assertEqual(r.status_code, 200)
# And there should be only one check in the database:
self.assertEqual(Check.objects.count(), 1)
def test_it_handles_missing_request_body(self):
r = self.client.post(self.URL, content_type="application/json")
self.assertEqual(r.status_code, 401)
self.assertEqual(r.json()["error"], "missing api key")
def test_it_handles_invalid_json(self):
r = self.client.post(
self.URL, "this is not json", content_type="application/json"
)
self.assertEqual(r.status_code, 400)
self.assertEqual(r.json()["error"], "could not parse request body")
def test_it_rejects_wrong_api_key(self):
r = self.post({"api_key": "Y" * 32})
self.assertEqual(r.status_code, 401)
def test_it_rejects_small_timeout(self):
self.post({"timeout": 0}, expect_fragment="timeout is too small")
def test_it_rejects_large_timeout(self):
self.post({"timeout": 2592001}, expect_fragment="timeout is too large")
def test_it_rejects_non_number_timeout(self):
self.post({"timeout": "oops"}, expect_fragment="timeout is not a number")
def test_it_rejects_non_string_name(self):
self.post({"name": False}, expect_fragment="name is not a string")
def test_it_rejects_long_name(self):
self.post({"name": "01234567890" * 20}, expect_fragment="name is too long")
def test_unique_accepts_only_specific_values(self):
self.post(
{"name": "Foo", "unique": ["status"]}, expect_fragment="unexpected value",
)
def test_it_rejects_bad_unique_values(self):
self.post(
{"name": "Foo", "unique": "not a list"}, expect_fragment="not an array",
)
def test_it_supports_cron_syntax(self):
r = self.post({"schedule": "5 * * * *", "tz": "Europe/Riga", "grace": 60})
self.assertEqual(r.status_code, 201)
doc = r.json()
self.assertEqual(doc["schedule"], "5 * * * *")
self.assertEqual(doc["tz"], "Europe/Riga")
self.assertEqual(doc["grace"], 60)
self.assertTrue("timeout" not in doc)
def test_it_validates_cron_expression(self):
r = self.post({"schedule": "bad-expression", "tz": "Europe/Riga", "grace": 60})
self.assertEqual(r.status_code, 400)
def test_it_validates_timezone(self):
r = self.post({"schedule": "* * * * *", "tz": "not-a-timezone", "grace": 60})
self.assertEqual(r.status_code, 400)
def test_it_sets_default_timeout(self):
r = self.post({})
self.assertEqual(r.status_code, 201)
doc = r.json()
self.assertEqual(doc["timeout"], 86400)
def test_it_obeys_check_limit(self):
self.profile.check_limit = 0
self.profile.save()
r = self.post({})
self.assertEqual(r.status_code, 403)
def test_it_rejects_readonly_key(self):
self.project.api_key_readonly = "R" * 32
self.project.save()
r = self.post({"api_key": "R" * 32, "name": "Foo"})
self.assertEqual(r.status_code, 401)
def test_it_sets_manual_resume(self):
r = self.post({"manual_resume": True})
self.assertEqual(r.status_code, 201)
check = Check.objects.get()
self.assertTrue(check.manual_resume)
def test_it_rejects_non_boolean_manual_resume(self):
r = self.post({"manual_resume": "surprise"})
self.assertEqual(r.status_code, 400)
def test_it_sets_methods(self):
r = self.post({"methods": "POST"})
self.assertEqual(r.status_code, 201)
check = Check.objects.get()
self.assertEqual(check.methods, "POST")
def test_it_rejects_bad_methods_value(self):
r = self.post({"methods": "bad-value"})
self.assertEqual(r.status_code, 400)
| bsd-3-clause |
BSVino/Digitanks | digitanks/src/dtintro/main.cpp | 493 | #include "intro_window.h"
extern tvector<Color> FullScreenShot(int& iWidth, int& iHeight);
void CreateApplication(int argc, char** argv)
{
int iWidth, iHeight;
tvector<Color> aclrScreenshot = FullScreenShot(iWidth, iHeight);
CIntroWindow oWindow(argc, argv);
oWindow.SetScreenshot(aclrScreenshot, iWidth, iHeight);
oWindow.OpenWindow();
oWindow.SetupEngine();
oWindow.Run();
}
int main(int argc, char** argv)
{
CreateApplicationWithErrorHandling(CreateApplication, argc, argv);
}
| bsd-3-clause |
seanlong/crosswalk | app/android/app_template/src/org/xwalk/app/template/AppTemplateActivity.java | 1403 | // Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.xwalk.app.template;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import org.xwalk.app.XWalkRuntimeActivityBase;
public class AppTemplateActivity extends XWalkRuntimeActivityBase {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// Passdown the key-up event to runtime view.
if (getRuntimeView() != null &&
getRuntimeView().onKeyUp(keyCode, event)) {
return true;
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void didTryLoadRuntimeView(View runtimeView) {
if (runtimeView != null) {
setContentView(runtimeView);
getRuntimeView().loadAppFromUrl("file:///android_asset/www/index.html");
} else {
TextView msgText = new TextView(this);
msgText.setText("Crosswalk failed to initialize.");
msgText.setTextSize(36);
msgText.setTextColor(Color.BLACK);
setContentView(msgText);
}
}
}
| bsd-3-clause |
fromkeith/awsgo | swf/respondActivityTaskCanceled.go | 3218 | /*
* Copyright (c) 2014, fromkeith
* 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 fromkeith nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package swf
import (
"github.com/fromkeith/awsgo"
"log"
"errors"
)
type RespondActivityTaskCanceledRequest struct {
awsgo.RequestBuilder
Details string `json:"details"`
TaskToken string `json:"taskToken"`
}
type RespondActivityTaskCanceledResponse struct {
}
func NewRespondActivityTaskCanceledRequest() *RespondActivityTaskCanceledRequest {
req := new(RespondActivityTaskCanceledRequest)
req.Host.Service = "swf"
req.Host.Region = ""
req.Host.Domain = "amazonaws.com"
req.Key.AccessKeyId = ""
req.Key.SecretAccessKey = ""
req.Headers = make(map[string]string)
req.Headers["X-Amz-Target"] = "SimpleWorkflowService.RespondActivityTaskCanceled"
req.RequestMethod = "POST"
req.CanonicalUri = "/"
return req
}
func (req *RespondActivityTaskCanceledRequest) VerifyInput() error {
return nil
}
func (req RespondActivityTaskCanceledRequest) DeMarshalResponse(response []byte, headers map[string]string, statusCode int) interface{} {
log.Println("response: ", string(response))
if statusCode != 200 {
return errors.New("Bad response code!")
}
return new(RespondActivityTaskCanceledResponse)
}
func (req RespondActivityTaskCanceledRequest) Request() (*RespondActivityTaskCanceledResponse, error) {
request, err := awsgo.NewAwsRequest(&req, req)
if err != nil {
return nil, err
}
request.RequestSigningType = awsgo.RequestSigningType_AWS3
resp, err := request.DoAndDemarshall(&req)
if resp == nil {
return nil, err
}
return resp.(*RespondActivityTaskCanceledResponse), err
} | bsd-3-clause |
kponda/SaikoroOmikuji | RankingEngine/app.js | 2326 | var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var path = require('path');
var routes = require('./routes/index');
var system_config_path = path.join(__dirname, './config/system-config');
var system_config = require(system_config_path);
var dynamodb = require('./common/dynamodb_util');
var AWS = require('aws-sdk');
var db = new AWS.DynamoDB({region:system_config.dynamodb.region,
apiVersion:system_config.dynamodb.apiVersion});
if (system_config.dynamodb.endpoint!=null) {
db.setEndpoint(system_config.dynamodb.endpoint);
}
var Ranking = dynamodb(db,system_config.schema);
Ranking.delete(function(err,result) {
// if (err) throw err;
setTimeout(function() {
Ranking.describe(function(err,result) {
if (err) {
if (err.code == 'ResourceNotFoundException') {
setTimeout(function() {
Ranking.create(function(err,result) {
// if (err) throw err;
});
},1000);
} else {
throw err;
}
}
});
},1000);
});
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
| bsd-3-clause |
iainbeeston/shipment_tracker | config/application.rb | 1589 | require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require 'active_model/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require 'sprockets/railtie'
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
Dotenv.load
module ShipmentTracker
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
config.action_dispatch.perform_deep_munge = false
config.ssh_private_key = ENV['SSH_PRIVATE_KEY']
config.ssh_public_key = ENV['SSH_PUBLIC_KEY']
config.ssh_user = ENV['SSH_USER']
config.approved_statuses = ENV.fetch('APPROVED_STATUSES', 'Done,Ready for Deployment').split(/\s*,\s*/)
config.git_repository_cache_dir = Dir.tmpdir
end
end
| bsd-3-clause |
hogin/panliu | frontend/controllers/NewsController.php | 2633 | <?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use yii\data\ActiveDataProvider;
use frontend\models\NewForm;
use frontend\models\UserForm;
use frontend\models\CategoryForm;
use yii\web\NotFoundHttpException;
class NewsController extends Controller
{
public function actionIndex()
{
$searchModel = new NewForm();
$dataProvider = $searchModel->search(Yii::$app->request->get());
return $this->render('index', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
}
public function actionDelete($id)
{
$model = $this->findModel($id);
if($model->delete()) {
return $this->redirect(['index']);
}
return $this->redirect(['index']);
}
public function actionView($id)
{
// todo;
/*$test = new CategoryForm();
$test->test();die;*/
$model = $this->findModel($id);
if($model === null) {
throw new NotFoundHttpException;
}
return $this->render('view', [
'model' => $model,
]);
}
public function actionCreate()
{
$model = new NewForm();
$model->created_at = time();
$model->updated_at = time();
if($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
}else{
$categoryInfo = $model->categories;
$userInfo = $model->users;
return $this->render('create',[
'model' => $model,
'categoryInfo' => $categoryInfo,
'userInfo' => $userInfo,
]);
}
}
public function actionUpdate($id)
{
// todo;
$model = $this->findModel($id);
if($model === null) {
throw new NotFoundHttpException;
}
$model->updated_at = time();
if($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index','id' =>$model->id]);
}
$models = new NewForm();
$categoryInfo = $models->categories;
$userInfo = $models->users;
return $this->render('update',[
'model' => $model,
'categoryInfo' => $categoryInfo,
'userInfo' => $userInfo,
]);
}
protected function findModel($id)
{
return $models=NewForm::findOne($id);
// todo;
}
public function actionTest()
{
$model = NewForm::findOne(2);
return $this->render('view', [
'model' => $model,
]);
}
} | bsd-3-clause |
junstyle/php.tools | src/Additionals/PSR2MultilineFunctionParams.php | 1976 | <?php
final class PSR2MultilineFunctionParams extends AdditionalPass {
const LINE_BREAK = "\x2 LN \x3";
public function candidate($source, $foundTokens) {
if (isset($foundTokens[T_FUNCTION])) {
return true;
}
return false;
}
public function format($source) {
$this->tkns = token_get_all($source);
$this->code = '';
while (list($index, $token) = each($this->tkns)) {
list($id, $text) = $this->getToken($token);
$this->ptr = $index;
switch ($id) {
case T_FUNCTION:
$this->appendCode($text);
$this->printUntil(ST_PARENTHESES_OPEN);
$this->appendCode(self::LINE_BREAK);
$touchedComma = false;
while (list($index, $token) = each($this->tkns)) {
list($id, $text) = $this->getToken($token);
$this->ptr = $index;
if (ST_PARENTHESES_OPEN === $id) {
$this->appendCode($text);
$this->printUntil(ST_PARENTHESES_CLOSE);
continue;
} elseif (ST_BRACKET_OPEN === $id) {
$this->appendCode($text);
$this->printUntil(ST_BRACKET_CLOSE);
continue;
} elseif (ST_PARENTHESES_CLOSE === $id) {
$this->appendCode(self::LINE_BREAK);
$this->appendCode($text);
break;
}
$this->appendCode($text);
if (ST_COMMA === $id && !$this->hasLnAfter()) {
$touchedComma = true;
$this->appendCode(self::LINE_BREAK);
}
}
$placeholderReplace = PHP_EOL;
if (!$touchedComma) {
$placeholderReplace = '';
}
$this->code = str_replace(self::LINE_BREAK, $placeholderReplace, $this->code);
break;
default:
$this->appendCode($text);
}
}
return $this->code;
}
/**
* @codeCoverageIgnore
*/
public function getDescription() {
return 'Break function parameters into multiple lines.';
}
/**
* @codeCoverageIgnore
*/
public function getExample() {
return <<<'EOT'
<?php
// PSR2 Mode - From
function a($a, $b, $c)
{}
// To
function a(
$a,
$b,
$c
) {}
?>
EOT;
}
}
| bsd-3-clause |
bigjun/mrpt | apps/simul-landmarks/simul-landmarks-main.cpp | 16482 | /* +---------------------------------------------------------------------------+
| The Mobile Robot Programming Toolkit (MRPT) |
| |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2013, Individual contributors, see AUTHORS file |
| Copyright (c) 2005-2013, MAPIR group, University of Malaga |
| Copyright (c) 2012-2013, University of Almeria |
| 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 copyright holders 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 HOLDERS 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 <mrpt/base.h>
#include <mrpt/slam.h>
#include <mrpt/gui.h>
using namespace mrpt;
using namespace mrpt::math;
using namespace mrpt::utils;
using namespace mrpt::slam;
using namespace mrpt::random;
using namespace std;
int main(int argc, char ** argv)
{
try
{
bool showHelp = argc>1 && !os::_strcmp(argv[1],"--help");
bool showVersion = argc>1 && !os::_strcmp(argv[1],"--version");
printf(" simul-landmarks - Part of the MRPT\n");
printf(" MRPT C++ Library: %s - BUILD DATE %s\n", MRPT_getVersion().c_str(), MRPT_getCompilationDate().c_str());
if (showVersion)
return 0; // Program end
// Process arguments:
if (argc<2 || showHelp )
{
printf("Usage: %s <config_file.ini>\n\n",argv[0]);
if (!showHelp)
{
mrpt::system::pause();
return -1;
}
else return 0;
}
string INI_FILENAME = std::string( argv[1] );
ASSERT_FILE_EXISTS_(INI_FILENAME)
CConfigFile ini( INI_FILENAME );
const int random_seed = ini.read_int("Params","random_seed",0);
if (random_seed!=0)
randomGenerator.randomize(random_seed);
else randomGenerator.randomize();
// Set default values:
unsigned int nLandmarks = 3;
unsigned int nSteps = 100;
std::string outFile("out.rawlog");
std::string outDir("OUT");
float min_x =-5;
float max_x =5;
float min_y =-5;
float max_y =5;
float min_z =0;
float max_z =0;
float odometryNoiseXY_std = 0.001f;
float odometryNoisePhi_std_deg = 0.01f;
float odometryNoisePitch_std_deg = 0.01f;
float odometryNoiseRoll_std_deg = 0.01f;
float minSensorDistance = 0;
float maxSensorDistance = 10;
float fieldOfView_deg= 180.0f;
float sensorPose_x = 0;
float sensorPose_y = 0;
float sensorPose_z = 0;
float sensorPose_yaw_deg = 0;
float sensorPose_pitch_deg = 0;
float sensorPose_roll_deg = 0;
float stdRange = 0.01f;
float stdYaw_deg = 0.1f;
float stdPitch_deg = 0.1f;
bool sensorDetectsIDs=true;
bool circularPath = true;
bool random6DPath = false;
size_t squarePathLength=40;
// Load params from INI:
MRPT_LOAD_CONFIG_VAR(outFile,string, ini,"Params");
MRPT_LOAD_CONFIG_VAR(outDir,string, ini,"Params");
MRPT_LOAD_CONFIG_VAR(nSteps,int, ini,"Params");
MRPT_LOAD_CONFIG_VAR(circularPath,bool, ini,"Params");
MRPT_LOAD_CONFIG_VAR(random6DPath,bool, ini,"Params");
MRPT_LOAD_CONFIG_VAR(squarePathLength,int,ini,"Params");
MRPT_LOAD_CONFIG_VAR(sensorDetectsIDs,bool, ini,"Params");
MRPT_LOAD_CONFIG_VAR(odometryNoiseXY_std,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(odometryNoisePhi_std_deg,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(odometryNoisePitch_std_deg,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(odometryNoiseRoll_std_deg,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(sensorPose_x,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(sensorPose_y,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(sensorPose_z,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(sensorPose_yaw_deg,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(sensorPose_pitch_deg,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(sensorPose_roll_deg,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(minSensorDistance,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(maxSensorDistance,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(fieldOfView_deg,float, ini,"Params");
bool show_in_3d = false;
MRPT_LOAD_CONFIG_VAR(show_in_3d,bool, ini,"Params");
MRPT_LOAD_CONFIG_VAR(stdRange,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(stdYaw_deg,float, ini,"Params");
MRPT_LOAD_CONFIG_VAR(stdPitch_deg,float, ini,"Params");
float stdYaw = DEG2RAD(stdYaw_deg);
float stdPitch = DEG2RAD(stdPitch_deg);
float odometryNoisePhi_std = DEG2RAD(odometryNoisePhi_std_deg);
float odometryNoisePitch_std = DEG2RAD(odometryNoisePitch_std_deg);
float odometryNoiseRoll_std = DEG2RAD(odometryNoiseRoll_std_deg);
float fieldOfView = DEG2RAD(fieldOfView_deg);
CPose3D sensorPoseOnRobot(
sensorPose_x,
sensorPose_y,
sensorPose_z,
DEG2RAD( sensorPose_yaw_deg ),
DEG2RAD( sensorPose_pitch_deg ),
DEG2RAD( sensorPose_roll_deg ) );
// Create out dir:
mrpt::system::createDirectory(outDir);
// ---------------------------------------------
// Create the point-beacons:
// ---------------------------------------------
printf("Creating landmark map...");
mrpt::slam::CLandmarksMap landmarkMap;
int randomSetCount = 0;
int uniqueIds = 1;
// Process each of the "RANDOMSET_%i" found:
do
{
string sectName = format("RANDOMSET_%i",++randomSetCount);
nLandmarks = 0;
MRPT_LOAD_CONFIG_VAR(nLandmarks,uint64_t, ini,sectName);
MRPT_LOAD_CONFIG_VAR(min_x,float, ini,sectName);
MRPT_LOAD_CONFIG_VAR(max_x,float, ini,sectName);
MRPT_LOAD_CONFIG_VAR(min_y,float, ini,sectName);
MRPT_LOAD_CONFIG_VAR(max_y,float, ini,sectName);
MRPT_LOAD_CONFIG_VAR(min_z,float, ini,sectName);
MRPT_LOAD_CONFIG_VAR(max_z,float, ini,sectName);
for (size_t i=0;i<nLandmarks;i++)
{
CLandmark LM;
CPointPDFGaussian pt3D;
// Random coordinates:
pt3D.mean = CPoint3D(
randomGenerator.drawUniform(min_x,max_x),
randomGenerator.drawUniform(min_y,max_y),
randomGenerator.drawUniform(min_z,max_z) );
// Add:
LM.createOneFeature();
LM.features[0]->type = featBeacon;
LM.ID = uniqueIds++;
LM.setPose( pt3D );
landmarkMap.landmarks.push_back(LM);
}
if (nLandmarks) cout << nLandmarks << " generated for the 'randomset' " << randomSetCount << endl;
}
while (nLandmarks);
landmarkMap.saveToTextFile( format("%s/%s_ground_truth.txt",outDir.c_str(),outFile.c_str()) );
printf("Done!\n");
// ---------------------------------------------
// Simulate:
// ---------------------------------------------
size_t nWarningsNoSight=0;
CActionRobotMovement2D::TMotionModelOptions opts;
opts.modelSelection = CActionRobotMovement2D::mmGaussian;
opts.gausianModel.a1=0;
opts.gausianModel.a2=0;
opts.gausianModel.a3=0;
opts.gausianModel.a4=0;
opts.gausianModel.minStdXY = odometryNoiseXY_std;
opts.gausianModel.minStdPHI = odometryNoisePhi_std;
// Output rawlog, gz-compressed.
CFileGZOutputStream fil( format("%s/%s",outDir.c_str(),outFile.c_str()));
CPose3D realPose;
const size_t N_STEPS_STOP_AT_THE_BEGINNING = 4;
CMatrixDouble GT_path;
for (size_t i=0;i<nSteps;i++)
{
cout << "Generating step " << i << "...\n";
CSensoryFrame SF;
CActionCollection acts;
CPose3D incPose3D;
bool incPose_is_3D = random6DPath;
if (i>=N_STEPS_STOP_AT_THE_BEGINNING)
{
if (random6DPath)
{ // 3D path
const double Ar = DEG2RAD(3);
TPose3D Ap = TPose3D(0.20*cos(Ar),0.20*sin(Ar),0,Ar,0,0);
//Ap.z += randomGenerator.drawGaussian1D(0,0.05);
Ap.yaw += randomGenerator.drawGaussian1D(0,DEG2RAD(0.2));
Ap.pitch += randomGenerator.drawGaussian1D(0,DEG2RAD(2));
Ap.roll += randomGenerator.drawGaussian1D(0,DEG2RAD(4));
incPose3D = CPose3D(Ap);
}
else
{ // 2D path:
if (circularPath)
{
// Circular path:
float Ar = DEG2RAD(5);
incPose3D = CPose3D(CPose2D(0.20f*cos(Ar),0.20f*sin(Ar),Ar));
}
else
{
// Square path:
if ( (i % squarePathLength) > (squarePathLength-5) )
incPose3D = CPose3D(CPose2D(0,0,DEG2RAD(90.0f/4)));
else incPose3D = CPose3D(CPose2D(0.20f,0,0));
}
}
}
else
{
// Robot is still at the beginning:
incPose3D = CPose3D(0,0,0,0,0,0);
}
// Simulate observations:
CObservationBearingRangePtr obs=CObservationBearingRange::Create();
obs->minSensorDistance=minSensorDistance;
obs->maxSensorDistance=maxSensorDistance;
obs->fieldOfView_yaw = fieldOfView;
obs->fieldOfView_pitch = fieldOfView;
obs->sensorLocationOnRobot = sensorPoseOnRobot;
landmarkMap.simulateRangeBearingReadings(
realPose,
sensorPoseOnRobot,
*obs,
sensorDetectsIDs, // wheter to identy landmarks
stdRange,
stdYaw,
stdPitch );
// Keep the GT of the robot pose:
GT_path.setSize(i+1,6);
for (size_t k=0;k<6;k++)
GT_path(i,k)=realPose[k];
cout << obs->sensedData.size() << " landmarks in sight";
if (!obs->sensedData.size()) nWarningsNoSight++;
SF.push_back( obs );
// Simulate odometry, from "incPose3D" with noise:
if (!incPose_is_3D)
{ // 2D odometry:
CActionRobotMovement2D act;
CPose2D incOdo( incPose3D );
if (incPose3D.x()!=0 || incPose3D.y()!=0 || incPose3D.yaw()!=0)
{
incOdo.x_incr( randomGenerator.drawGaussian1D_normalized() * odometryNoiseXY_std );
incOdo.y_incr( randomGenerator.drawGaussian1D_normalized() * odometryNoiseXY_std );
incOdo.phi_incr( randomGenerator.drawGaussian1D_normalized() * odometryNoisePhi_std );
}
act.computeFromOdometry(incOdo, opts);
acts.insert( act );
}
else
{ // 3D odometry:
CActionRobotMovement3D act;
act.estimationMethod = CActionRobotMovement3D::emOdometry;
CPose3D noisyIncPose = incPose3D;
if (incPose3D.x()!=0 || incPose3D.y()!=0 || incPose3D.yaw()!=0)
{
noisyIncPose.x_incr( randomGenerator.drawGaussian1D_normalized() * odometryNoiseXY_std );
noisyIncPose.y_incr( randomGenerator.drawGaussian1D_normalized() * odometryNoiseXY_std );
noisyIncPose.z_incr( randomGenerator.drawGaussian1D_normalized() * odometryNoiseXY_std );
noisyIncPose.setYawPitchRoll(
noisyIncPose.yaw()+ randomGenerator.drawGaussian1D_normalized() * odometryNoisePhi_std,
noisyIncPose.pitch()+ randomGenerator.drawGaussian1D_normalized() * odometryNoisePitch_std,
noisyIncPose.roll()+ randomGenerator.drawGaussian1D_normalized() * odometryNoiseRoll_std );
}
act.poseChange.mean = noisyIncPose;
act.poseChange.cov.eye();
act.poseChange.cov(0,0) =
act.poseChange.cov(1,1) =
act.poseChange.cov(2,2) = square(odometryNoiseXY_std);
act.poseChange.cov(3,3) = square(odometryNoisePhi_std);
act.poseChange.cov(4,4) = square(odometryNoisePitch_std);
act.poseChange.cov(5,5) = square(odometryNoiseRoll_std);
acts.insert( act );
}
// Save:
fil << SF << acts;
// Next pose:
realPose = realPose + incPose3D;
cout << endl;
}
// Save the ground truth for the robot poses as well:
GT_path.saveToTextFile(
format("%s/%s_ground_truth_robot_path.txt",outDir.c_str(),outFile.c_str()),
MATRIX_FORMAT_FIXED,
true,
"% Columns are: x(m) y(m) z(m) yaw(rad) pitch(rad) roll(rad)\n");
cout << "Data saved to directory: " << outDir << endl;
if (nWarningsNoSight)
cout << "WARNING: " << nWarningsNoSight << " observations contained zero landmarks in the sensor range." << endl;
// Optionally, display in 3D:
if (show_in_3d && size(GT_path,1)>1)
{
#if MRPT_HAS_OPENGL_GLUT && MRPT_HAS_WXWIDGETS
mrpt::gui::CDisplayWindow3D win("Final simulation",400,300);
mrpt::opengl::COpenGLScenePtr &scene = win.get3DSceneAndLock();
scene->insert( mrpt::opengl::CGridPlaneXY::Create( min_x-10,max_x+10,min_y-10,max_y+10,0 ));
scene->insert( mrpt::opengl::stock_objects::CornerXYZ() );
// Insert all landmarks:
for (CLandmarksMap::TCustomSequenceLandmarks::const_iterator it=landmarkMap.landmarks.begin();it!=landmarkMap.landmarks.end();++it)
{
mrpt::opengl::CSpherePtr lm = mrpt::opengl::CSphere::Create();
lm->setColor(1,0,0);
lm->setRadius(0.1);
lm->setLocation( it->pose_mean );
lm->setName( format("LM#%u",(unsigned) it->ID ) );
//lm->enableShowName(true);
scene->insert(lm);
}
// Insert all robot poses:
const size_t N = size(GT_path,1);
mrpt::opengl::CSetOfLinesPtr pathLines = mrpt::opengl::CSetOfLines::Create();
pathLines->setColor(0,0,1,0.5);
pathLines->setLineWidth(3.0);
pathLines->resize(N-1);
for (size_t i=0;i<N-1;i++)
pathLines->setLineByIndex(i, GT_path(i,0),GT_path(i,1),GT_path(i,2), GT_path(i+1,0),GT_path(i+1,1),GT_path(i+1,2) );
scene->insert(pathLines);
for (size_t i=0;i<N;i++)
{
mrpt::opengl::CSetOfObjectsPtr corner = mrpt::opengl::stock_objects::CornerXYZ();
corner->setScale(0.2);
corner->setPose(TPose3D(GT_path(i,0),GT_path(i,1),GT_path(i,2),GT_path(i,3),GT_path(i,4),GT_path(i,5)));
scene->insert(corner);
}
win.unlockAccess3DScene();
win.forceRepaint();
cout << "Press any key or close the 3D window to exit." << endl;
win.waitForKey();
#endif // MRPT_HAS_OPENGL_GLUT && MRPT_HAS_WXWIDGETS
}
}
catch (std::exception &e)
{
std::cout << e.what();
}
catch (...)
{
std::cout << "Untyped exception!";
}
}
| bsd-3-clause |
zenus/thinkphpLint | test/stdlib/it/icosaedro/lint/data/5-general.php | 11990 | <?php
/**
* PHPLint Test Program
* @package PHPLintTest
* @author Umberto Salsi
* @copyright 2005 Umberto Salsi
* @license http://www.icosaedro.it/phplint/manual.html?p=license BSD-style
*/
/*.
require_module 'standard';
.*/
/* literals: */
define("BOOL1", false || true && (1&2^3|4) == 0);
define("INT1", 123*4.3);
define("INT2", +123);
define("INT3", -123);
define("INT4", 012);
define("INT5", 0x1Ff120);
define("FLOAT1", 1.234 + 12.34 * (-6e9) / (0.5e-34));
define("STRING1", "abc" . 'abc' . "a\000b\0x85");
define("STRING2", <<< EOT
EOT
. <<<EOT
Just a line.
EOT
. <<< EOT
Just two
lines.
EOT
);
define("STRING3", /*.(string).*/ NULL);
/* arrays: */
$arr0 = array();
$arr1 = array(1, 2, 3);
$arr2 = array("a", "b");
$arr3 = array(1=>111, 222, 3=>333);
$arr4 = array("a"=>"x", "b"=>"x"); # warn
$arr1[] = 4;
$arr1[4] = 4;
$arr2[4] = "d";
$arr3[4] = 4;
$arr4["4"] = "z";
$undef_arr1[1]["sss"] = 111;
$undef_arr2[1][123] = "aaa";
$i = $arr1[1]++ + ++$arr1[1];
/* operators: */
$i = 0;
$i++;
++$i;
$arr1[0]++;
++$arr1[0];
/* control structures: */
if( true );
if( true ) ; else ;
if( true ) ; elseif( false ) ;
if( true ) ; elseif( false ) ; else ;
while( false ) ;
do break; while( false ) ;
for(;;) break;
for($i = 0; $i < 10; $i++) {break;}
for($i = 0, $j = 1; $k = 2, $i < 10; $i++) ;
foreach($arr2 as $v) continue;
foreach($arr2 as $k => $v) continue;
switch(1){
case 1: break;
case 2:
case 3: echo "hello"; break;
default:
}
switch(1){
case 1:
case 2:
case 1:
echo 1;
break;
case "1":
echo 1;
}
# Test double quoted strings with embedded variables:
$s = "" . "$i" . "@$i" . "$i@" . "$i$i$i" . "$i@$i@$i";
# Test here-doc with embedded vars:
$s = <<< XXX
$i
XXX
. <<< XXX
$i
XXX
. <<< ZZZ
$i $i
text
ZZZ;
# Test here-doc with double-quoted label:
$s = <<< "XXX"
$i
XXX;
# Test now-doc:
$s = <<< 'XXX'
?> ?> <? <?
XXX;
$s = <<< 'XXX'
XXX;
$s = <<< 'XXX'
XXX
;
/*. int .*/ function size_of_int()
{
$n = 1;
$x = 1;
while( is_int($x) ){ $n++; $x*=2; }
return $n;
}
echo "size of int = ", size_of_int(), " bits\n";
if(true){
exit;
exit();
exit(0);
exit("xyz");
die;
die();
die(0);
die("xyz");
}
/* Passing arguments by ref.: */
/*. void .*/ function set_string(/*. string .*/ &$s)
{
$s = "hello";
?>hello, world, today is <?= date("c") ?>
<?
}
$s = "";
set_string($s);
set_string($undef_string);
set_string($undef_array[2]);
class A extends stdClass
{
public $x = 0;
public static $y = 0;
public /*. void .*/ function by_ref(/*. int .*/ & $i)
{ $i=123; }
public /*. void .*/ function call_by_ref()
{
self::by_ref($this->x);
echo "x=", $this->x, "\n";
self::by_ref(self::$y);
echo self::$y;
}
public /*. void .*/ function new_self_parent()
{
$a = new self;
$b = new parent;
$c = new self();
$d = new parent();
}
public /*. void .*/ function self_parent_args(
/*. self .*/ $o1,
/*. parent .*/ $o2,
self $o3,
parent $o4)
{}
}
class B
{
public $x = 0;
}
$a = new A(); $a->x = 123;
$b = new A(); $b->x = 123;
if( $a === $b ) ;
if( $a instanceof A ) ;
if( ! $a instanceof B ) ;
$a->call_by_ref();
$a_clone = clone $a;
/* ****
$fr = pg_connect("dbname=icodb");
$to1 = (boolean) $fr;
$to2 = (int) $fr;
$to3 = (float) $fr;
$to4 = (string) $fr;
#$to5 = (array) $fr;
****/
/* Cmp ops: */
if( 1 < 2 || 1 <= 2 || 1 == 2 || 1 === 2 || 1 >= 2
|| "a"==="b" || "a" !== "b" ) ;
if( 1 < 2 || 0.5 >= 3.0 && "012" === "890"
|| 12 != 34 || 12 !== 34 || 1 === 3 and true or false xor true) ;
# All the valid combinations of visibility, static and final attributes:
final class Z {
public /*.int.*/ $a;
public static $b = 0;
static $c = 0;
static public $d = 0;
public /*. void .*/ function f(){}
public static /*. void .*/ function g(){}
public final /*. void .*/ function h(){}
static /*. void .*/ function i(){}
static public /*. void .*/ function j(){}
static final /*. void .*/ function k(){}
static public final /*. void .*/ function l(){}
static final public /*. void .*/ function m(){}
final /*. void .*/ function n(){}
final public /*. void .*/ function o(){}
final static /*. void .*/ function p(){}
final public static /*. void .*/ function q(){}
final static public /*. void .*/ function r(){}
}
# Exceptions:
class MyExc extends ErrorException {}
try {
$error = 'Always throw this error';
throw new Exception($error, 10);
throw new MyExc($error);
throw new MyExc();
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
catch (MyExc $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
/* Type hinting: */
/*. void .*/ function type_hinting(A $o){}
type_hinting(new A());
/* Typecasting: */
$tc1 = FALSE or (boolean) 1;
$tc2 = 1 + (int) "123";
$tc3 = 0.0 + (float) "3.14";
$tc4 = "abc" . (string) 123;
$tc5 = /*. (array[int]string) .*/ array(); $tc5[1] = "abc";
$tc6 = /*. (resource) .*/ count_chars("abc");
#$tc7 = /*. (object) .*/ new A();
#$tc8 = /*. (A) .*/ new A();
/*. void .*/ function LoginMask(/*. string .*/ $name)
{
?>
<html><body>
<form method=post action="<?= $_SERVER['PHP_SELF'] ?>">
</form>
</body></html>
<?
}
/* Error handling: */
$file = @fopen("text.php", "r");
class TestStaticExpr
{
const a = FALSE,
b = NULL,
c = 123,
d = -123,
e = "hello",
f = self::a,
# g = array("one", "two"),
# note: array() not allowed in class constants
h = 3.141592e-4;
public $a = FALSE,
$b = NULL,
$c = 123,
$d = -123,
$e = "hello",
$f = self::a,
$g = array("one", "two"),
$h = 3.141592e-4;
/*. void .*/ function f($a1=FALSE, $a2=NULL, $a3=-123,
$a5="hello", $a6=self::a, $a7=array("one", "two"), $a8=3.141592e-4)
{
static $a = FALSE,
$b = NULL,
$c = 123;
static $d = -123;
static $e = "hello";
static $f = self::a;
static $g = array("one", "two");
static $h = 3.141592e-4;
}
}
class SpecialMethods {
/*. void .*/ function __destruct(){}
public /*. void .*/ function __clone(){}
static /*. void .*/ function __set_static(/*. array[string]mixed .*/ $a){}
public /*. array[int]string .*/ function __sleep(){}
public /*. void .*/ function __wakeup(){}
public /*. string.*/ function __toString(){}
#public /*. void .*/ function __set(/*.string.*/ $n, /*. mixed .*/ $v){}
#public /*. mixed .*/ function __get(/*.string.*/ $n){}
#public /*. bool .*/ function __isset(/*.string.*/ $n){}
#public /*. void .*/ function __unset(/*.string.*/ $n){}
#public /*. mixed .*/ function __call(/*.string.*/ $n, /*. array[]mixed .*/ $a){}
}
$last_exception1 = /*. (Exception) .*/ NULL;
/*. Exception .*/ $last_exception2 = NULL;
/** @var Exception */
$last_exception3 = NULL;
/*
phpDocumentor DocBlocks
*/
# Empty DocBlocks:
/***/ # <== empty DocBlock
/** */
/**
*/
/** * */
/**
*
*/
/**
* short short
* long long
* long long
* long long
* long long
*/
$dummy10 = 1;
/**
* short short
* short short.
* long long
* long long
* long long
*/
$dummy11 = 1;
/**
* short short
* short short
* short short.
* long long
* long long
*/
$dummy12 = 1;
/**
* short short
*
* long long
*/
$dummy13 = 1;
/**
* short short
* short short
*
* long long
*/
$dummy14 = 1;
/**
* short short
* short short
* short short
*
* long long
*/
$dummy15 = 1;
/**
* short short
* long long
* long long
* long long
*
* long long
*/
$dummy16 = 1;
/**
* <b>bold</b> in short.
* <b>bold</b> in long.
*/
$dummy17 = 1;
/**
* Testing all the tags:
*
* ATTENTION<br>
* <b>bold</b> <i>italic</i> <code>Code</code> [BR here:]<br>
* [P here:]<p>
* <pre>
* while( $i >= 0 )
* $i--;
* </pre>
* <ul> <li><b>first bolded</b></li> <li>sublist:<ul><li>second</li></ul></li> <li>...and last</li> </ul>
* <ol> <li>first</li> <li>second</li> <li>...and last</li> </ol>
* <b><i>bold+italic</i></b>
*/
$dummy18 = 1;
/**#@+ FIXME: incomplete support for templates, now parsed but ignored */
/**#@-*/
/**
* A constant giving the number of days in a week
*/
define("WEEK_DAYS", 7);
/**
* Short description. This is the long long long description.
*
* @var array
*/
$emptyArray = array();
/**
* Another array
*
* @var array[int]string|int|FALSE
*/
$emptyArray2 = array("hello");
/**
* Another array
*
* @var array[int][string]string
*/
$emptyArray3 = array( array("s"=>"s") );
/**
* Simple test for docBlock
*
* This text follows an empty line, so it is moved to the long descr.
* @param int $len
* @param string $str
* @param Exception & $obj bla bla bla
* @return bool
* @author Umberto Salsi <phplint@icosaedro.it>
*/
function TestDocBlock($len, $str, &$obj)
{
return strlen($str) > $len;
}
/**
* Classic test class
*
*/
class docBlockCommentedClass {
/**
* The second integer number
*/
const TWO = 2;
/**
* @var int
*/
public $intProp;
/**
* Useless method
*
* Use this method to do nothing in a simple, efficient way.
*
* @param resource $fd
* @param string $name
* @return bool
*/
function aMethod($fd, $name){}
}
/* Abstract classes: */
abstract class Shape
{
const DEF_SCALE = 1.0;
public $x = 0.0, $y = 0.0;
/*. void .*/ function moveTo(/*. float .*/ $x, /*. float .*/ $y)
{
$this->x = $x;
$this->y = $y;
}
abstract /*. void .*/ function scale(/*. float .*/ $factor) ;
}
class Circle extends Shape
{
public $radius = 1.0;
/*. void .*/ function scale(/*. float .*/ $factor)
{
$this->radius *= $factor;
}
}
class Rectangle extends Shape
{
public $side_a = 1.0, $side_b = 2.0;
/*. void .*/ function scale(/*. float .*/ $factor)
{
$this->side_a *= $factor;
$this->side_b *= $factor;
}
}
$drawing = /*. (array[int]Shape) .*/ array();
/*. void .*/ function scale_shapes(/*. float .*/ $factor)
{
foreach($GLOBALS['drawing'] as $shape)
$shape->scale($factor);
}
$drawing[] = new Circle();
$drawing[] = new Circle();
$drawing[] = new Rectangle();
scale_shapes(100.0);
/* Interface test: */
interface DataContainer
{
/*. void .*/ function set(
/*. string .*/ $name,
/*. string .*/ $value);
/*. string .*/ function get(/*. string .*/ $name);
}
class FileBasedContainer implements DataContainer
{
private $base_dir = "";
/*. void .*/ function __construct(/*. string .*/ $base_dir)
{
$this->base_dir = $base_dir;
}
/*. void .*/ function set(
/*. string .*/ $name,
/*. string .*/ $value)
{
@file_put_contents($this->base_dir ."/". $name, $value);
}
/*. string .*/ function get(/*. string .*/ $name)
{
return @file_get_contents($this->base_dir ."/". $name);
}
}
/*. void .*/ function save_data(/*. array[string]mixed .*/ $arr, /*. DataContainer .*/ $c)
{
foreach($arr as $k => $v)
$c->set($k, serialize($v));
}
save_data( array("one"=>1, "two"=>2), new FileBasedContainer("/tmp") );
/**
Check DocBlock Parser.
@param int $a
@param int $b
@return void
*/
function docblock_f1($a, $b){}
/**
Check DocBlock Parser.
@param int $a
@param int $b
@return void
*/
function docblock_f2($a){}
/**
Check DocBlock Parser.
@param int $a
@param int $b
@return void
*/
function docblock_f3($a, $b, $c){}
/**
Check DocBlock Parser.
@param int $a
@param int $b
@param int $c
@return void
*/
function docblock_f4($a, $b){}
/**
Check DocBlock Parser.
@param int $a
@param int $z
@return void
*/
function docblock_f5($a, $b){}
/**
Check DocBlock Parser.
@param int $a
@param int $b
@return void
*/
function docblock_f6($a, $b){ return 1; }
/**
Check DocBlock Parser.
@param int $a
@param int $b
@return void
*/
/*. int .*/ function docblock_f7(/*. float .*/ $a, /*. float .*/ $b){ return 1; }
// Array short syntax - static expression:
function array_short_syntax($a = [], $b = ["a"], $c = [1, 2]){}
// Array short syntax - non-static expression:
$array_short_syntax_1 = []; if($array_short_syntax_1);
$array_short_syntax_2 = ["a"]; if($array_short_syntax_2);
$array_short_syntax_3 = [1, 2]; if($array_short_syntax_3);
// ClassName::class special constant:
const X = Exception::class;
echo Exception::class, X, "\n";
?> <?= "...", "..." ?> PHP execution terminated.
| bsd-3-clause |
NLog/NLog | tests/NLog.UnitTests/Layouts/LayoutTypedTests.cs | 32395 | //
// Copyright (c) 2004-2021 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.
//
using System;
using NLog.Layouts;
using Xunit;
namespace NLog.UnitTests.Layouts
{
public class LayoutTypedTests : NLogTestBase
{
[Fact]
public void LayoutFixedIntValueTest()
{
// Arrange
Layout<int> layout = 5;
// Act
var result = layout.RenderValue(LogEventInfo.CreateNullEvent());
// Assert
Assert.Equal(5, result);
Assert.Equal("5", layout.Render(LogEventInfo.CreateNullEvent()));
Assert.True(layout.IsFixed);
Assert.Equal(5, layout.FixedValue);
Assert.Equal("5", layout.ToString());
Assert.Equal(5, layout);
Assert.NotEqual(0, layout);
}
[Fact]
public void LayoutFixedNullableIntValueTest()
{
// Arrange
Layout<int?> layout = 5;
// Act
var result = layout.RenderValue(LogEventInfo.CreateNullEvent());
// Assert
Assert.Equal(5, result);
Assert.Equal("5", layout.Render(LogEventInfo.CreateNullEvent()));
Assert.True(layout.IsFixed);
Assert.Equal(5, layout.FixedValue);
Assert.Equal("5", layout.ToString());
Assert.Equal(5, layout);
Assert.NotEqual(0, layout);
Assert.NotEqual(default(int?), layout);
}
[Fact]
public void LayoutFixedNullIntValueTest()
{
// Arrange
var nullValue = (int?)null;
Layout<int?> layout = new Layout<int?>(nullValue);
// Act
var result = layout.RenderValue(LogEventInfo.CreateNullEvent());
var result5 = layout.RenderValue(LogEventInfo.CreateNullEvent(), 5);
// Assert
Assert.Null(result);
Assert.Null(result5);
Assert.Equal("", layout.Render(LogEventInfo.CreateNullEvent()));
Assert.True(layout.IsFixed);
Assert.Null(layout.FixedValue);
Assert.Equal("null", layout.ToString());
Assert.Equal(nullValue, layout);
Assert.NotEqual(0, layout);
}
[Fact]
public void LayoutFixedUrlValueTest()
{
// Arrange
var uri = new Uri("http://nlog");
Layout<Uri> layout = uri.ToString();
// Act
var result = layout.RenderValue(LogEventInfo.CreateNullEvent());
// Assert
Assert.Equal(uri, result);
Assert.Same(result, layout.RenderValue(LogEventInfo.CreateNullEvent()));
Assert.Equal(uri.ToString(), layout.Render(LogEventInfo.CreateNullEvent()));
Assert.Equal(uri, layout);
Assert.True(layout.IsFixed);
Assert.Equal(uri, layout.FixedValue);
Assert.Same(layout.FixedValue, layout.FixedValue);
Assert.Equal(uri.ToString(), layout.ToString());
Assert.Equal(uri, layout);
Assert.NotEqual(new Uri("//other"), layout);
Assert.NotEqual(default(Uri), layout);
}
[Fact]
public void LayoutFixedNullUrlValueTest()
{
// Arrange
Uri uri = null;
Layout<Uri> layout = new Layout<Uri>(uri);
// Act
var result = layout.RenderValue(LogEventInfo.CreateNullEvent());
// Assert
Assert.Equal(uri, result);
Assert.Same(result, layout.RenderValue(LogEventInfo.CreateNullEvent()));
Assert.Equal("", layout.Render(LogEventInfo.CreateNullEvent()));
Assert.True(layout == uri);
Assert.False(layout != uri);
Assert.True(layout.IsFixed);
Assert.Equal(uri, layout.FixedValue);
Assert.Same(layout.FixedValue, layout.FixedValue);
Assert.Equal("null", layout.ToString());
Assert.NotEqual(new Uri("//other"), layout);
}
[Fact]
public void NullLayoutDefaultValueTest()
{
var nullLayout = default(Layout<int>);
Assert.True(default(Layout<int>) == nullLayout);
Assert.False(default(Layout<int>) != nullLayout);
Assert.True(default(Layout<int>) == default(int));
Assert.False(default(Layout<int>) != default(int));
Assert.True(default(Layout<int>) == null);
Assert.False(default(Layout<int>) != null);
Assert.True(default(Layout<int?>) == default(int?));
Assert.False(default(Layout<int?>) != default(int?));
Assert.True(default(Layout<int?>) == null);
Assert.False(default(Layout<int?>) != null);
Assert.True(default(Layout<Uri>) == default(Uri));
Assert.False(default(Layout<Uri>) != default(Uri));
Assert.True(default(Layout<Uri>) == null);
Assert.False(default(Layout<Uri>) != null);
}
[Fact]
public void LayoutDynamicIntValueTest()
{
// Arrange
string simpleLayout = "${event-properties:intvalue}";
Layout<int> layout = simpleLayout;
// Act
var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{intvalue}", new object[] { 5 });
var result = layout.RenderValue(logevent);
// Assert
Assert.Equal(5, result);
Assert.Equal("5", layout.Render(logevent));
Assert.False(layout.IsFixed);
Assert.Equal(simpleLayout, layout.ToString());
Assert.NotEqual(0, layout);
}
[Fact]
public void LayoutDynamicNullableIntValueTest()
{
// Arrange
Layout<int?> layout = "${event-properties:intvalue}";
// Act
var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{intvalue}", new object[] { 5 });
var result = layout.RenderValue(logevent);
// Assert
Assert.Equal(5, result);
Assert.Equal("5", layout.Render(logevent));
Assert.False(layout.IsFixed);
Assert.NotEqual(0, layout);
Assert.NotEqual(default(int?), layout);
}
[Fact]
public void LayoutDynamicNullableGuidValueTest()
{
// Arrange
Layout<Guid?> layout = "${event-properties:guidvalue}";
var guid = Guid.NewGuid();
// Act
var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{guidvalue}", new object[] { guid });
var result = layout.RenderValue(logevent);
// Assert
Assert.Equal(guid, result);
Assert.Equal(guid.ToString(), layout.Render(logevent));
Assert.False(layout.IsFixed);
Assert.NotEqual(default(Guid), layout);
Assert.NotEqual(default(Guid?), layout);
}
[Fact]
public void LayoutDynamicNullIntValueTest()
{
// Arrange
Layout<int?> layout = "${event-properties:intvalue}";
// Act
var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{intvalue}", new object[] { null });
var result = layout.RenderValue(logevent);
var result5 = layout.RenderValue(logevent, 5);
// Assert
Assert.Null(result);
Assert.Equal(5, result5);
Assert.Equal("", layout.Render(logevent));
}
[Fact]
public void LayoutDynamicUrlValueTest()
{
// Arrange
Layout<Uri> layout = "${event-properties:urlvalue}";
var uri = new Uri("http://nlog");
// Act
var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{urlvalue}", new object[] { uri.ToString() });
var result = layout.RenderValue(logevent);
// Assert
Assert.Equal(uri, result);
Assert.Same(result, layout.RenderValue(logevent));
Assert.Equal(uri.ToString(), layout.Render(logevent));
Assert.False(layout.IsFixed);
Assert.NotEqual(uri, layout);
Assert.NotEqual(default(Uri), layout);
}
[Fact]
public void LayoutDynamicNullUrlValueTest()
{
// Arrange
Layout<Uri> layout = "${event-properties:urlvalue}";
Uri uri = null;
// Act
var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{urlvalue}", new object[] { uri });
var result = layout.RenderValue(logevent);
// Assert
Assert.Equal(uri, result);
Assert.Same(result, layout.RenderValue(logevent));
Assert.Equal("", layout.Render(logevent));
Assert.False(layout.IsFixed);
Assert.NotEqual(uri, layout);
}
[Fact]
public void LayoutDynamicIntValueAsyncTest()
{
// Arrange
Layout<int> layout = "${scopeproperty:intvalue}";
// Act
var logevent = LogEventInfo.CreateNullEvent();
using (ScopeContext.PushProperty("intvalue", 5))
{
layout.Precalculate(logevent);
}
// Assert
Assert.Equal(5, layout.RenderValue(logevent));
Assert.Equal("5", layout.Render(logevent));
Assert.False(layout.IsFixed);
Assert.NotEqual(0, layout);
}
[Fact]
public void LayoutDynamicNullableIntValueAsyncTest()
{
// Arrange
Layout<int?> layout = "${scopeproperty:intvalue}";
// Act
var logevent = LogEventInfo.CreateNullEvent();
using (ScopeContext.PushProperty("intvalue", 5))
{
layout.Precalculate(logevent);
}
// Assert
Assert.Equal(5, layout.RenderValue(logevent));
Assert.Equal("5", layout.Render(logevent));
Assert.False(layout.IsFixed);
Assert.NotEqual(0, layout);
Assert.NotEqual(default(int?), layout);
}
[Fact]
public void LayoutDynamicUrlValueAsyncTest()
{
// Arrange
Layout<Uri> layout = "${scopeproperty:urlvalue}";
var uri = new Uri("http://nlog");
// Act
var logevent = LogEventInfo.CreateNullEvent();
using (ScopeContext.PushProperty("urlvalue", uri.ToString()))
{
layout.Precalculate(logevent);
}
// Assert
Assert.Equal(uri, layout.RenderValue(logevent));
Assert.Same(layout.RenderValue(logevent), layout.RenderValue(logevent));
Assert.Equal(uri.ToString(), layout.Render(logevent));
Assert.False(layout.IsFixed);
Assert.NotEqual(uri, layout);
Assert.NotEqual(default(Uri), layout);
}
[Fact]
public void LayoutDynamicUrlValueRawAsyncTest()
{
// Arrange
Layout<Uri> layout = "${event-properties:urlvalue}";
var uri = new Uri("http://nlog");
// Act
var logevent = LogEventInfo.Create(LogLevel.Info, null, null, "{urlvalue}", new object[] { uri });
layout.Precalculate(logevent);
// Assert
Assert.Same(uri, layout.RenderValue(logevent));
Assert.Same(layout.RenderValue(logevent), layout.RenderValue(logevent));
Assert.Same(uri, layout.RenderValue(logevent));
Assert.Equal(uri.ToString(), layout.Render(logevent));
Assert.False(layout.IsFixed);
Assert.NotEqual(uri, layout);
Assert.NotEqual(default(Uri), layout);
}
[Fact]
public void LayoutDynamicRenderExceptionTypeTest()
{
// Arrange
Layout<Type> layout = "${exception:format=type:norawvalue=true}";
var exception = new System.ApplicationException("Test");
var stringBuilder = new System.Text.StringBuilder();
// Act
var logevent = LogEventInfo.Create(LogLevel.Info, null, exception, null, "");
var exceptionType = layout.RenderTypedValue(logevent, stringBuilder, null);
stringBuilder.Length = 0;
// Assert
Assert.Equal(exception.GetType(), exceptionType);
Assert.Same(exceptionType, layout.RenderTypedValue(logevent, stringBuilder, null));
}
[Fact]
public void ComplexTypeTestWithStringConversion()
{
// Arrange
var value = "utf8";
var layout = CreateLayoutRenderedFromProperty<System.Text.Encoding>();
var logEventInfo = CreateLogEventInfoWithValue(value);
// Act
var result = layout.RenderValue(logEventInfo);
// Assert
Assert.Equal(System.Text.Encoding.UTF8.EncodingName, result.EncodingName);
}
[Fact]
public void LayoutRenderIntValueWhenNull()
{
// Arrange
var integer = 42;
Layout<int> layout = null;
// Act
var value = LayoutTypedExtensions.RenderValue(layout, null, integer);
// Assert
Assert.Equal(integer, value);
}
[Fact]
public void LayoutRenderNullableIntValueWhenNull()
{
// Arrange
var integer = 42;
Layout<int?> layout = null;
// Act
var value = LayoutTypedExtensions.RenderValue(layout, null, integer);
// Assert
Assert.Equal(integer, value);
}
[Fact]
public void LayoutRenderUrlValueWhenNull()
{
// Arrange
var url = new Uri("http://nlog");
Layout<Uri> layout = null;
// Act
var value = LayoutTypedExtensions.RenderValue(layout, null, url);
// Assert
Assert.Equal(url, value);
}
[Fact]
public void LayoutEqualsIntValueFixedTest()
{
// Arrange
Layout<int> layout1 = "42";
Layout<int> layout2 = "42";
// Act + Assert
Assert.True(layout1 == 42);
Assert.True(layout1.Equals(42));
Assert.True(layout1.Equals((object)42));
Assert.Equal(layout1, layout2);
Assert.Equal(layout1.GetHashCode(), layout2.GetHashCode());
}
[Fact]
public void LayoutEqualsNullableIntValueFixedTest()
{
// Arrange
Layout<int?> layout1 = "42";
Layout<int?> layout2 = "42";
// Act + Assert
Assert.True(layout1 == 42);
Assert.True(layout1.Equals(42));
Assert.True(layout1.Equals((object)42));
Assert.Equal(layout1, layout2);
Assert.Equal(layout1.GetHashCode(), layout2.GetHashCode());
}
[Fact]
public void LayoutEqualsNullIntValueFixedTest()
{
// Arrange
int? nullInt = null;
Layout<int?> layout1 = nullInt;
Layout<int?> layout2 = nullInt;
// Act + Assert
Assert.True(layout1 == nullInt);
Assert.True(layout1.Equals(nullInt));
Assert.True(layout1.Equals((object)nullInt));
Assert.Equal(layout1, layout2);
Assert.Equal(layout1.GetHashCode(), layout2.GetHashCode());
}
[Fact]
public void LayoutNotEqualsIntValueFixedTest()
{
// Arrange
Layout<int> layout1 = "2";
Layout<int> layout2 = "42";
// Act + Assert
Assert.False(layout1 == 42);
Assert.False(layout1.Equals(42));
Assert.False(layout1.Equals((object)42));
Assert.NotEqual(layout1, layout2);
Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode());
}
[Fact]
public void LayoutNotEqualsNullableIntValueFixedTest()
{
// Arrange
Layout<int?> layout1 = "2";
Layout<int?> layout2 = "42";
// Act + Assert
Assert.False(layout1 == 42);
Assert.False(layout1.Equals(42));
Assert.False(layout1.Equals((object)42));
Assert.NotEqual(layout1, layout2);
Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode());
}
[Fact]
public void LayoutNotEqualsNullIntValueFixedTest()
{
// Arrange
int? nullInt = null;
Layout<int?> layout1 = "2";
Layout<int?> layout2 = nullInt;
// Act + Assert
Assert.False(layout1 == nullInt);
Assert.False(layout1.Equals(nullInt));
Assert.False(layout1.Equals((object)nullInt));
Assert.NotEqual(layout1, layout2);
Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode());
}
[Fact]
public void LayoutEqualsUrlValueFixedTest()
{
// Arrange
var url = new Uri("http://nlog");
Layout<Uri> layout1 = url;
Layout<Uri> layout2 = url;
// Act + Assert
Assert.True(layout1 == url);
Assert.True(layout1.Equals(url));
Assert.True(layout1.Equals((object)url));
Assert.Equal(layout1, layout2);
Assert.Equal(layout1.GetHashCode(), layout2.GetHashCode());
}
[Fact]
public void LayoutEqualsNullUrlValueFixedTest()
{
// Arrange
Uri url = null;
Layout<Uri> layout1 = url;
Layout<Uri> layout2 = new Layout<Uri>(url);
// Act + Assert
Assert.Null(layout1);
Assert.True(layout1 == url);
Assert.True(layout2 == url);
Assert.True(layout2.Equals(url));
Assert.True(layout2.Equals((object)url));
Assert.NotEqual(layout1, layout2);
}
[Fact]
public void LayoutNotEqualsUrlValueFixedTest()
{
// Arrange
var url = new Uri("http://nlog");
var url2 = new Uri("http://nolog");
Layout<Uri> layout1 = url2;
Layout<Uri> layout2 = url;
// Act + Assert
Assert.False(layout1 == url);
Assert.False(layout1.Equals(url));
Assert.False(layout1.Equals((object)url));
Assert.NotEqual(layout1, layout2);
Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode());
}
[Fact]
public void LayoutNotEqualsNullUrlValueFixedTest()
{
// Arrange
Uri url = null;
var url2 = new Uri("http://nlog");
Layout<Uri> layout1 = url2;
Layout<Uri> layout2 = new Layout<Uri>(url);
// Act + Assert
Assert.False(layout1 == url);
Assert.False(layout1.Equals(url));
Assert.False(layout1.Equals((object)url));
Assert.NotEqual(layout1, layout2);
Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode());
}
[Fact]
public void LayoutEqualsIntValueDynamicTest()
{
// Arrange
Layout<int> layout1 = "${event-properties:intvalue}";
Layout<int> layout2 = "${event-properties:intvalue}";
// Act + Assert (LogEventInfo.LayoutCache must work)
Assert.NotEqual(layout1, layout2);
Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode());
Assert.NotEqual(0, layout1);
}
[Fact]
public void LayoutEqualsNullableIntValueDynamicTest()
{
// Arrange
Layout<int?> layout1 = "${event-properties:intvalue}";
Layout<int?> layout2 = "${event-properties:intvalue}";
// Act + Assert (LogEventInfo.LayoutCache must work)
Assert.NotEqual(layout1, layout2);
Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode());
Assert.NotEqual(0, layout1);
Assert.NotEqual(default(int?), layout1);
}
[Fact]
public void LayoutEqualsUrlValueDynamicTest()
{
// Arrange
Layout<Uri> layout1 = "${event-properties:urlvalue}";
Layout<Uri> layout2 = "${event-properties:urlvalue}";
// Act + Assert (LogEventInfo.LayoutCache must work)
Assert.NotEqual(layout1, layout2);
Assert.NotEqual(layout1.GetHashCode(), layout2.GetHashCode());
Assert.NotEqual(default(Uri), layout1);
}
[Theory]
[InlineData(100)]
[InlineData(100d)]
[InlineData("100")]
[InlineData(" 100 ")]
public void TypedIntLayoutDynamicTest(object value)
{
// Arrange
var layout = CreateLayoutRenderedFromProperty<int>();
var logEventInfo = CreateLogEventInfoWithValue(value);
// Act
var result = layout.RenderValue(logEventInfo);
// Assert
Assert.Equal(100, result);
}
[Fact]
public void TypedNullableIntToIntLayoutDynamicTest()
{
// Arrange
var layout = CreateLayoutRenderedFromProperty<int>();
int? value = 100;
var logEventInfo = CreateLogEventInfoWithValue(value);
// Act
var result = layout.RenderValue(logEventInfo);
// Assert
Assert.Equal(100, result);
}
[Theory]
[InlineData(100)]
[InlineData(100d)]
[InlineData("100")]
[InlineData(" 100 ")]
public void TypedNullableIntLayoutDynamicTest(object value)
{
// Arrange
var layout = CreateLayoutRenderedFromProperty<int?>();
var logEventInfo = CreateLogEventInfoWithValue(value);
// Act
var result = layout.RenderValue(logEventInfo);
// Assert
Assert.Equal(100, result);
}
[Theory]
[InlineData(100.5)]
[InlineData("100.5", "EN-us")]
[InlineData(" 100.5 ", "EN-us")]
public void TypedDecimalLayoutDynamicTest(object value, string culture = null)
{
// Arrange
var oldCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
try
{
if (!string.IsNullOrEmpty(culture))
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture);
}
var layout = CreateLayoutRenderedFromProperty<decimal>();
var logEventInfo = CreateLogEventInfoWithValue(value);
// Act
var result = layout.RenderValue(logEventInfo);
// Assert
decimal expected = 100.5m;
Assert.Equal(expected, result);
}
finally
{
System.Threading.Thread.CurrentThread.CurrentCulture = oldCulture;
}
}
[Theory]
[InlineData(true)]
[InlineData("true")]
[InlineData(" true ")]
public void TypedBoolLayoutDynamicTest(object value)
{
// Arrange
var layout = CreateLayoutRenderedFromProperty<bool>();
var logEventInfo = CreateLogEventInfoWithValue(value);
// Act
var result = layout.RenderValue(logEventInfo);
// Assert
Assert.True(result);
}
/// <remarks>Cache usage, see coverage result</remarks>
[Fact]
public void SameValueShouldUseCacheAndCorrectResult()
{
// Arrange
var layout = CreateLayoutRenderedFromProperty<bool>();
var logEventInfo1 = CreateLogEventInfoWithValue("true");
var logEventInfo2 = CreateLogEventInfoWithValue("true");
var logEventInfo3 = CreateLogEventInfoWithValue("true");
// Act
var result1 = layout.RenderValue(logEventInfo1);
var result2 = layout.RenderValue(logEventInfo2);
var result3 = layout.RenderValue(logEventInfo3);
// Assert
Assert.True(result1);
Assert.True(result2);
Assert.True(result3);
}
[Fact]
public void ComplexTypeTest()
{
// Arrange + Act + Assert
Assert.Throws<NLogConfigurationException>(() => CreateLayoutRenderedFromProperty<TestObject>());
}
[Fact]
public void WrongValueErrorTest()
{
// Arrange
var value = "12312aa3";
var layout = CreateLayoutRenderedFromProperty<int>();
var logEventInfo = CreateLogEventInfoWithValue(value);
// Act
var result = layout.RenderValue(logEventInfo);
// Assert
Assert.Equal(0, result);
}
[Theory]
[InlineData("100", 100)]
[InlineData("1 00", null)]
public void TryGetRawValueTest(string input, int? expected)
{
// Arrange
var layout = new Layout<int?>("${event-properties:prop1}");
var logEventInfo = LogEventInfo.CreateNullEvent();
logEventInfo.Properties["prop1"] = input;
// Act
var result = layout.RenderValue(logEventInfo);
// Assert
Assert.Equal(expected, result);
}
[Fact]
public void TryConvertToShouldHandleNullLayout()
{
// Arrange
var layout = new Layout<int>((Layout)null);
var logEventInfo = LogEventInfo.CreateNullEvent();
// Act
var result = layout.RenderValue(logEventInfo);
// Assert
Assert.Equal(0, result);
}
[Fact]
public void RenderShouldHandleInvalidConversionAndLogFactory()
{
// Arrange
var factory = new LogFactory
{
ThrowExceptions = false,
};
var configuration = new NLog.Config.LoggingConfiguration(factory);
var layout = new Layout<int>("${event-properties:prop1}");
layout.Initialize(configuration);
var logEventInfo = LogEventInfo.CreateNullEvent();
logEventInfo.Properties["prop1"] = "Not a int";
// Act
int result;
using (new NoThrowNLogExceptions())
{
result = layout.RenderValue(logEventInfo);
}
// Assert
Assert.Equal(0, result);
}
[Fact]
public void RenderShouldHandleInvalidConversionAndLogFactoryAndDefault()
{
// Arrange
var factory = new LogFactory
{
ThrowExceptions = false,
};
var configuration = new NLog.Config.LoggingConfiguration(factory);
var layout = new Layout<int>("${event-properties:prop1}");
layout.Initialize(configuration);
var logEventInfo = LogEventInfo.CreateNullEvent();
logEventInfo.Properties["prop1"] = "Not a int";
// Act
int result;
using (new NoThrowNLogExceptions())
{
result = layout.RenderValue(logEventInfo, 200);
}
// Assert
Assert.Equal(200, result);
}
[Fact]
public void RenderShouldHandleValidConversion()
{
// Arrange
var layout = new Layout<int>("${event-properties:prop1}");
var logEventInfo = LogEventInfo.CreateNullEvent();
logEventInfo.Properties["prop1"] = "100";
// Act
var result = layout.RenderValue(logEventInfo);
// Assert
Assert.Equal(100, result);
}
#if !DEBUG
[Fact(Skip = "RELEASE not working, only DEBUG")]
#else
[Fact]
#endif
public void RenderShouldRecognizeStackTraceUsage()
{
// Arrange
object[] callback_args = null;
Action<LogEventInfo, object[]> callback = (evt, args) => callback_args = args;
var logger = new LogFactory().Setup().LoadConfiguration(builder =>
{
var methodCall = new NLog.Targets.MethodCallTarget("dbg", callback);
methodCall.Parameters.Add(new NLog.Targets.MethodCallParameter("LineNumber", "${callsite-linenumber}", typeof(int)));
builder.ForLogger().WriteTo(methodCall);
}).GetLogger(nameof(RenderShouldRecognizeStackTraceUsage));
// Act
logger.Info("Testing");
// Assert
Assert.Single(callback_args);
var lineNumber = Assert.IsType<int>(callback_args[0]);
Assert.True(lineNumber > 0);
}
[Fact]
public void LayoutRendererSupportTypedLayout()
{
var cif = new NLog.Config.ConfigurationItemFactory();
cif.RegisterType(typeof(LayoutTypedTestLayoutRenderer), string.Empty);
Layout l = new SimpleLayout("${LayoutTypedTestLayoutRenderer:IntProperty=42}", cif);
l.Initialize(null);
var result = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("42", result);
}
private class TestObject
{
public string Value { get; set; }
}
private static Layout<T> CreateLayoutRenderedFromProperty<T>()
{
var layout = new Layout<T>("${event-properties:value1}");
return layout;
}
private static LogEventInfo CreateLogEventInfoWithValue(object value)
{
var logEventInfo = LogEventInfo.Create(LogLevel.Info, "logger1", "message1");
logEventInfo.Properties.Add("value1", value);
return logEventInfo;
}
[NLog.LayoutRenderers.LayoutRenderer(nameof(LayoutTypedTestLayoutRenderer))]
public class LayoutTypedTestLayoutRenderer : NLog.LayoutRenderers.LayoutRenderer
{
public Layout<int> IntProperty { get; set; } = 0;
protected override void Append(System.Text.StringBuilder builder, LogEventInfo logEvent)
{
builder.Append(IntProperty.RenderValue(logEvent).ToString());
}
}
}
}
| bsd-3-clause |
endlessm/chromium-browser | chromeos/services/secure_channel/connection_medium.cc | 544 | // Copyright 2018 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 "chromeos/services/secure_channel/connection_medium.h"
#include "base/check.h"
namespace chromeos {
namespace secure_channel {
std::ostream& operator<<(std::ostream& stream, const ConnectionMedium& medium) {
DCHECK(medium == ConnectionMedium::kBluetoothLowEnergy);
stream << "[BLE]";
return stream;
}
} // namespace secure_channel
} // namespace chromeos
| bsd-3-clause |
endlessm/chromium-browser | chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/library/feedsessionmanager/internal/SessionContentTracker.java | 2491 | // 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.
package org.chromium.chrome.browser.feed.library.feedsessionmanager.internal;
import org.chromium.chrome.browser.feed.library.common.logging.Dumpable;
import org.chromium.chrome.browser.feed.library.common.logging.Dumper;
import org.chromium.chrome.browser.feed.library.common.logging.Logger;
import org.chromium.components.feed.core.proto.libraries.api.internal.StreamDataProto.StreamStructure;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/** Class tracking the content IDs associated to a session. */
public class SessionContentTracker implements Dumpable {
private static final String TAG = "SessionContentTracker";
private final boolean mSupportsClearAll;
private final Set<String> mContentIds = new HashSet<>();
SessionContentTracker(boolean supportsClearAll) {
this.mSupportsClearAll = supportsClearAll;
}
public boolean isEmpty() {
return mContentIds.isEmpty();
}
public void clear() {
mContentIds.clear();
}
public boolean contains(String contentId) {
return mContentIds.contains(contentId);
}
public Set<String> getContentIds() {
return new HashSet<>(mContentIds);
}
public void update(StreamStructure streamStructure) {
String contentId = streamStructure.getContentId();
switch (streamStructure.getOperation()) {
case UPDATE_OR_APPEND: // Fall-through
case REQUIRED_CONTENT:
mContentIds.add(contentId);
break;
case REMOVE:
mContentIds.remove(contentId);
break;
case CLEAR_ALL:
if (mSupportsClearAll) {
mContentIds.clear();
} else {
Logger.i(TAG, "CLEAR_ALL not supported.");
}
break;
default:
Logger.e(TAG, "unsupported operation: %s", streamStructure.getOperation());
}
}
public void update(List<StreamStructure> streamStructures) {
for (StreamStructure streamStructure : streamStructures) {
update(streamStructure);
}
}
@Override
public void dump(Dumper dumper) {
dumper.title(TAG);
dumper.forKey("contentIds").value(mContentIds.size());
}
}
| bsd-3-clause |
wdavidw/node-csv-docs | .eslintrc.js | 128 | module.exports = {
globals: {
__PATH_PREFIX__: true,
},
extends: `react-app`,
"rules": {
"no-eval": true
}
}
| bsd-3-clause |
Team3574/Alastair | src/edu/wpi/first/wpilibj/templates/subsystems/Drive.java | 3229 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.subsystems;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.templates.RobotMap;
import edu.wpi.first.wpilibj.templates.commands.Drive.DriveWithJoysticks;
import team.util.DeadReckoner;
import team.util.Location;
/**
*
* @author team3574
*/
public class Drive extends Subsystem {
// Put methods for controlling this subsystem
// here. Call these from Commands.
Jaguar frontRightMotor = RobotMap.frontRightMotor;
Jaguar frontLeftMotor = RobotMap.frontLeftMotor;
Jaguar backRightMotor = RobotMap.backRightMotor;
Jaguar backLeftMotor = RobotMap.backLeftMotor;
Encoder leftWheelEncoder = RobotMap.leftWheelEncoder;
Encoder rightWheelEncoder = RobotMap.rightWheelEncoder;
double scaler = 1;
DeadReckoner myLocation;
//RobotDrive robotDrive = new RobotDrive(frontLeftMotor, backLeftMotor, frontRightMotor, backRightMotor);
public Drive() {
super("Drive");
leftWheelEncoder.start();
rightWheelEncoder.start();
myLocation = new DeadReckoner(leftWheelEncoder, rightWheelEncoder);
LiveWindow.addActuator("Drive", "back left " + backLeftMotor.getChannel(), backLeftMotor);
LiveWindow.addActuator("Drive", "front left " + frontLeftMotor.getChannel(), frontLeftMotor);
LiveWindow.addSensor("Drive", "Left ENCODER ", leftWheelEncoder);
LiveWindow.addActuator("Drive", "back right " + backRightMotor.getChannel(), backRightMotor);
LiveWindow.addActuator("Drive", "front right " + frontRightMotor.getChannel(), frontRightMotor);
LiveWindow.addSensor("Drive", "Right ENCODER ", rightWheelEncoder);
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
setDefaultCommand(new DriveWithJoysticks());
}
public void updateDeadReckoner() {
myLocation.execute();
}
public Location getLocation() {
return myLocation.getLocation();
}
public void resetDeadReckoner() {
myLocation.resetPosition();
leftWheelEncoder.reset();
rightWheelEncoder.reset();
}
public void goVariable(double leftSpeed, double rightSpeed) {
//robotDrive.tankDrive(leftSpeed, rightSpeed);
frontLeftMotor.set(-leftSpeed * scaler);
backLeftMotor.set(-leftSpeed * scaler);
frontRightMotor.set(rightSpeed * scaler);
backRightMotor.set(rightSpeed * scaler);
this.updateDeadReckoner();
}
public void shiftScale() {
if (scaler == 1.0) {
scaler = 0.8;
} else {
scaler = 1.0;
}
}
public void updateStatus() {
SmartDashboard.putNumber("Loc X", myLocation.getLocation().getXLocation());
SmartDashboard.putNumber("Loc Y", myLocation.getLocation().getYLocation());
SmartDashboard.putNumber("Loc Heading", myLocation.getLocation().getHeading());
SmartDashboard.putNumber("Left Encoder", leftWheelEncoder.get());
SmartDashboard.putNumber("Right Encoder", rightWheelEncoder.get());
}
}
| bsd-3-clause |
patrickm/chromium.src | sync/notifier/gcm_network_channel_unittest.cc | 18455 | // 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 "base/run_loop.h"
#include "base/strings/string_util.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "net/url_request/test_url_fetcher_factory.h"
#include "net/url_request/url_request_test_util.h"
#include "sync/notifier/gcm_network_channel.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace syncer {
class TestGCMNetworkChannelDelegate : public GCMNetworkChannelDelegate {
public:
TestGCMNetworkChannelDelegate()
: register_call_count_(0) {}
virtual void Initialize() OVERRIDE {}
virtual void RequestToken(RequestTokenCallback callback) OVERRIDE {
request_token_callback = callback;
}
virtual void InvalidateToken(const std::string& token) OVERRIDE {
invalidated_token = token;
}
virtual void Register(RegisterCallback callback) OVERRIDE {
++register_call_count_;
register_callback = callback;
}
virtual void SetMessageReceiver(MessageCallback callback) OVERRIDE {
message_callback = callback;
}
RequestTokenCallback request_token_callback;
std::string invalidated_token;
RegisterCallback register_callback;
int register_call_count_;
MessageCallback message_callback;
};
// Backoff policy for test. Run first 5 retries without delay.
const net::BackoffEntry::Policy kTestBackoffPolicy = {
// Number of initial errors (in sequence) to ignore before applying
// exponential back-off rules.
5,
// Initial delay for exponential back-off in ms.
2000, // 2 seconds.
// Factor by which the waiting time will be multiplied.
2,
// Fuzzing percentage. ex: 10% will spread requests randomly
// between 90%-100% of the calculated time.
0.2, // 20%.
// Maximum amount of time we are willing to delay our request in ms.
1000 * 3600 * 4, // 4 hours.
// Time to keep an entry from being discarded even when it
// has no significant state, -1 to never discard.
-1,
// Don't use initial delay unless the last request was an error.
false,
};
class TestGCMNetworkChannel : public GCMNetworkChannel {
public:
TestGCMNetworkChannel(
scoped_refptr<net::URLRequestContextGetter> request_context_getter,
scoped_ptr<GCMNetworkChannelDelegate> delegate)
: GCMNetworkChannel(request_context_getter, delegate.Pass()) {
ResetRegisterBackoffEntryForTest(&kTestBackoffPolicy);
}
protected:
// On Android GCMNetworkChannel::BuildUrl hits NOTREACHED(). I still want
// tests to run.
virtual GURL BuildUrl(const std::string& registration_id) OVERRIDE {
return GURL("http://test.url.com");
}
};
class GCMNetworkChannelTest;
// Test needs to capture setting echo-token header on http request.
// This class is going to do that.
class TestNetworkChannelURLFetcher : public net::FakeURLFetcher {
public:
TestNetworkChannelURLFetcher(GCMNetworkChannelTest* test,
const GURL& url,
net::URLFetcherDelegate* delegate,
const std::string& response_data,
net::HttpStatusCode response_code,
net::URLRequestStatus::Status status)
: net::FakeURLFetcher(url,
delegate,
response_data,
response_code,
status),
test_(test) {}
virtual void AddExtraRequestHeader(const std::string& header_line) OVERRIDE;
private:
GCMNetworkChannelTest* test_;
};
class GCMNetworkChannelTest
: public ::testing::Test,
public SyncNetworkChannel::Observer {
public:
GCMNetworkChannelTest()
: delegate_(NULL),
url_fetchers_created_count_(0),
last_invalidator_state_(TRANSIENT_INVALIDATION_ERROR) {}
virtual ~GCMNetworkChannelTest() {
}
virtual void SetUp() {
request_context_getter_ = new net::TestURLRequestContextGetter(
base::MessageLoopProxy::current());
// Ownership of delegate goes to GCNMentworkChannel but test needs pointer
// to it.
delegate_ = new TestGCMNetworkChannelDelegate();
scoped_ptr<GCMNetworkChannelDelegate> delegate(delegate_);
gcm_network_channel_.reset(new TestGCMNetworkChannel(
request_context_getter_,
delegate.Pass()));
gcm_network_channel_->AddObserver(this);
gcm_network_channel_->SetMessageReceiver(
invalidation::NewPermanentCallback(
this, &GCMNetworkChannelTest::OnIncomingMessage));
url_fetcher_factory_.reset(new net::FakeURLFetcherFactory(NULL,
base::Bind(&GCMNetworkChannelTest::CreateURLFetcher,
base::Unretained(this))));
}
virtual void TearDown() {
gcm_network_channel_->RemoveObserver(this);
}
// Helper functions to call private methods from test
GURL BuildUrl(const std::string& registration_id) {
return gcm_network_channel_->GCMNetworkChannel::BuildUrl(registration_id);
}
static void Base64EncodeURLSafe(const std::string& input,
std::string* output) {
GCMNetworkChannel::Base64EncodeURLSafe(input, output);
}
static bool Base64DecodeURLSafe(const std::string& input,
std::string* output) {
return GCMNetworkChannel::Base64DecodeURLSafe(input, output);
}
virtual void OnNetworkChannelStateChanged(
InvalidatorState invalidator_state) OVERRIDE {
last_invalidator_state_ = invalidator_state;
}
void OnIncomingMessage(std::string incoming_message) {
}
GCMNetworkChannel* network_channel() {
return gcm_network_channel_.get();
}
TestGCMNetworkChannelDelegate* delegate() {
return delegate_;
}
int url_fetchers_created_count() {
return url_fetchers_created_count_;
}
net::FakeURLFetcherFactory* url_fetcher_factory() {
return url_fetcher_factory_.get();
}
scoped_ptr<net::FakeURLFetcher> CreateURLFetcher(
const GURL& url,
net::URLFetcherDelegate* delegate,
const std::string& response_data,
net::HttpStatusCode response_code,
net::URLRequestStatus::Status status) {
++url_fetchers_created_count_;
return scoped_ptr<net::FakeURLFetcher>(new TestNetworkChannelURLFetcher(
this, url, delegate, response_data, response_code, status));
}
void set_last_echo_token(const std::string& echo_token) {
last_echo_token_ = echo_token;
}
const std::string& get_last_echo_token() {
return last_echo_token_;
}
InvalidatorState get_last_invalidator_state() {
return last_invalidator_state_;
}
void RunLoopUntilIdle() {
base::RunLoop run_loop;
run_loop.RunUntilIdle();
}
private:
base::MessageLoop message_loop_;
TestGCMNetworkChannelDelegate* delegate_;
scoped_ptr<GCMNetworkChannel> gcm_network_channel_;
scoped_refptr<net::TestURLRequestContextGetter> request_context_getter_;
scoped_ptr<net::FakeURLFetcherFactory> url_fetcher_factory_;
int url_fetchers_created_count_;
std::string last_echo_token_;
InvalidatorState last_invalidator_state_;
};
void TestNetworkChannelURLFetcher::AddExtraRequestHeader(
const std::string& header_line) {
net::FakeURLFetcher::AddExtraRequestHeader(header_line);
std::string header_name("echo-token: ");
std::string echo_token;
if (StartsWithASCII(header_line, header_name, false)) {
echo_token = header_line;
ReplaceFirstSubstringAfterOffset(
&echo_token, 0, header_name, std::string());
test_->set_last_echo_token(echo_token);
}
}
TEST_F(GCMNetworkChannelTest, HappyCase) {
EXPECT_EQ(TRANSIENT_INVALIDATION_ERROR, get_last_invalidator_state());
EXPECT_FALSE(delegate()->message_callback.is_null());
url_fetcher_factory()->SetFakeResponse(GURL("http://test.url.com"),
std::string(),
net::HTTP_NO_CONTENT,
net::URLRequestStatus::SUCCESS);
// After construction GCMNetworkChannel should have called Register.
EXPECT_FALSE(delegate()->register_callback.is_null());
// Return valid registration id.
delegate()->register_callback.Run("registration.id", gcm::GCMClient::SUCCESS);
network_channel()->SendMessage("abra.cadabra");
// SendMessage should have triggered RequestToken. No HTTP request should be
// started yet.
EXPECT_FALSE(delegate()->request_token_callback.is_null());
EXPECT_EQ(url_fetchers_created_count(), 0);
// Return valid access token. This should trigger HTTP request.
delegate()->request_token_callback.Run(
GoogleServiceAuthError::AuthErrorNone(), "access.token");
RunLoopUntilIdle();
EXPECT_EQ(url_fetchers_created_count(), 1);
// Return another access token. Message should be cleared by now and shouldn't
// be sent.
delegate()->request_token_callback.Run(
GoogleServiceAuthError::AuthErrorNone(), "access.token2");
RunLoopUntilIdle();
EXPECT_EQ(url_fetchers_created_count(), 1);
EXPECT_EQ(INVALIDATIONS_ENABLED, get_last_invalidator_state());
}
TEST_F(GCMNetworkChannelTest, FailedRegister) {
// After construction GCMNetworkChannel should have called Register.
EXPECT_FALSE(delegate()->register_callback.is_null());
EXPECT_EQ(1, delegate()->register_call_count_);
// Return transient error from Register call.
delegate()->register_callback.Run("", gcm::GCMClient::NETWORK_ERROR);
RunLoopUntilIdle();
// GcmNetworkChannel should have scheduled Register retry.
EXPECT_EQ(2, delegate()->register_call_count_);
// Return persistent error from Register call.
delegate()->register_callback.Run("", gcm::GCMClient::NOT_SIGNED_IN);
RunLoopUntilIdle();
// GcmNetworkChannel should give up trying.
EXPECT_EQ(2, delegate()->register_call_count_);
network_channel()->SendMessage("abra.cadabra");
// SendMessage shouldn't trigger RequestToken.
EXPECT_TRUE(delegate()->request_token_callback.is_null());
EXPECT_EQ(0, url_fetchers_created_count());
}
TEST_F(GCMNetworkChannelTest, RegisterFinishesAfterSendMessage) {
url_fetcher_factory()->SetFakeResponse(GURL("http://test.url.com"),
"",
net::HTTP_NO_CONTENT,
net::URLRequestStatus::SUCCESS);
// After construction GCMNetworkChannel should have called Register.
EXPECT_FALSE(delegate()->register_callback.is_null());
network_channel()->SendMessage("abra.cadabra");
// SendMessage shouldn't trigger RequestToken.
EXPECT_TRUE(delegate()->request_token_callback.is_null());
EXPECT_EQ(url_fetchers_created_count(), 0);
// Return valid registration id.
delegate()->register_callback.Run("registration.id", gcm::GCMClient::SUCCESS);
EXPECT_FALSE(delegate()->request_token_callback.is_null());
EXPECT_EQ(url_fetchers_created_count(), 0);
// Return valid access token. This should trigger HTTP request.
delegate()->request_token_callback.Run(
GoogleServiceAuthError::AuthErrorNone(), "access.token");
RunLoopUntilIdle();
EXPECT_EQ(url_fetchers_created_count(), 1);
}
TEST_F(GCMNetworkChannelTest, RequestTokenFailure) {
// After construction GCMNetworkChannel should have called Register.
EXPECT_FALSE(delegate()->register_callback.is_null());
// Return valid registration id.
delegate()->register_callback.Run("registration.id", gcm::GCMClient::SUCCESS);
network_channel()->SendMessage("abra.cadabra");
// SendMessage should have triggered RequestToken. No HTTP request should be
// started yet.
EXPECT_FALSE(delegate()->request_token_callback.is_null());
EXPECT_EQ(url_fetchers_created_count(), 0);
// RequestToken returns failure.
delegate()->request_token_callback.Run(
GoogleServiceAuthError::FromConnectionError(1), "");
// Should be no HTTP requests.
EXPECT_EQ(url_fetchers_created_count(), 0);
}
TEST_F(GCMNetworkChannelTest, AuthErrorFromServer) {
// Setup fake response to return AUTH_ERROR.
url_fetcher_factory()->SetFakeResponse(GURL("http://test.url.com"),
"",
net::HTTP_UNAUTHORIZED,
net::URLRequestStatus::SUCCESS);
// After construction GCMNetworkChannel should have called Register.
EXPECT_FALSE(delegate()->register_callback.is_null());
// Return valid registration id.
delegate()->register_callback.Run("registration.id", gcm::GCMClient::SUCCESS);
network_channel()->SendMessage("abra.cadabra");
// SendMessage should have triggered RequestToken. No HTTP request should be
// started yet.
EXPECT_FALSE(delegate()->request_token_callback.is_null());
EXPECT_EQ(url_fetchers_created_count(), 0);
// Return valid access token. This should trigger HTTP request.
delegate()->request_token_callback.Run(
GoogleServiceAuthError::AuthErrorNone(), "access.token");
RunLoopUntilIdle();
EXPECT_EQ(url_fetchers_created_count(), 1);
EXPECT_EQ(delegate()->invalidated_token, "access.token");
}
// Following two tests are to check for memory leaks/crashes when Register and
// RequestToken don't complete by the teardown.
TEST_F(GCMNetworkChannelTest, RegisterNeverCompletes) {
network_channel()->SendMessage("abra.cadabra");
// Register should be called by now. Let's not complete and see what happens.
EXPECT_FALSE(delegate()->register_callback.is_null());
}
TEST_F(GCMNetworkChannelTest, RequestTokenNeverCompletes) {
network_channel()->SendMessage("abra.cadabra");
// Return valid registration id.
delegate()->register_callback.Run("registration.id", gcm::GCMClient::SUCCESS);
// RequestToken should be called by now. Let's not complete and see what
// happens.
EXPECT_FALSE(delegate()->request_token_callback.is_null());
}
#if !defined(ANDROID)
TEST_F(GCMNetworkChannelTest, BuildUrl) {
GURL url = BuildUrl("registration.id");
EXPECT_TRUE(url.SchemeIsHTTPOrHTTPS());
EXPECT_FALSE(url.host().empty());
EXPECT_FALSE(url.path().empty());
std::vector<std::string> parts;
Tokenize(url.path(), "/", &parts);
std::string buffer;
EXPECT_TRUE(Base64DecodeURLSafe(parts[parts.size() - 1], &buffer));
}
#endif
TEST_F(GCMNetworkChannelTest, Base64EncodeDecode) {
std::string input;
std::string plain;
std::string base64;
// Empty string.
Base64EncodeURLSafe(input, &base64);
EXPECT_TRUE(base64.empty());
EXPECT_TRUE(Base64DecodeURLSafe(base64, &plain));
EXPECT_EQ(input, plain);
// String length: 1..7.
for (int length = 1; length < 8; length++) {
input = "abra.cadabra";
input.resize(length);
Base64EncodeURLSafe(input, &base64);
// Ensure no padding at the end.
EXPECT_NE(base64[base64.size() - 1], '=');
EXPECT_TRUE(Base64DecodeURLSafe(base64, &plain));
EXPECT_EQ(input, plain);
}
// Presence of '-', '_'.
input = "\xfb\xff";
Base64EncodeURLSafe(input, &base64);
EXPECT_EQ("-_8", base64);
EXPECT_TRUE(Base64DecodeURLSafe(base64, &plain));
EXPECT_EQ(input, plain);
}
TEST_F(GCMNetworkChannelTest, TransientError) {
EXPECT_FALSE(delegate()->message_callback.is_null());
// POST will fail.
url_fetcher_factory()->SetFakeResponse(GURL("http://test.url.com"),
std::string(),
net::HTTP_SERVICE_UNAVAILABLE,
net::URLRequestStatus::SUCCESS);
delegate()->register_callback.Run("registration.id", gcm::GCMClient::SUCCESS);
network_channel()->SendMessage("abra.cadabra");
EXPECT_FALSE(delegate()->request_token_callback.is_null());
delegate()->request_token_callback.Run(
GoogleServiceAuthError::AuthErrorNone(), "access.token");
RunLoopUntilIdle();
EXPECT_EQ(url_fetchers_created_count(), 1);
// Failing HTTP POST should cause TRANSIENT_INVALIDATION_ERROR.
EXPECT_EQ(TRANSIENT_INVALIDATION_ERROR, get_last_invalidator_state());
// Network change to CONNECTION_NONE shouldn't affect invalidator state.
network_channel()->OnNetworkChanged(
net::NetworkChangeNotifier::CONNECTION_NONE);
EXPECT_EQ(TRANSIENT_INVALIDATION_ERROR, get_last_invalidator_state());
// Network change to something else should trigger retry.
network_channel()->OnNetworkChanged(
net::NetworkChangeNotifier::CONNECTION_WIFI);
EXPECT_EQ(INVALIDATIONS_ENABLED, get_last_invalidator_state());
network_channel()->OnNetworkChanged(
net::NetworkChangeNotifier::CONNECTION_NONE);
EXPECT_EQ(INVALIDATIONS_ENABLED, get_last_invalidator_state());
}
#if !defined(ANDROID)
TEST_F(GCMNetworkChannelTest, EchoToken) {
url_fetcher_factory()->SetFakeResponse(GURL("http://test.url.com"),
std::string(),
net::HTTP_OK,
net::URLRequestStatus::SUCCESS);
// After construction GCMNetworkChannel should have called Register.
// Return valid registration id.
delegate()->register_callback.Run("registration.id", gcm::GCMClient::SUCCESS);
network_channel()->SendMessage("abra.cadabra");
// Return valid access token. This should trigger HTTP request.
delegate()->request_token_callback.Run(
GoogleServiceAuthError::AuthErrorNone(), "access.token");
RunLoopUntilIdle();
EXPECT_EQ(url_fetchers_created_count(), 1);
EXPECT_TRUE(get_last_echo_token().empty());
// Trigger response.
delegate()->message_callback.Run("abra.cadabra", "echo.token");
// Send another message.
network_channel()->SendMessage("abra.cadabra");
// Return valid access token. This should trigger HTTP request.
delegate()->request_token_callback.Run(
GoogleServiceAuthError::AuthErrorNone(), "access.token");
RunLoopUntilIdle();
EXPECT_EQ(url_fetchers_created_count(), 2);
EXPECT_EQ("echo.token", get_last_echo_token());
// Trigger response with empty echo token.
delegate()->message_callback.Run("abra.cadabra", "");
// Send another message.
network_channel()->SendMessage("abra.cadabra");
// Return valid access token. This should trigger HTTP request.
delegate()->request_token_callback.Run(
GoogleServiceAuthError::AuthErrorNone(), "access.token");
RunLoopUntilIdle();
EXPECT_EQ(url_fetchers_created_count(), 3);
// Echo_token should be from second message.
EXPECT_EQ("echo.token", get_last_echo_token());
}
#endif
} // namespace syncer
| bsd-3-clause |
parsers/php-parser | lib/PHPParser/Node/Expression/AssignMulExpression.php | 799 | <?php
namespace PHPParser\Node\Expression;
/**
* @property \PHPParser\Node\Expression\Expression $var Variable
* @property \PHPParser\Node\Expression\Expression $expr Expression
*/
class AssignMulExpression extends Expression
{
/**
* Constructs an assignment with multiplication node.
*
* @param \PHPParser\Node\Expression\Expression $var Variable
* @param \PHPParser\Node\Expression\Expression $expr Expression
* @param array $attributes Additional attributes
*/
public function __construct(Expression $var, Expression $expr, array $attributes = array()) {
parent::__construct(
array(
'var' => $var,
'expr' => $expr
),
$attributes
);
}
}
| bsd-3-clause |
shishkander/luci-go | common/logging/logging.go | 2923 | // Copyright 2015 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 logging defines Logger interface and context.Context helpers to put\get
logger from context.Context.
Unfortunately standard library doesn't define any Logger interface (only
struct). And even worse: GAE logger is exposing different set of methods. Some
additional layer is needed to unify the logging. Package logging is intended to
be used from packages that support both local and GAE environments. Such
packages should not use global logger but must accept instances of Logger
interface (or even more generally context.Context) as parameters. Then callers
can pass appropriate Logger implementation (or inject appropriate logger into
context.Context) depending on where the code is running.
Libraries under luci-go/common/ MUST use luci-go/common/logging instead of
directly instantiating concrete implementations.
*/
package logging
import (
"golang.org/x/net/context"
)
// Logger interface is ultimately implemented by underlying logging libraries
// (like go-logging or GAE logging). It is the least common denominator among
// logger implementations.
type Logger interface {
// Debugf formats its arguments according to the format, analogous to
// fmt.Printf and records the text as a log message at Debug level.
Debugf(format string, args ...interface{})
// Infof is like Debugf, but logs at Info level.
Infof(format string, args ...interface{})
// Warningf is like Debugf, but logs at Warning level.
Warningf(format string, args ...interface{})
// Errorf is like Debugf, but logs at Error level.
Errorf(format string, args ...interface{})
// LogCall is a generic logging function. This is oriented more towards
// utility functions than direct end-user usage.
LogCall(l Level, calldepth int, format string, args []interface{})
}
// Factory is a method that returns a Logger instance for the specified context.
type Factory func(context.Context) Logger
type key int
const (
loggerKey key = iota
fieldsKey
levelKey
)
// SetFactory sets the Logger factory for this context.
//
// The factory will be called each time Get(context) is used.
func SetFactory(c context.Context, f Factory) context.Context {
return context.WithValue(c, loggerKey, f)
}
// Set sets the logger for this context.
//
// It can be retrieved with Get(context).
func Set(c context.Context, l Logger) context.Context {
return SetFactory(c, func(context.Context) Logger { return l })
}
// GetFactory returns the currently-configured logging factory.
func GetFactory(c context.Context) Factory {
if f, ok := c.Value(loggerKey).(Factory); ok {
return f
}
return NullFactory
}
// Get the current Logger, or a logger that ignores all messages if none
// is defined.
func Get(c context.Context) (ret Logger) {
return GetFactory(c)(c)
}
| bsd-3-clause |
comilla/map | config/initializers/error_notifier.rb | 1155 | require 'rollbar/rails'
Rollbar.configure do |config|
config.access_token = Cartodb.config[:rollbar_api_key]
config.enabled = Rails.env.production? || Rails.env.staging?
# Add exception class names to the exception_level_filters hash to
# change the level that exception is reported at. Note that if an exception
# has already been reported and logged the level will need to be changed
# via the rollbar interface.
# Valid levels: 'critical', 'error', 'warning', 'info', 'debug', 'ignore'
# 'ignore' will cause the exception to not be reported at all.
config.exception_level_filters.merge!(
'ActionController::RoutingError' => 'ignore'
)
end
module CartoDB
def self.notify_exception(e, extra={})
user = extra.delete(:user)
request = extra.delete(:request)
Rollbar.report_exception(e, request, user)
rescue
# If Rollbar fails, bubble up the exception
raise e
end
def self.notify_error(message, additional_data={})
Rollbar.report_message(message, 'error', additional_data)
end
def self.notify_warning_exception(exception)
Rollbar.report_exception(exception, nil, nil, 'warning')
end
end
| bsd-3-clause |
ericdill/databroker | databroker/assets/core.py | 12168 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from jsonschema import validate as js_validate
import warnings
import uuid
import time as ttime
import pandas as pd
from ..utils import sanitize_np, apply_to_dict_recursively
class DatumNotFound(Exception):
"""
Raised if a Datum id is not found.
"""
def __init__(self, datum_id, msg=None, *args):
if msg is None:
msg = f"No datum found with datum id {datum_id}"
super().__init__(msg, *args)
self.datum_id = datum_id
class EventDatumNotFound(Exception):
"""
Raised if an Event document is found to have an unknown Datum id.
"""
def __init__(self, event_uid, datum_id, msg=None, *args):
if msg is None:
msg = (
f"Event with uid {event_uid} references "
f"unknown Datum with datum id {datum_id}"
)
super().__init__(msg, *args)
self.event_uid = event_uid
self.datum_id = datum_id
def doc_or_uid_to_uid(doc_or_uid):
"""Given Document or uid return the uid
Parameters
----------
doc_or_uid : dict or str
If str, then assume uid and pass through, if not, return
the 'uid' field
Returns
-------
uid : str
A string version of the uid of the given document
"""
if not isinstance(doc_or_uid, six.string_types):
doc_or_uid = doc_or_uid['uid']
return doc_or_uid
def _get_datum_from_datum_id(col, datum_id, datum_cache, logger):
try:
datum = datum_cache[datum_id]
except KeyError:
# find the current document
edoc = col.find_one({'datum_id': datum_id})
if edoc is None:
raise DatumNotFound(datum_id=datum_id)
# save it for later
datum = dict(edoc)
res = edoc['resource']
count = 0
for dd in col.find({'resource': res}):
count += 1
d_id = dd['datum_id']
if d_id not in datum_cache:
datum_cache[d_id] = dict(dd)
if count > datum_cache.max_size:
logger.warn("More datum in a resource than your "
"datum cache can hold.")
datum.pop('_id', None)
return datum
def retrieve(col, datum_id, datum_cache, get_spec_handler, logger):
datum = _get_datum_from_datum_id(col, datum_id, datum_cache, logger)
handler = get_spec_handler(datum['resource'])
return handler(**datum['datum_kwargs'])
def resource_given_datum_id(col, datum_id, datum_cache, logger):
datum_id = doc_or_uid_to_uid(datum_id)
datum = _get_datum_from_datum_id(col, datum_id, datum_cache, logger)
res = datum['resource']
return res
def resource_given_uid(col, resource):
uid = doc_or_uid_to_uid(resource)
ret = col.find_one({'uid': uid})
ret.pop('_id', None)
ret['id'] = ret['uid']
return ret
def bulk_insert_datum(col, resource, datum_ids,
datum_kwarg_list):
resource_id = doc_or_uid_to_uid(resource)
def datum_factory():
for d_id, d_kwargs in zip(datum_ids, datum_kwarg_list):
datum = dict(resource=resource_id,
datum_id=str(d_id),
datum_kwargs=dict(d_kwargs))
apply_to_dict_recursively(datum, sanitize_np)
yield datum
col.insert(datum_factory())
def bulk_register_datum_table(datum_col,
resource_uid,
dkwargs_table,
validate):
if validate:
raise
d_ids = [str(uuid.uuid4()) for j in range(len(dkwargs_table))]
dkwargs_table = pd.DataFrame(dkwargs_table)
bulk_insert_datum(datum_col, resource_uid, d_ids, [
dict(r) for _, r in dkwargs_table.iterrows()])
return d_ids
def register_datum(col, resource_uid, datum_kwargs):
datum_uid = str(uuid.uuid4())
datum = insert_datum(col, resource_uid, datum_uid, datum_kwargs, {}, None)
return datum['datum_id']
def insert_datum(col, resource, datum_id, datum_kwargs, known_spec,
resource_col, ignore_duplicate_error=False,
duplicate_exc=None):
if ignore_duplicate_error:
assert duplicate_exc is not None
if duplicate_exc is None:
class _PrivateException(Exception):
pass
duplicate_exc = _PrivateException
try:
resource['spec']
spec = resource['spec']
if spec in known_spec:
js_validate(datum_kwargs, known_spec[spec]['datum'])
except (AttributeError, TypeError):
pass
resource_uid = doc_or_uid_to_uid(resource)
datum = dict(resource=resource_uid,
datum_id=str(datum_id),
datum_kwargs=dict(datum_kwargs))
apply_to_dict_recursively(datum, sanitize_np)
# We are transitioning from ophyd objects inserting directly into a
# Registry to ophyd objects passing documents to the RunEngine which in
# turn inserts them into a Registry. During the transition period, we allow
# an ophyd object to attempt BOTH so that configuration files are
# compatible with both the new model and the old model. Thus, we need to
# ignore the second attempt to insert.
try:
col.insert_one(datum)
except duplicate_exc:
if ignore_duplicate_error:
warnings.warn("Ignoring attempt to insert Resource with duplicate "
"uid, assuming that both ophyd and bluesky "
"attempted to insert this document. Remove the "
"Registry (`reg` parameter) from your ophyd "
"instance to remove this warning.")
else:
raise
# do not leak mongo objectID
datum.pop('_id', None)
return datum
def insert_resource(col, spec, resource_path, resource_kwargs,
known_spec, root, path_semantics='posix', uid=None,
run_start=None, id=None,
ignore_duplicate_error=False, duplicate_exc=None):
"""Insert resource into a databroker.
Parameters
----------
col : pymongo.Collection instance
Collection to insert data into
spec : str
The resource data spec
resource_path : str
The path to the resource files
resource_kwargs : dict
The kwargs for the resource
known_spec : set
The known specs
root : str
The root of the file path
path_semantics : str, optional
The name of the path semantics, e.g. ``posix`` for Linux systems
uid : str, optional
The unique ID for the resource
run_start : str, optional
The unique ID for the start document the resource is associated with
id : str, optional
Dummy variable so that we round trip resources, same as ``uid``
Returns
-------
resource_object : dict
The resource
"""
if ignore_duplicate_error:
assert duplicate_exc is not None
if duplicate_exc is None:
class _PrivateException(Exception):
pass
duplicate_exc = _PrivateException
resource_kwargs = dict(resource_kwargs)
if spec in known_spec:
js_validate(resource_kwargs, known_spec[spec]['resource'])
if uid is None:
uid = str(uuid.uuid4())
resource_object = dict(spec=str(spec),
resource_path=str(resource_path),
root=str(root),
resource_kwargs=resource_kwargs,
path_semantics=path_semantics,
uid=uid)
# This is special-cased because it was added later.
# Someday this may be required and no longer special-cased.
if run_start is not None:
resource_object['run_start'] = run_start
# We are transitioning from ophyd objects inserting directly into a
# Registry to ophyd objects passing documents to the RunEngine which in
# turn inserts them into a Registry. During the transition period, we allow
# an ophyd object to attempt BOTH so that configuration files are
# compatible with both the new model and the old model. Thus, we need to
# ignore the second attempt to insert.
try:
col.insert_one(resource_object)
except duplicate_exc:
if ignore_duplicate_error:
warnings.warn("Ignoring attempt to insert Datum with duplicate "
"datum_id, assuming that both ophyd and bluesky "
"attempted to insert this document. Remove the "
"Registry (`reg` parameter) from your ophyd "
"instance to remove this warning.")
else:
raise
resource_object['id'] = resource_object['uid']
resource_object.pop('_id', None)
return resource_object
def update_resource(update_col, resource_col, old, new, cmd, cmd_kwargs):
'''Update a resource document
Parameters
----------
update_col : Collection
The collection to record audit trail in
resource_col : Collection
The resource collection
old : dict
The old resource document
new : dict
The new resource document
cmd : str
The name of the operation which generated this update
cmd_kwargs : dict
The arguments that went into the update (excluding the resource id)
Returns
-------
ret : dict
The new resource document
log_object : dict
The history object inserted (with oid removed)
'''
if old['uid'] != new['uid']:
raise RuntimeError('must not change the resource uid')
uid = old['uid']
log_object = {'resource': uid,
'old': old,
'new': new,
'time': ttime.time(),
'cmd': cmd,
'cmd_kwargs': cmd_kwargs}
update_col.insert_one(log_object)
result = resource_col.replace_one({'uid': uid}, new)
ret = resource_given_uid(resource_col, uid)
# TODO look inside of result
del result
log_object.pop('_id', None)
return ret, log_object
def get_resource_history(col, resource):
uid = doc_or_uid_to_uid(resource)
cursor = col.find({'resource': uid})
for doc in cursor:
for k in ['new', 'old']:
d = doc[k]
d.pop('_id', None)
d['id'] = d['uid']
doc[k] = d
doc.pop('_id', None)
yield doc
def get_datumkw_by_resuid_gen(datum_col, resource_uid):
'''Given a resource uid, get all datum_kwargs
No order is guaranteed.
Internally the result of this is passed to the `get_file_list` method
of the handler object in `change_root`
Parameters
----------
datum_col : Collection
The Datum collection
resource_uid : dict or str
The resource to work on
Yields
------
datum_kwarg : dict
'''
resource_uid = doc_or_uid_to_uid(resource_uid)
cur = datum_col.find({'resource': resource_uid})
for d in cur:
yield d['datum_kwargs']
def get_datum_by_res_gen(datum_col, resource_uid):
'''Given a resource uid, get all datums
No order is guaranteed.
Internally the result of this is passed to the `get_file_list` method
of the handler object in `change_root`
Parameters
----------
datum_col : Collection
The Datum collection
resource_uid : dict or str
The resource to work on
Yields
------
datum : dict
'''
resource_uid = doc_or_uid_to_uid(resource_uid)
cur = datum_col.find({'resource': resource_uid})
for d in cur:
yield d
def get_file_list(resource, datum_kwarg_gen, get_spec_handler):
"""
Given a resource and an iterable of datum kwargs, get a list of
associated files.
DO NOT USE FOR COPYING OR MOVING. This is for debugging only.
See the methods for moving and copying on the Registry object.
"""
handler = get_spec_handler(resource['uid'])
return handler.get_file_list(datum_kwarg_gen)
| bsd-3-clause |
datafolklabs/cement | tests/utils/test_fs.py | 2007 |
import os
from pytest import raises
from cement.utils import fs
def test_abspath(tmp):
path = fs.abspath('.')
assert path.startswith('/')
def test_join(tmp, rando):
full_path = os.path.abspath(os.path.join(tmp.dir, rando))
assert fs.join(tmp.dir, rando) == full_path
def test_join_exists(tmp, rando):
full_path = os.path.abspath(os.path.join(tmp.dir, rando))
res = fs.join_exists(tmp.dir, rando)
assert res[0] == full_path
assert res[1] is False
with open(full_path, 'w') as f:
f.write('data')
res = fs.join_exists(tmp.dir, rando)
assert res[1] is True
def test_ensure_dir_exists(tmp, rando):
fs.ensure_dir_exists(fs.join(tmp.dir, rando))
assert os.path.exists(fs.join(tmp.dir, rando))
with raises(AssertionError, match='(.*)exists but is not a directory(.*)'):
fs.ensure_dir_exists(tmp.file)
def test_ensure_parent_dir_exists(tmp, rando):
fs.ensure_parent_dir_exists(fs.join(tmp.dir, 'parent', rando))
assert os.path.exists(fs.join(tmp.dir, 'parent'))
def test_tmp(tmp, rando):
t1 = fs.Tmp()
assert os.path.exists(t1.dir)
assert os.path.exists(t1.file)
with fs.Tmp() as t2:
pass
assert not os.path.exists(t2.dir)
assert not os.path.exists(t2.file)
def test_backup(tmp):
bkfile = fs.backup(tmp.file)
assert "%s.bak" % os.path.basename(tmp.file) == os.path.basename(bkfile)
bkfile = fs.backup(tmp.file)
assert "%s.bak.0" % os.path.basename(tmp.file) == os.path.basename(bkfile)
bkfile = fs.backup(tmp.file)
assert "%s.bak.1" % os.path.basename(tmp.file) == os.path.basename(bkfile)
bkdir = fs.backup(tmp.dir)
assert "%s.bak" % os.path.basename(tmp.dir) == os.path.basename(bkdir)
assert fs.backup('someboguspath') is None
def test_backup_dir_trailing_slash(tmp):
# https://github.com/datafolklabs/cement/issues/610
bkdir = fs.backup("%s/" % tmp.dir)
assert "%s.bak" % os.path.basename(tmp.dir) == os.path.basename(bkdir)
| bsd-3-clause |
darug/dds-yii | protected/views/felvilagosit/_view.php | 503 | <?php
/* @var $this FelvilagositController */
/* @var $data Felvilagosit */
$bUrl=Yii::app()->request->baseUrl;
?>
<div class="view">
<fieldset>
<legend align="center" ><?php echo CHtml::encode($data->title); ?></legend>
<br />
<a href="<?php if(strpos($data->link,'://')){ echo $data->link;} else {echo $bUrl.$data->link;} ?>">
<?php echo $data->rovid; ?>
</a>
<br />
<a class="more" href="#">Bővebben</a>
<div class="long_text"><?php echo $data->hosszu; ?></div>
</fieldset>
</div> | bsd-3-clause |
smartdevicelink/sdl_atf_test_scripts | test_scripts/MobileProjection/Phase1/001_Start_video_audio_service.lua | 1711 | ---------------------------------------------------------------------------------------------------
-- User story: TBD
-- Use case: TBD
--
-- Requirement summary:
-- TBD
--
-- Description:
-- In case:
-- 1) Application is registered with PROJECTION appHMIType
-- 2) and starts video and audio services
-- SDL must:
-- 1) Start services successful
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local common = require('test_scripts/MobileProjection/Phase1/common')
local runner = require('user_modules/script_runner')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local appHMIType = "PROJECTION"
--[[ General configuration parameters ]]
config.application1.registerAppInterfaceParams.appHMIType = { appHMIType }
--[[ Local Functions ]]
local function ptUpdate(pTbl)
pTbl.policy_table.app_policies[common.getConfigAppParams().fullAppID].AppHMIType = { appHMIType }
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App", common.registerApp)
runner.Step("PolicyTableUpdate with HMI types", common.policyTableUpdate, { ptUpdate })
runner.Step("Activate App", common.activateApp)
runner.Title("Test")
runner.Step("Start video service", common.startService, { 11 })
runner.Step("Start audio service", common.startService, { 10 })
runner.Title("Postconditions")
runner.Step("Stop service", common.StopService, { 10 })
runner.Step("Stop service", common.StopService, { 11 })
runner.Step("Stop SDL", common.postconditions)
| bsd-3-clause |
glogiotatidis/mozillians-new | media/js/infinite.js | 1388 | (function($) {
'use strict';
$().ready(function() {
var paginator = $('.pagination');
var results = $('#final-result')
var pages = paginator.attr('data-pages');
// Variable to keep track of whether we've reached our max page
var cease;
paginator.hide();
results.hide();
// If there is no paginator, don't do any scrolling
cease = (pages == undefined)
$(document).endlessScroll({
// Number of pixels from the bottom at which callback is triggered
bottomPixels: 750,
// Wait a second before we even think of loading more content
fireDelay: 1000,
fireOnce: true,
ceaseFire: function() {
return cease;
},
callback: function(i) {
cease = (pages <= i);
if (cease) {
// Show the user that we have stopped scrolling on purpose.
results.show()
} else {
$.ajax({
data:{'page': i + 1},
dataType: 'html',
success: function(data) {
paginator.before($(data));
}
});
}
}
});
});
})(jQuery);
| bsd-3-clause |
NUBIC/psc-mirror | core/src/main/java/edu/northwestern/bioinformatics/studycalendar/xml/writers/PreviousScheduledActivityStateXmlSerializer.java | 481 | package edu.northwestern.bioinformatics.studycalendar.xml.writers;
import edu.northwestern.bioinformatics.studycalendar.xml.XsdElement;
import static edu.northwestern.bioinformatics.studycalendar.xml.XsdElement.PREVIOUS_SCHEDULED_ACTIVITY_STATE;
/**
* @author John Dzak
*/
public class PreviousScheduledActivityStateXmlSerializer extends AbstractScheduledActivityStateXmlSerializer {
@Override protected XsdElement element() { return PREVIOUS_SCHEDULED_ACTIVITY_STATE; }
}
| bsd-3-clause |
atheken/NoRM | NoRM/Commands/Qualifiers/InQualifier.cs | 538 | using Norm.BSON;
namespace Norm.Commands.Qualifiers
{
/// <summary>
/// The in qualifier.
/// </summary>
/// <typeparam retval="T">In type to qualify</typeparam>
public class InQualifier<T> : QualifierCommand
{
/// <summary>
/// Initializes a new instance of the <see cref="InQualifier{T}"/> class.
/// </summary>
/// <param retval="inset">
/// The inset.
/// </param>
public InQualifier(params T[] inset) : base("$in", inset)
{
}
}
} | bsd-3-clause |