repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
|---|---|---|---|---|
fgvieira/ngsF-HMM
|
README.md
|
5771
|
# ngsF-HMM
`ngsF-HMM` is a program to estimate per-individual inbreeding tracts using a two-state Hidden Markov Model (HMM). Furthermore, instead of using called genotypes, it uses a probabilistic framework that takes the uncertainty of genotype's assignation into account; making it specially suited for low-quality or low-coverage datasets.
### Citation
`ngsF-HMM` was published in 2016 at [Bioinformatics](http://bioinformatics.oxfordjournals.org/content/32/14/2096), so please cite it if you use it in your work:
Vieira FG, Albrechtsen A and Nielsen R
Estimating IBD tracts from low coverage NGS data
Bioinformatics (2016) 32: 2096-2102
### Installation
`ngsF-HMM` can be easily installed but has some external dependencies:
* Mandatory:
* `gcc`: >= 4.9.2 tested on Debian 7.8 (wheezy)
* `zlib`: v1.2.7 tested on Debian 7.8 (wheezy)
* `gsl` : v1.15 tested on Debian 7.8 (wheezy)
* Optional (only needed for testing or auxilliary scripts):
* `md5sum`
* `Perl` packages: `Getopt::Long`, and `IO::Zlib`
* `R` packages: `optparse`, and `plyr`
To install the entire package just download the source code:
% git clone https://github.com/fgvieira/ngsF-HMM.git
and run:
% cd ngsF-HMM
% make
To run the tests (only if installed through [ngsTools](https://github.com/mfumagalli/ngsTools)):
% make test
Executables are built into the main directory. If you wish to clean all binaries and intermediate files:
% make clean
### Usage
% ./ngsF-HMM [options] --n_ind INT --n_sites INT --glf glf/in/file --out output/file
#### Parameters
* `--geno FILE`: input file with genotypes, genotype likelihoods or genotype posterior probabilities.
* `--pos` FILE: input file with site coordinates (one per line), where the 1st column stands for the chromosome/contig and the 2nd for the position (bp); remaining columns are ignored.
* `--lkl`: input are genotype likelihoods (BEAGLE format).
* `--loglkl`: input are genotype log-likelihoods.
* `--n_ind INT`: sample size (number of individuals).
* `--n_sites INT`: total number of sites.
* `--call_geno`: call genotypes before running analyses.
* `--freqs DOUBLE or CHAR`: initial frequency values. Can be defined by user as a DOUBLE, (r)andom, (e)stimated or read from a FILE.
* `--freqs_est INT`: allele frequency estimation method: 0) fixed (no optimizatopn); 1) assuming independence of sites; and 2) through haplotype frequency.
* `--indF DOUBLE-DOUBLE or CHAR`: initial inbreeding and transition parameter values. Can be defined by user as a DOUBLE-DOUBLE, (r)andom, or read from a FILE.
* `--indF_fixed`: inbreeding parameter values are fixed (will not be optimized).
* `--alpha_fixed`: transition parameter values are fixed (will not be optimized).
* `--out CHAR`: prefix for output files.
* `--log INT`: dump LOG file each INT iterations. [0]
* `--log_bin`: dump LOG file in binary.
* `--min_iters INT`: minimum number of EM iterations. [10]
* `--max_iters INT`: maximum number of EM iterations. [100]
* `--min_epsilon FLOAT`: maximum RMSD between iterations to assume convergence. [1e-5]
* `--n_threads INT`: number of threads to use. [1]
* `--verbose INT`: selects verbosity level. [1]
* `--seed INT`: seed for random number generator.
### Input data
As input, `ngsF-HMM` accepts both genotypes, genotype likelihoods (GP) or genotype posterior probabilities (GP). Genotypes must be input as gziped TSV with one row per site and one column per individual  and genotypes coded as [-1, 0, 1, 2]. The file can have a header and an arbitrary number of columns preceeding the actual data (that will all be ignored), much like the Beagle file format ([link](http://faculty.washington.edu/browning/beagle/beagle.html)).
As for GL and GP, `ngsF-HMM` accepts both gzipd TSV and binary formats, but with 3 columns per individual  and, in the case of binary, the GL/GP coded as doubles.
### Stopping Criteria
An issue on iterative algorithms is the stopping criteria. `ngsF-HMM` implements a dual condition threshold: relative difference in log-likelihood and estimates RMSD (F and freq). As for which threshold to use, simulations show that 1e-5 seems to be a reasonable value. However, if you're dealing with low coverage data (2x-3x), it might be worth to use lower thresholds (between 1e-6 and 1e-9).
To avoid convergence to local maxima, ngsF-HMM should be run several times from different starting points. To make this task easier, a script (`ngsF-HMM.sh`) is provided that can be called with the exact same parameters as `ngsF-HMM`.
### Output files
`ngsF-HMM` will output several files, some depending on input options:
* `.indF`: file similar to [ngsF](https://github.com/fgvieira/ngsF) output format, where the first line stands for the final log-likelihood, followed by per individual (one per line) inbreeding coefficients (1st column) and transition rate parameters (2nd column) and, finally, the per-site minor allele frequency.
* `.ibd`: file storing IBD tracts results, where first line stands for the per-individual final log-likelihood, followed by per individual (one per line) most-probable inbreeding tracts (0: position is not IBD; 1: position is IBD), and IBD posterior probabilities.
* `.geno`: binary file with genotype posterior probabilities (similar to ANGSD `-doGeno 32`).
* `.log.gz`: if option `-log INT` is specified, a gziped log file similar to `.ibd` is printed every `INT` iterations.
* `.pdf`: optionally, the `scripts/ngsF-HMMplot.R` script can be used to plot the IBD tracts.
### Thread pool
The thread pool implementation was adapted from Mathias Brossard's and is freely available from:
https://github.com/mbrossard/threadpool
|
gpl-3.0
|
jeremiah-c-leary/vhdl-style-guide
|
vsg/tests/process/test_rule_035.py
|
2131
|
import os
import unittest
from vsg.rules import process
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_035_test_input.vhd'))
lExpected = []
lExpected.append('')
utils.read_file(os.path.join(sTestDir, 'rule_035_test_input.fixed.vhd'), lExpected)
lExpectedCompactAlignmentFalse = []
lExpectedCompactAlignmentFalse.append('')
utils.read_file(os.path.join(sTestDir, 'rule_035_test_input.fixed_compact_alignment_false.vhd'), lExpectedCompactAlignmentFalse)
class test_process_rule(unittest.TestCase):
def setUp(self):
self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
def test_rule_035(self):
oRule = process.rule_035()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'process')
self.assertEqual(oRule.identifier, '035')
lExpected = [30, 31, 35, 38]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
def test_fix_rule_035(self):
oRule = process.rule_035()
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpected, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
def test_rule_035_compact_alignment_false(self):
oRule = process.rule_035()
oRule.compact_alignment = False
oRule.include_lines_without_comments = False
lExpected = [30, 31, 38]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
def test_fix_rule_035_compact_alignment_false(self):
oRule = process.rule_035()
oRule.compact_alignment = False
oRule.include_lines_without_comments = False
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpectedCompactAlignmentFalse, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
|
gpl-3.0
|
00-Evan/shattered-pixel-dungeon
|
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/Skeleton.java
|
3174
|
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2021 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.actors.mobs;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.items.Generator;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.levels.features.Chasm;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.sprites.SkeletonSprite;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.watabou.noosa.audio.Sample;
import com.watabou.utils.PathFinder;
import com.watabou.utils.Random;
public class Skeleton extends Mob {
{
spriteClass = SkeletonSprite.class;
HP = HT = 25;
defenseSkill = 9;
EXP = 5;
maxLvl = 10;
loot = Generator.Category.WEAPON;
lootChance = 0.1667f; //by default, see rollToDropLoot()
properties.add(Property.UNDEAD);
properties.add(Property.INORGANIC);
}
@Override
public int damageRoll() {
return Random.NormalIntRange( 2, 10 );
}
@Override
public void die( Object cause ) {
super.die( cause );
if (cause == Chasm.class) return;
boolean heroKilled = false;
for (int i = 0; i < PathFinder.NEIGHBOURS8.length; i++) {
Char ch = findChar( pos + PathFinder.NEIGHBOURS8[i] );
if (ch != null && ch.isAlive()) {
int damage = Random.NormalIntRange(6, 12);
damage = Math.max( 0, damage - (ch.drRoll() + ch.drRoll()) );
ch.damage( damage, this );
if (ch == Dungeon.hero && !ch.isAlive()) {
heroKilled = true;
}
}
}
if (Dungeon.level.heroFOV[pos]) {
Sample.INSTANCE.play( Assets.Sounds.BONES );
}
if (heroKilled) {
Dungeon.fail( getClass() );
GLog.n( Messages.get(this, "explo_kill") );
}
}
@Override
public void rollToDropLoot() {
//each drop makes future drops 1/2 as likely
// so loot chance looks like: 1/6, 1/12, 1/24, 1/48, etc.
lootChance *= Math.pow(1/2f, Dungeon.LimitedDrops.SKELE_WEP.count);
super.rollToDropLoot();
}
@Override
protected Item createLoot() {
Dungeon.LimitedDrops.SKELE_WEP.count++;
return super.createLoot();
}
@Override
public int attackSkill( Char target ) {
return 12;
}
@Override
public int drRoll() {
return Random.NormalIntRange(0, 5);
}
}
|
gpl-3.0
|
piyus/btkernel
|
btmod/bt/peep/peeptab.h
|
720
|
#ifndef PEEP_PEEPTAB_H
#define PEEP_PEEPTAB_H
#define MAX_IN_LEN 1
#define MAX_OUT_LEN 10
#define MAX_CONSTANTS 24
#define MAX_NOMATCH_PAIRS 32
#include <lib/hash.h>
#include "peep/insntypes.h"
#include "peep/cpu_constraints.h"
#include "peep/nomatch_pair.h"
typedef struct peep_entry_t
{
int n_tmpl;
insn_t tmpl[MAX_IN_LEN]; /* input template. */
int label;
unsigned n_temporaries;
tag_t temporaries[MAX_TEMPORARIES];
cpu_constraints_t cpu_constraints;
int num_nomatch_pairs;
struct nomatch_pair_t nomatch_pairs[MAX_NOMATCH_PAIRS];
char const *name; /* for debugging purposes. */
/* hash_elem for peep_tab. */
struct hash_elem peeptab_elem;
} peep_entry_t;
#endif
|
gpl-3.0
|
alcexhim/Sydne
|
PrivateWebsite/Include/Configuration.inc.php
|
604
|
<?php
use Phast\System;
System::$Configuration["Database.ServerName"] = "localhost";
System::$Configuration["Database.UserName"] = "Sydne_Sullen";
System::$Configuration["Database.Password"] = "Hb+z.p)iF/}P.*aoIW6efA2.#";
System::$Configuration["Database.DatabaseName"] = "Sydne_SullenStudio";
System::$Configuration["Database.TablePrefix"] = "";
System::$Configuration["Application.BasePath"] = "http://sydne.sullen-studio.com";
System::$Configuration["WebFramework.StaticPath"] = "http://static.alcehosting.net";
System::$Configuration["Company.Title"] = "Sullen Studio";
?>
|
gpl-3.0
|
NetRevolutions/SICOTYC
|
SICOTYC/UI/src/app/sicotyc/operaciones/operaciones.component.ts
|
297
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'operaciones',
templateUrl: './operaciones.component.html',
styleUrls: ['./operaciones.component.css']
})
export class OperacionesComponent implements OnInit {
constructor() { }
ngOnInit(): void { }
}
|
gpl-3.0
|
fangxinmiao/projects
|
Architeture/Embedded/SoC/ST/STM32/utils/stm32flash/README.md
|
1476
|
# stm32flash - Linux下的STM32串口下载工具
在Windows上,STM32的下载工具很多,官方自己也提供了下载工具。在Linux上,我自己觉得stm32flash非常不错。
[stm32flash](https://sourceforge.net/projects/stm32flash/)是一款开源的stm32固件串口下载工具。
stm32flash - Open source cross platform flash program for the STM32 ARM microcontrollers
using the built-in ST serial bootloader over UART or I2C。
## Features
- UART and I2C transports supported
- device identification
- write to flash/ram
- read from flash/ram
- auto-detect Intel HEX or raw binary input format with option to force binary
- flash from binary file
- save flash to binary file
- verify & retry up to N times on failed writes
- start execution at specified address
- software reset the device when finished if -R is specified
- resume already initialized connection (for when reset fails, UART only)
- GPIO signalling to enter bootloader mode (hardware dependent)
## 安装
通过源码编译方式安装:
$ tar -xf stm32flash-0.5.tar.gz
$ cd stm32flash
$ make
$ sudo cp stm32flash /usr/sbin
Ubuntu-16.04支持通过包管理器直接安装:
$ sudo apt install stm32flash
## 简单使用
下面的命令通过`/dev/ttyUSB0`串口(波特率`115200`)将名为`led.hex`的16进制文件写入到flash的起始位置(`0x0`):
$ sudo stm32flash /dev/ttyUSB0 -b 115200 -v -g 0x0 -w led.hex
|
gpl-3.0
|
newmediamedicine/indivo_server_1_0
|
indivo/models/fact_objects/videomessage.py
|
489
|
"""
Indivo Model for VideoMessage
"""
from fact import Fact
from django.db import models
from django.conf import settings
class VideoMessage(Fact):
file_id=models.CharField(max_length=200)
storage_type=models.CharField(max_length=200)
subject=models.CharField(max_length=200)
from_str=models.CharField(max_length=200)
date_recorded=models.DateTimeField(null=True)
date_sent=models.DateTimeField(null=True)
def __unicode__(self):
return 'VideoMessage %s' % self.id
|
gpl-3.0
|
RalfBarkow/Zettelkasten
|
src/main/java/de/danielluedecke/zettelkasten/database/Result.java
|
345
|
package de.danielluedecke.zettelkasten.database;
public class Result {
Document[] collection = new Document[0];
public Result() {}
public Result(Document[]collection) {
this.collection = collection;
}
public int getCount() {return collection.length;}
public Document getItem(int i) {return collection[i];}
}
|
gpl-3.0
|
DMJC/mg2modeller-
|
doc/latex/classnurbs__cube.tex
|
717
|
\hypertarget{classnurbs__cube}{}\section{nurbs\+\_\+cube Class Reference}
\label{classnurbs__cube}\index{nurbs\+\_\+cube@{nurbs\+\_\+cube}}
Inheritance diagram for nurbs\+\_\+cube\+:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=150pt]{classnurbs__cube__inherit__graph}
\end{center}
\end{figure}
Collaboration diagram for nurbs\+\_\+cube\+:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=191pt]{classnurbs__cube__coll__graph}
\end{center}
\end{figure}
\subsection*{Additional Inherited Members}
The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
include/nurbs.\+h\end{DoxyCompactItemize}
|
gpl-3.0
|
tudor3084/percent2
|
app/controllers/home_controller.rb
|
95
|
class HomeController < ApplicationController
def index
end
def nice
end
end
|
gpl-3.0
|
rodrigolucianocosta/ControleEstoque
|
rOne/Storage101/django-localflavor/django-localflavor-1.3/docs/_build/html/_modules/localflavor/tn/forms.html
|
5525
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>localflavor.tn.forms — django-localflavor 1.2 documentation</title>
<link rel="stylesheet" href="../../../_static/classic.css" type="text/css" />
<link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../../../',
VERSION: '1.2',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../../../_static/jquery.js"></script>
<script type="text/javascript" src="../../../_static/underscore.js"></script>
<script type="text/javascript" src="../../../_static/doctools.js"></script>
<link rel="top" title="django-localflavor 1.2 documentation" href="../../../index.html" />
<link rel="up" title="Module code" href="../../index.html" />
</head>
<body role="document">
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../../../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="nav-item nav-item-0"><a href="../../../index.html">django-localflavor 1.2 documentation</a> »</li>
<li class="nav-item nav-item-1"><a href="../../index.html" accesskey="U">Module code</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<h1>Source code for localflavor.tn.forms</h1><div class="highlight"><pre>
<span></span><span class="c1"># -*- coding: utf-8 -*-</span>
<span class="sd">"""</span>
<span class="sd">Tunisia-specific Form helpers.</span>
<span class="sd">"""</span>
<span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">unicode_literals</span>
<span class="kn">from</span> <span class="nn">django.forms.fields</span> <span class="kn">import</span> <span class="n">Select</span>
<span class="kn">from</span> <span class="nn">.tn_governorates</span> <span class="kn">import</span> <span class="n">GOVERNORATE_CHOICES</span>
<div class="viewcode-block" id="TNGovernorateSelect"><a class="viewcode-back" href="../../../localflavor/tn.html#localflavor.tn.forms.TNGovernorateSelect">[docs]</a><span class="k">class</span> <span class="nc">TNGovernorateSelect</span><span class="p">(</span><span class="n">Select</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> A Select widget that uses a list of the Tunisian governorates as its</span>
<span class="sd"> choices.</span>
<span class="sd"> """</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">attrs</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
<span class="nb">super</span><span class="p">(</span><span class="n">TNGovernorateSelect</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span>
<span class="n">attrs</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="n">GOVERNORATE_CHOICES</span>
<span class="p">)</span></div>
</pre></div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="../../../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="../../../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="nav-item nav-item-0"><a href="../../../index.html">django-localflavor 1.2 documentation</a> »</li>
<li class="nav-item nav-item-1"><a href="../../index.html" >Module code</a> »</li>
</ul>
</div>
<div class="footer" role="contentinfo">
© Copyright Django Software Foundation and individual contributors.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.4.1.
</div>
</body>
</html>
|
gpl-3.0
|
elebow/otter
|
src/ui/toolbars/BookmarkWidget.cpp
|
4719
|
/**************************************************************************
* Otter Browser: Web browser controlled by the user, not vice-versa.
* Copyright (C) 2015 - 2016 Michal Dutkiewicz aka Emdek <michal@emdek.pl>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
**************************************************************************/
#include "BookmarkWidget.h"
#include "../MainWindow.h"
#include "../Menu.h"
#include "../../core/BookmarksManager.h"
#include "../../core/Utils.h"
#include "../../core/WindowsManager.h"
#include <QtCore/QDateTime>
#include <QtGui/QMouseEvent>
namespace Otter
{
BookmarkWidget::BookmarkWidget(BookmarksItem *bookmark, const ActionsManager::ActionEntryDefinition &definition, QWidget *parent) : ToolButtonWidget(definition, parent),
m_bookmark(bookmark)
{
updateBookmark(m_bookmark);
connect(BookmarksManager::getModel(), SIGNAL(bookmarkRemoved(BookmarksItem*)), this, SLOT(removeBookmark(BookmarksItem*)));
connect(BookmarksManager::getModel(), SIGNAL(bookmarkModified(BookmarksItem*)), this, SLOT(updateBookmark(BookmarksItem*)));
}
BookmarkWidget::BookmarkWidget(const QString &path, const ActionsManager::ActionEntryDefinition &definition, QWidget *parent) : ToolButtonWidget(definition, parent),
m_bookmark(BookmarksManager::getModel()->getItem(path))
{
updateBookmark(m_bookmark);
connect(BookmarksManager::getModel(), SIGNAL(bookmarkRemoved(BookmarksItem*)), this, SLOT(removeBookmark(BookmarksItem*)));
connect(BookmarksManager::getModel(), SIGNAL(bookmarkModified(BookmarksItem*)), this, SLOT(updateBookmark(BookmarksItem*)));
}
void BookmarkWidget::mouseReleaseEvent(QMouseEvent *event)
{
QToolButton::mouseReleaseEvent(event);
if ((event->button() == Qt::LeftButton || event->button() == Qt::MiddleButton) && m_bookmark)
{
MainWindow *mainWindow(MainWindow::findMainWindow(parentWidget()));
if (mainWindow)
{
mainWindow->getWindowsManager()->open(m_bookmark, WindowsManager::calculateOpenHints(WindowsManager::DefaultOpen, event->button(), event->modifiers()));
}
}
}
void BookmarkWidget::removeBookmark(BookmarksItem *bookmark)
{
if (m_bookmark && m_bookmark == bookmark)
{
m_bookmark = NULL;
deleteLater();
}
}
void BookmarkWidget::updateBookmark(BookmarksItem *bookmark)
{
if (bookmark != m_bookmark)
{
return;
}
const QString title(m_bookmark->data(BookmarksModel::TitleRole).toString().isEmpty() ? tr("(Untitled)") : m_bookmark->data(BookmarksModel::TitleRole).toString());
const BookmarksModel::BookmarkType type(static_cast<BookmarksModel::BookmarkType>(m_bookmark->data(BookmarksModel::TypeRole).toInt()));
if (type == BookmarksModel::RootBookmark || type == BookmarksModel::TrashBookmark || type == BookmarksModel::FolderBookmark)
{
Menu *menu(new Menu(Menu::BookmarksMenuRole, this));
menu->menuAction()->setData(m_bookmark->index());
setPopupMode(QToolButton::InstantPopup);
setToolTip(title);
setMenu(menu);
setEnabled(m_bookmark->rowCount() > 0);
}
else
{
QStringList toolTip;
toolTip.append(tr("Title: %1").arg(title));
if (!m_bookmark->data(BookmarksModel::UrlRole).toString().isEmpty())
{
toolTip.append(tr("Address: %1").arg(m_bookmark->data(BookmarksModel::UrlRole).toString()));
}
if (m_bookmark->data(BookmarksModel::DescriptionRole).isValid())
{
toolTip.append(tr("Description: %1").arg(m_bookmark->data(BookmarksModel::DescriptionRole).toString()));
}
if (!m_bookmark->data(BookmarksModel::TimeAddedRole).toDateTime().isNull())
{
toolTip.append(tr("Created: %1").arg(m_bookmark->data(BookmarksModel::TimeAddedRole).toDateTime().toString()));
}
if (!m_bookmark->data(BookmarksModel::TimeVisitedRole).toDateTime().isNull())
{
toolTip.append(tr("Visited: %1").arg(m_bookmark->data(BookmarksModel::TimeVisitedRole).toDateTime().toString()));
}
setToolTip(QLatin1String("<div style=\"white-space:pre;\">") + toolTip.join(QLatin1Char('\n')) + QLatin1String("</div>"));
setMenu(NULL);
}
setText(title);
setStatusTip(m_bookmark->data(BookmarksModel::UrlRole).toString());
setIcon(m_bookmark->data(Qt::DecorationRole).value<QIcon>());
}
}
|
gpl-3.0
|
timusus/Shuttle
|
app/src/main/java/com/simplecity/amp_library/ui/modelviews/GenreView.java
|
3659
|
package com.simplecity.amp_library.ui.modelviews;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.simplecity.amp_library.R;
import com.simplecity.amp_library.model.Genre;
import com.simplecity.amp_library.ui.adapters.ViewType;
import com.simplecity.amp_library.ui.views.NonScrollImageButton;
import com.simplecity.amp_library.utils.StringUtils;
import com.simplecityapps.recycler_adapter.model.BaseViewModel;
import com.simplecityapps.recycler_adapter.recyclerview.BaseViewHolder;
public class GenreView extends BaseViewModel<GenreView.ViewHolder> implements
SectionedView {
public interface ClickListener {
void onItemClick(Genre genre);
void onOverflowClick(View v, Genre genre);
}
public Genre genre;
@Nullable
private ClickListener clickListener;
public GenreView(Genre genre) {
this.genre = genre;
}
public void setClickListener(@Nullable ClickListener clickListener) {
this.clickListener = clickListener;
}
void onClick() {
if (clickListener != null) {
clickListener.onItemClick(genre);
}
}
void onOverflowClick(View v) {
if (clickListener != null) {
clickListener.onOverflowClick(v, genre);
}
}
@Override
public int getViewType() {
return ViewType.GENRE;
}
@Override
public int getLayoutResId() {
return R.layout.list_item_two_lines;
}
@Override
public void bindView(ViewHolder holder) {
super.bindView(holder);
holder.lineOne.setText(genre.name);
String albumAndSongsLabel = StringUtils.makeAlbumAndSongsLabel(holder.itemView.getContext(), -1, genre.numSongs);
if (!TextUtils.isEmpty(albumAndSongsLabel)) {
holder.lineTwo.setText(albumAndSongsLabel);
holder.lineTwo.setVisibility(View.VISIBLE);
} else {
holder.lineTwo.setVisibility(View.GONE);
}
}
@Override
public ViewHolder createViewHolder(ViewGroup parent) {
return new ViewHolder(createView(parent));
}
@Override
public String getSectionName() {
String string = StringUtils.keyFor(genre.name);
if (!TextUtils.isEmpty(string)) {
string = string.substring(0, 1).toUpperCase();
} else {
string = " ";
}
return string;
}
public static class ViewHolder extends BaseViewHolder<GenreView> {
@BindView(R.id.line_one)
public TextView lineOne;
@BindView(R.id.line_two)
public TextView lineTwo;
@BindView(R.id.btn_overflow)
public NonScrollImageButton overflowButton;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(v -> viewModel.onClick());
overflowButton.setOnClickListener(v -> viewModel.onOverflowClick(v));
}
@Override
public String toString() {
return "GenreView.ViewHolder";
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GenreView genreView = (GenreView) o;
return genre != null ? genre.equals(genreView.genre) : genreView.genre == null;
}
@Override
public int hashCode() {
return genre != null ? genre.hashCode() : 0;
}
}
|
gpl-3.0
|
sonm-io/core
|
insonmnia/worker/whitelist.go
|
3863
|
package worker
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/docker/distribution/reference"
dc "github.com/docker/docker/client"
"github.com/ethereum/go-ethereum/common"
log "github.com/noxiouz/zapctx/ctxlog"
"github.com/opencontainers/go-digest"
"github.com/sonm-io/core/insonmnia/auth"
"github.com/sonm-io/core/util"
"github.com/sonm-io/core/util/xdocker"
"go.uber.org/zap"
)
type Whitelist interface {
Allowed(ctx context.Context, ref xdocker.Reference, auth string) (bool, xdocker.Reference, error)
}
func NewWhitelist(ctx context.Context, config *WhitelistConfig) Whitelist {
wl := whitelist{
superusers: make(map[string]struct{}),
}
for _, su := range config.PrivilegedAddresses {
parsed := common.HexToAddress(su)
wl.superusers[parsed.Hex()] = struct{}{}
}
go wl.updateRoutine(ctx, config.Url, config.RefreshPeriod)
return &wl
}
type WhitelistRecord struct {
AllowedHashes []digest.Digest `json:"allowed_hashes"`
}
type whitelist struct {
superusers map[string]struct{}
Records map[string]WhitelistRecord
RecordsMu sync.RWMutex
}
func (w *whitelist) updateRoutine(ctx context.Context, url string, updatePeriod uint) error {
ticker := util.NewImmediateTicker(time.Duration(time.Second * time.Duration(updatePeriod)))
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
err := w.load(ctx, url)
if err != nil {
log.G(ctx).Error("could not load whitelist", zap.Error(err))
}
}
}
}
func (w *whitelist) load(ctx context.Context, url string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
log.G(ctx).Info("fetched whitelist")
if resp.StatusCode != 200 {
return fmt.Errorf("failed to download whitelist - got %s", resp.Status)
}
return w.fillFromJsonReader(ctx, resp.Body)
}
func (w *whitelist) fillFromJsonReader(ctx context.Context, jsonReader io.Reader) error {
decoder := json.NewDecoder(jsonReader)
r := make(map[string]WhitelistRecord)
err := decoder.Decode(&r)
if err != nil {
return fmt.Errorf("could not decode whitelist data: %v", err)
}
w.RecordsMu.Lock()
w.Records = r
w.RecordsMu.Unlock()
return nil
}
func (w *whitelist) digestAllowed(name string, digest digest.Digest) (bool, error) {
ref, err := reference.ParseNormalizedNamed(name)
if err != nil {
return false, err
}
w.RecordsMu.RLock()
defer w.RecordsMu.RUnlock()
record, ok := w.Records[ref.Name()]
if !ok {
return false, nil
}
for _, allowedDigest := range record.AllowedHashes {
if allowedDigest == digest {
return true, nil
}
}
return false, nil
}
func (w *whitelist) Allowed(ctx context.Context, ref xdocker.Reference, authority string) (bool, xdocker.Reference, error) {
wallet, err := auth.ExtractWalletFromContext(ctx)
if err != nil {
log.G(ctx).Warn("could not extract wallet from context", zap.Error(err))
return false, ref, err
}
_, ok := w.superusers[wallet.Hex()]
if ok {
return true, ref, nil
}
if !ref.HasName() {
return false, ref, errors.New("can not check whitelist for unnamed reference")
}
if ref.HasDigest() {
allowed, err := w.digestAllowed(ref.Name(), ref.Digest())
return allowed, ref, err
}
dockerClient, err := dc.NewEnvClient()
if err != nil {
return false, ref, err
}
defer dockerClient.Close()
inspection, err := dockerClient.DistributionInspect(ctx, ref.String(), authority)
if err != nil {
return false, ref, fmt.Errorf("could not perform DistributionInspect for %s: %v", ref.String(), err)
}
ref, err = ref.WithDigest(inspection.Descriptor.Digest)
if err != nil {
return false, ref, fmt.Errorf("could not add digest to reference %s: %v", ref.String(), err)
}
allowed, err := w.digestAllowed(ref.Name(), inspection.Descriptor.Digest)
return allowed, ref, err
}
|
gpl-3.0
|
flatCore/flatCore-CMS
|
install/index.php
|
2785
|
<?php
/**
* flatCore Content Management System
* Installer/Updater
*/
session_start();
error_reporting(E_ALL ^E_NOTICE);
require '../config.php';
$modus = 'install';
define('INSTALLER', TRUE);
if(isset($_GET['l']) && is_dir('../lib/lang/'.basename($_GET['l']).'/')) {
$_SESSION['lang'] = basename($_GET['l']);
}
if(!isset($_SESSION['lang']) || $_SESSION['lang'] == '') {
$l = 'de';
$modus = 'choose_lang';
} else {
$l = $_SESSION['lang'];
}
include 'php/functions.php';
include '../lib/lang/'.$l.'/dict-install.php';
include '../acp/core/icons.php';
if(is_file("$fc_db_content")) {
$modus = "update";
$db_type = 'sqlite';
}
if(is_file("../config_database.php")) {
$modus = "update";
$db_type = 'mysql';
}
if(isset($_POST['check_database'])) {
include 'php/check_connection.php';
}
if($_SESSION['user_class'] == "administrator") {
$modus = "update";
}
if($modus == "update") {
/* updates for admins only */
if($_SESSION['user_class'] != "administrator"){
die("PERMISSION DENIED!");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><?php echo"$modus"; ?> flatCore | Content Management System</title>
<script src="../styles/default/js/jquery.min.js"></script>
<script src="../styles/default/js/bootstrap.bundle.min.js"></script>
<link media="screen" rel="stylesheet" type="text/css" href="../styles/default/css/styles.min.css" />
<link media="screen" rel="stylesheet" type="text/css" href="css/styles.css" />
<link href="../acp/fontawesome/css/all.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div id="inst-background">
<div id="inst-header">
<div style="float:right;margin-top:-38px;"><span class="badge badge-info p-2"><?php echo"$modus" ?></span></div>
<h1>flatCore <small>Installation & Setup</small></h1>
</div>
<div id="inst-body">
<?php
if($modus == "install") {
include("inc.install.php");
} else if($modus == "update") {
include("inc.update.php");
} else {
echo '<h3 class="text-center">Choose your Language ...</h3><hr>';
echo '<div class="row">';
echo '<div class="col-md-6">';
echo '<p class="text-center"><a href="index.php?l=de"><img src="../lib/lang/de/flag.png" class="img-rounded"><br>DE</a></p>';
echo '</div>';
echo '<div class="col-md-6">';
echo '<p class="text-center"><a href="index.php?l=en"><img src="../lib/lang/en/flag.png" class="img-rounded"><br>EN</a></p>';
echo '</div>';
echo '</div>';
}
?>
</div>
<div id="inst-footer">
<a href="http://www.flatcore.org">
<img src="images/logo.png" alt="flatCore Logo">
<h3>flatCore<br><small>Content Management System</small></h3>
</a>
</div>
</div>
<p class="text-center"><?php echo date("Y/m/d H:i:s",time()); ?></p>
</div>
</body>
</html>
|
gpl-3.0
|
zebraxxl/CIL2Java
|
StdLibs/System/System/IO/Ports/SerialPort.cs
|
11104
|
using System.Diagnostics;
using System.ComponentModel;
using System.IO;
using System.Text;
namespace System.IO.Ports
{
[MonitoringDescriptionAttribute("SerialPortDesc")]
public class SerialPort : Component
{
public const int InfiniteTimeout = -1;
[MonitoringDescriptionAttribute("SerialErrorReceived")]
public event SerialErrorReceivedEventHandler ErrorReceived;
[MonitoringDescriptionAttribute("SerialPinChanged")]
public event SerialPinChangedEventHandler PinChanged;
[MonitoringDescriptionAttribute("SerialDataReceived")]
public event SerialDataReceivedEventHandler DataReceived;
[BrowsableAttribute(false)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public Stream BaseStream
{
get { throw new NotImplementedException(); }
}
[BrowsableAttribute(true)]
[MonitoringDescriptionAttribute("BaudRate")]
[DefaultValueAttribute(9600)]
public int BaudRate
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(false)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public bool BreakState
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute(false)]
public int BytesToWrite
{
get { throw new NotImplementedException(); }
}
[BrowsableAttribute(false)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public int BytesToRead
{
get { throw new NotImplementedException(); }
}
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute(false)]
public bool CDHolding
{
get { throw new NotImplementedException(); }
}
[BrowsableAttribute(false)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public bool CtsHolding
{
get { throw new NotImplementedException(); }
}
[MonitoringDescriptionAttribute("DataBits")]
[BrowsableAttribute(true)]
[DefaultValueAttribute(8)]
public int DataBits
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DefaultValueAttribute(false)]
[MonitoringDescriptionAttribute("DiscardNull")]
[BrowsableAttribute(true)]
public bool DiscardNull
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(false)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public bool DsrHolding
{
get { throw new NotImplementedException(); }
}
[MonitoringDescriptionAttribute("DtrEnable")]
[BrowsableAttribute(true)]
[DefaultValueAttribute(false)]
public bool DtrEnable
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
[MonitoringDescriptionAttribute("Encoding")]
[BrowsableAttribute(false)]
public Encoding Encoding
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[MonitoringDescriptionAttribute("Handshake")]
//[DefaultValueAttribute(Mono.Cecil.CustomAttributeArgument)]
[BrowsableAttribute(true)]
public Handshake Handshake
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(false)]
public bool IsOpen
{
get { throw new NotImplementedException(); }
}
[DefaultValueAttribute("\n")]
[MonitoringDescriptionAttribute("NewLine")]
[BrowsableAttribute(false)]
public string NewLine
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[MonitoringDescriptionAttribute("Parity")]
[BrowsableAttribute(true)]
//[DefaultValueAttribute(Mono.Cecil.CustomAttributeArgument)]
public Parity Parity
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DefaultValueAttribute(63)]
[MonitoringDescriptionAttribute("ParityReplace")]
[BrowsableAttribute(true)]
public byte ParityReplace
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DefaultValueAttribute("COM1")]
[MonitoringDescriptionAttribute("PortName")]
[BrowsableAttribute(true)]
public string PortName
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(true)]
[DefaultValueAttribute(4096)]
[MonitoringDescriptionAttribute("ReadBufferSize")]
public int ReadBufferSize
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DefaultValueAttribute(-1)]
[BrowsableAttribute(true)]
[MonitoringDescriptionAttribute("ReadTimeout")]
public int ReadTimeout
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[MonitoringDescriptionAttribute("ReceivedBytesThreshold")]
[BrowsableAttribute(true)]
[DefaultValueAttribute(1)]
public int ReceivedBytesThreshold
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(true)]
[MonitoringDescriptionAttribute("RtsEnable")]
[DefaultValueAttribute(false)]
public bool RtsEnable
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
//[DefaultValueAttribute(Mono.Cecil.CustomAttributeArgument)]
[MonitoringDescriptionAttribute("StopBits")]
[BrowsableAttribute(true)]
public StopBits StopBits
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(true)]
[DefaultValueAttribute(2048)]
[MonitoringDescriptionAttribute("WriteBufferSize")]
public int WriteBufferSize
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DefaultValueAttribute(-1)]
[MonitoringDescriptionAttribute("WriteTimeout")]
[BrowsableAttribute(true)]
public int WriteTimeout
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public SerialPort(IContainer container)
{
throw new NotImplementedException();
}
public SerialPort()
{
throw new NotImplementedException();
}
public SerialPort(string portName)
{
throw new NotImplementedException();
}
public SerialPort(string portName, int baudRate)
{
throw new NotImplementedException();
}
public SerialPort(string portName, int baudRate, Parity parity)
{
throw new NotImplementedException();
}
public SerialPort(string portName, int baudRate, Parity parity, int dataBits)
{
throw new NotImplementedException();
}
public SerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
{
throw new NotImplementedException();
}
public void Close()
{
throw new NotImplementedException();
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
public void DiscardInBuffer()
{
throw new NotImplementedException();
}
public void DiscardOutBuffer()
{
throw new NotImplementedException();
}
public static string[] GetPortNames()
{
throw new NotImplementedException();
}
public void Open()
{
throw new NotImplementedException();
}
public int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public int ReadChar()
{
throw new NotImplementedException();
}
public int Read(char[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public int ReadByte()
{
throw new NotImplementedException();
}
public string ReadExisting()
{
throw new NotImplementedException();
}
public string ReadLine()
{
throw new NotImplementedException();
}
public string ReadTo(string value)
{
throw new NotImplementedException();
}
public void Write(string text)
{
throw new NotImplementedException();
}
public void Write(char[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public void WriteLine(string text)
{
throw new NotImplementedException();
}
}
}
|
gpl-3.0
|
3cky/bkemu-android
|
app/src/main/java/su/comp/bk/arch/cpu/opcode/CmpOpcode.java
|
3085
|
/*
* Created: 15.04.2012
*
* Copyright (C) 2012 Victor Antonovich (v.antonovich@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package su.comp.bk.arch.cpu.opcode;
import su.comp.bk.arch.Computer;
import su.comp.bk.arch.cpu.Cpu;
import su.comp.bk.arch.cpu.addressing.AddressingMode;
import su.comp.bk.arch.cpu.addressing.RegisterAddressingMode;
/**
* Compare operation.
*/
public class CmpOpcode extends DoubleOperandOpcode {
public final static int OPCODE = 020000;
public CmpOpcode(Cpu cpu) {
super(cpu);
}
@Override
public int getOpcode() {
return OPCODE;
}
@Override
public int getExecutionTime() {
int srcAddrCode = getSrcOperandAddressingMode().getCode();
int destAddrCode = getDestOperandAddressingMode().getCode();
return getBaseExecutionTime() + getAddressingTimeA(srcAddrCode) +
((srcAddrCode == RegisterAddressingMode.CODE) ? getAddressingTimeA2(destAddrCode)
: getAddressingTimeA(destAddrCode));
}
@Override
public void execute() {
boolean isByteMode = isByteModeOperation();
AddressingMode srcMode = getSrcOperandAddressingMode();
int srcRegister = getSrcOperandRegister();
// Read source value
srcMode.preAddressingAction(isByteMode, srcRegister);
int srcValue = srcMode.readAddressedValue(isByteMode, srcRegister);
srcMode.postAddressingAction(isByteMode, srcRegister);
if (srcValue != Computer.BUS_ERROR) {
// Read destination value
AddressingMode destMode = getDestOperandAddressingMode();
int destRegister = getDestOperandRegister();
destMode.preAddressingAction(isByteMode, destRegister);
int destValue = destMode.readAddressedValue(isByteMode, destRegister);
destMode.postAddressingAction(isByteMode, destRegister);
if (destValue != Computer.BUS_ERROR) {
int resultValue = srcValue - destValue;
// Set flags
Cpu cpu = getCpu();
cpu.setPswFlagN(isByteMode, resultValue);
cpu.setPswFlagZ(isByteMode, resultValue);
cpu.setPswFlagV((((srcValue ^ destValue) & (~destValue ^ resultValue))
& (isByteMode ? 0200 : 0100000)) != 0);
cpu.setPswFlagC((resultValue & (isByteMode ? ~0377 : ~0177777)) != 0);
}
}
}
}
|
gpl-3.0
|
landonb/hamster-applet
|
src/hamster/widgets/dayline.py
|
13958
|
# -*- coding: utf-8 -*-
# Copyright (C) 2007-2010 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster 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 Project Hamster. If not, see <http://www.gnu.org/licenses/>.
import gtk
import gobject
import time
import datetime as dt
from ..lib import stuff, graphics, pytweener
from ..configuration import conf
class Selection(graphics.Sprite):
def __init__(self, start_time = None, end_time = None):
graphics.Sprite.__init__(self, z_order = 100)
self.start_time, self.end_time = None, None
self.width, self.height = None, None
self.fill = None # will be set to proper theme color on render
self.fixed = False
self.start_label = graphics.Label("", 8, "#333", visible = False)
self.end_label = graphics.Label("", 8, "#333", visible = False)
self.duration_label = graphics.Label("", 8, "#FFF", visible = False)
self.add_child(self.start_label, self.end_label, self.duration_label)
self.connect("on-render", self.on_render)
def on_render(self, sprite):
if not self.fill: # not ready yet
return
self.graphics.rectangle(0, 0, self.width, self.height)
self.graphics.fill(self.fill, 0.3)
self.graphics.rectangle(0.5, 0.5, self.width, self.height)
self.graphics.stroke(self.fill)
# adjust labels
self.start_label.visible = self.fixed == False and self.start_time is not None
if self.start_label.visible:
self.start_label.text = self.start_time.strftime("%H:%M")
if self.x - self.start_label.width - 5 > 0:
self.start_label.x = -self.start_label.width - 5
else:
self.start_label.x = 5
self.start_label.y = self.height
self.end_label.visible = self.fixed == False and self.end_time is not None
if self.end_label.visible:
self.end_label.text = self.end_time.strftime("%H:%M")
self.end_label.x = self.width + 5
self.end_label.y = self.height
duration = self.end_time - self.start_time
duration = int(duration.seconds / 60)
self.duration_label.text = "%02d:%02d" % (duration / 60, duration % 60)
self.duration_label.visible = self.duration_label.width < self.width
if self.duration_label.visible:
self.duration_label.y = (self.height - self.duration_label.height) / 2
self.duration_label.x = (self.width - self.duration_label.width) / 2
else:
self.duration_label.visible = False
class DayLine(graphics.Scene):
__gsignals__ = {
"on-time-chosen": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
}
def __init__(self, start_time = None):
graphics.Scene.__init__(self)
day_start = conf.get("day_start_minutes")
self.day_start = dt.time(day_start / 60, day_start % 60)
self.view_time = start_time or dt.datetime.combine(dt.date.today(), self.day_start)
self.scope_hours = 24
self.fact_bars = []
self.categories = []
self.connect("on-enter-frame", self.on_enter_frame)
self.connect("on-mouse-move", self.on_mouse_move)
self.connect("on-mouse-down", self.on_mouse_down)
self.connect("on-mouse-up", self.on_mouse_up)
self.connect("on-click", self.on_click)
self.plot_area = graphics.Sprite()
self.selection = Selection()
self.chosen_selection = Selection()
self.plot_area.add_child(self.selection, self.chosen_selection)
self.drag_start = None
self.current_x = None
self.snap_points = []
self.add_child(self.plot_area)
def plot(self, date, facts, select_start, select_end = None):
for bar in self.fact_bars:
self.plot_area.sprites.remove(bar)
self.fact_bars = []
for fact in facts:
fact_bar = graphics.Rectangle(0, 0, fill = "#aaa", stroke="#aaa") # dimensions will depend on screen situation
fact_bar.fact = fact
if fact.category in self.categories:
fact_bar.category = self.categories.index(fact.category)
else:
fact_bar.category = len(self.categories)
self.categories.append(fact.category)
self.plot_area.add_child(fact_bar)
self.fact_bars.append(fact_bar)
self.view_time = dt.datetime.combine((select_start - dt.timedelta(hours=self.day_start.hour, minutes=self.day_start.minute)).date(), self.day_start)
if select_start and select_start > dt.datetime.now():
select_start = dt.datetime.now()
self.chosen_selection.start_time = select_start
if select_end and select_end > dt.datetime.now():
select_end = dt.datetime.now()
self.chosen_selection.end_time = select_end
self.chosen_selection.width = None
self.chosen_selection.fixed = True
self.chosen_selection.visible = True
self.redraw()
def on_mouse_down(self, scene, event):
self.drag_start = self.current_x
self.chosen_selection.visible = False
def on_mouse_up(self, scene, event):
if self.drag_start:
self.drag_start = None
start_time = self.selection.start_time
if start_time > dt.datetime.now():
start_time = dt.datetime.now()
end_time = self.selection.end_time
self.new_selection()
self.emit("on-time-chosen", start_time, end_time)
def on_click(self, scene, event, target):
self.drag_start = None
# If self.selection.start_time is somehow None, just reset the selection.
# This can sometimes happen when dragging left to right in small
# increments. https://bugzilla.gnome.org/show_bug.cgi?id=669478
if self.selection == None or self.selection.start_time == None:
self.new_selection()
return
start_time = self.selection.start_time
if start_time > dt.datetime.now():
start_time = dt.datetime.now()
end_time = None
if self.fact_bars:
times = [bar.fact.start_time for bar in self.fact_bars if bar.fact.start_time - start_time > dt.timedelta(minutes=5)]
times.extend([bar.fact.start_time + bar.fact.delta for bar in self.fact_bars if bar.fact.start_time + bar.fact.delta - start_time > dt.timedelta(minutes=5)])
if times:
end_time = min(times)
self.new_selection()
self.emit("on-time-chosen", start_time, end_time)
def new_selection(self):
self.plot_area.sprites.remove(self.selection)
self.selection = Selection()
self.plot_area.add_child(self.selection)
self.redraw()
def on_mouse_move(self, scene, event):
if self.current_x:
active_bar = None
# find if we are maybe on a bar
for bar in self.fact_bars:
if bar.x < self.current_x < bar.x + bar.width:
active_bar = bar
break
if active_bar:
self.set_tooltip_text("%s - %s" % (active_bar.fact.activity, active_bar.fact.category))
else:
self.set_tooltip_text("")
self.redraw()
def on_enter_frame(self, scene, context):
g = graphics.Graphics(context)
self.plot_area.y = 15.5
self.plot_area.height = self.height - 30
vertical = min(self.plot_area.height / 5 , 7)
minute_pixel = (self.scope_hours * 60.0 - 15) / self.width
snap_points = []
g.set_line_style(width=1)
bottom = self.plot_area.y + self.plot_area.height
for bar in self.fact_bars:
bar.y = vertical * bar.category + 5
bar.height = vertical
bar_start_time = bar.fact.start_time - self.view_time
minutes = bar_start_time.seconds / 60 + bar_start_time.days * self.scope_hours * 60
bar.x = round(minutes / minute_pixel) + 0.5
bar.width = round((bar.fact.delta).seconds / 60 / minute_pixel)
if not snap_points or bar.x - snap_points[-1][0] > 1:
snap_points.append((bar.x, bar.fact.start_time))
if not snap_points or bar.x + bar.width - snap_points[-1][0] > 1:
snap_points.append((bar.x + bar.width, bar.fact.start_time + bar.fact.delta))
self.snap_points = snap_points
if self.chosen_selection.start_time and self.chosen_selection.width is None:
# we have time but no pixels
minutes = round((self.chosen_selection.start_time - self.view_time).seconds / 60 / minute_pixel) + 0.5
self.chosen_selection.x = minutes
if self.chosen_selection.end_time:
self.chosen_selection.width = round((self.chosen_selection.end_time - self.chosen_selection.start_time).seconds / 60 / minute_pixel)
else:
self.chosen_selection.width = 0
self.chosen_selection.height = self.chosen_selection.parent.height
# use the oportunity to set proper colors too
self.chosen_selection.fill = self.get_style().bg[gtk.STATE_SELECTED].to_string()
self.chosen_selection.duration_label.color = self.get_style().fg[gtk.STATE_SELECTED].to_string()
self.selection.visible = self._mouse_in # TODO - think harder about the mouse_out event
self.selection.width = 0
self.selection.height = self.selection.parent.height
if self.mouse_x:
start_x = max(min(self.mouse_x, self.width-1), 0) #mouse, but within screen regions
# check for snap points
start_x = start_x + 0.5
minutes = int(round(start_x * minute_pixel / 15)) * 15
start_time = self.view_time + dt.timedelta(hours = minutes / 60, minutes = minutes % 60)
if snap_points:
delta, closest_snap, time = min((abs(start_x - i), i, time) for i, time in snap_points)
if abs(closest_snap - start_x) < 5 and (not self.drag_start or self.drag_start != closest_snap):
start_x = closest_snap
minutes = (time.hour - self.day_start.hour) * 60 + time.minute - self.day_start.minute
start_time = time
self.current_x = minutes / minute_pixel
end_time, end_x = None, None
if self.drag_start:
minutes = int(self.drag_start * minute_pixel)
end_time = self.view_time + dt.timedelta(hours = minutes / 60, minutes = minutes % 60)
end_x = round(self.drag_start) + 0.5
if end_time and end_time < start_time:
start_time, end_time = end_time, start_time
start_x, end_x = end_x, start_x
self.selection.start_time = start_time
self.selection.end_time = end_time
self.selection.x = start_x
if end_time:
self.selection.width = end_x - start_x
self.selection.y = 0
self.selection.fill = self.get_style().bg[gtk.STATE_SELECTED].to_string()
self.selection.duration_label.color = self.get_style().fg[gtk.STATE_SELECTED].to_string()
#time scale
g.set_color("#000")
background = self.get_style().bg[gtk.STATE_NORMAL].to_string()
text = self.get_style().text[gtk.STATE_NORMAL].to_string()
tick_color = g.colors.contrast(background, 80)
layout = g.create_layout(size = 8)
for i in range(self.scope_hours * 60):
label_time = (self.view_time + dt.timedelta(minutes=i))
g.set_color(tick_color)
if label_time.minute == 0:
g.move_to(round(i / minute_pixel) + 0.5, bottom - 15)
g.line_to(round(i / minute_pixel) + 0.5, bottom)
g.stroke()
elif label_time.minute % 15 == 0:
g.move_to(round(i / minute_pixel) + 0.5, bottom - 5)
g.line_to(round(i / minute_pixel) + 0.5, bottom)
g.stroke()
if label_time.minute == 0 and label_time.hour % 4 == 0:
if label_time.hour == 0:
g.move_to(round(i / minute_pixel) + 0.5, self.plot_area.y)
g.line_to(round(i / minute_pixel) + 0.5, bottom)
label_minutes = label_time.strftime("%b %d")
else:
label_minutes = label_time.strftime("%H<small><sup>%M</sup></small>")
g.set_color(text)
layout.set_markup(label_minutes)
label_w, label_h = layout.get_pixel_size()
g.move_to(round(i / minute_pixel) + 2, 0)
context.show_layout(layout)
#current time
if self.view_time < dt.datetime.now() < self.view_time + dt.timedelta(hours = self.scope_hours):
minutes = round((dt.datetime.now() - self.view_time).seconds / 60 / minute_pixel) + 0.5
g.move_to(minutes, self.plot_area.y)
g.line_to(minutes, bottom)
g.stroke("#f00", 0.4)
snap_points.append(minutes - 0.5)
|
gpl-3.0
|
cwalther/Plasma-nobink-test
|
Sources/Plasma/PubUtilLib/plDrawable/plSpanInstance.h
|
9242
|
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#ifndef plSpanInstance_inc
#define plSpanInstance_inc
#include "hsGeometry3.h"
#include "hsMatrix44.h"
// plClusterGroup
// array of templates
// array of materials (indexed by templates)
// array of clusters
// array of LOD blend
// array of vis sets
// plCluster
// array of span instances that are combinable
// LOD blend start and end index
// vis set index
// Combinable means:
// same material
// same format
// same LOD blend
// same vis set
// same lights
// same encoding?
// plSpanInstance
// template idx
// 3x4 transform
// encoding flags
// (what components does it include, delPos? color?)
// (what's the encoding? 32bit RGBA? 16Bit/Chan? 10Bit/Chan? 8Bit/Chan?)
// (need an encoding per channel)
// plSpanTemplate
// numVerts
// Format (assume pos & norm?)
// kUVWMask
// kColMask
// kWeightMask
// fPos
// fNorm
// fCol
// fUVWs
// fWeights
class plSpanEncoding
{
public:
enum
{
kPosNone = 0x0,
kPos888 = 0x1,
kPos161616 = 0x2,
kPos101010 = 0x4,
kPos008 = 0x8,
kPosMask = kPos888 | kPos161616 | kPos101010 | kPos008,
kColNone = 0x0,
kColA8 = 0x10,
kColI8 = 0x20,
kColAI88 = 0x40,
kColRGB888 = 0x80,
kColARGB8888 = 0x100,
kColMask = kColNone
| kColA8
| kColI8
| kColAI88
| kColRGB888
| kColARGB8888,
};
uint32_t fCode;
float fPosScale;
plSpanEncoding() : fCode(kPosNone|kColNone), fPosScale(0) {}
plSpanEncoding(uint32_t c, float s) : fCode(c), fPosScale(s) {}
uint32_t Code() const { return fCode; }
float Scale() const { return fPosScale; }
void Read(hsStream* s);
void Write(hsStream* s) const;
};
class plSpanInstance
{
protected:
uint8_t* fPosDelta;
uint8_t* fCol;
float fL2W[3][4];
friend class plSpanInstanceIter;
public:
plSpanInstance();
~plSpanInstance();
void Read(hsStream* s, const plSpanEncoding& encoding, uint32_t numVerts);
void Write(hsStream* s, const plSpanEncoding& encoding, uint32_t numVerts) const;
void Encode(const plSpanEncoding& encoding, uint32_t numVerts, const hsVector3* delPos, const uint32_t* color);
void Alloc(const plSpanEncoding& encoding, uint32_t numVerts);
void DeAlloc();
hsMatrix44 LocalToWorld() const;
hsMatrix44 WorldToLocal() const;
void SetLocalToWorld(const hsMatrix44& l2w);
hsBool HasPosDelta() const { return fPosDelta != nil; }
hsBool HasColor() const { return fCol != nil; }
static uint16_t PosStrideFromEncoding(const plSpanEncoding& encoding)
{
switch(encoding.fCode & plSpanEncoding::kPosMask)
{
case plSpanEncoding::kPos888:
return 3;
case plSpanEncoding::kPos161616:
return 6;
case plSpanEncoding::kPos101010:
return 4;
case plSpanEncoding::kPos008:
return 1;
}
return 0;
}
static uint16_t ColStrideFromEncoding(const plSpanEncoding& encoding)
{
switch(encoding.fCode & plSpanEncoding::kPosMask)
{
case plSpanEncoding::kColNone:
return 0;
case plSpanEncoding::kColA8:
return 1;
case plSpanEncoding::kColI8:
return 1;
case plSpanEncoding::kColAI88:
return 2;
case plSpanEncoding::kColRGB888:
return 3;
case plSpanEncoding::kColARGB8888:
return 4;
}
return 0;
}
};
class plSpanInstanceIter
{
protected:
plSpanInstance* fInst;
plSpanEncoding fEncoding;
uint32_t fNumVerts;
int32_t fNumVertsLeft;
uint16_t fPosStride;
uint16_t fColStride;
union {
int8_t* fPos888;
int16_t* fPos161616;
uint32_t* fPos101010;
};
union {
uint8_t* fA8;
uint8_t* fI8;
uint16_t* fAI88;
uint8_t* fRGB888;
uint32_t* fARGB8888;
};
public:
plSpanInstanceIter();
plSpanInstanceIter(plSpanInstance* inst, const plSpanEncoding& encoding, uint32_t numVerts) { Init(inst, encoding, numVerts); }
void Init(plSpanInstance* inst, const plSpanEncoding& encoding, uint32_t numVerts)
{
fInst = inst;
fEncoding = encoding;
fNumVerts = numVerts;
fPosStride = inst->PosStrideFromEncoding(fEncoding);
fColStride = inst->ColStrideFromEncoding(fEncoding);
fNumVertsLeft = 0;
}
void Begin()
{
fPos888 = (int8_t*)fInst->fPosDelta;
fA8 = fInst->fCol;
fNumVertsLeft = fNumVerts;
}
void Advance()
{
fPos888 += fPosStride;
fA8 += fColStride;
fNumVertsLeft--;
}
hsBool More() const { return fNumVertsLeft > 0; }
hsVector3 DelPos() const
{
switch(fEncoding.fCode & plSpanEncoding::kPosMask)
{
case plSpanEncoding::kPos888:
return hsVector3(fPos888[0] * fEncoding.fPosScale,
fPos888[1] * fEncoding.fPosScale,
fPos888[2] * fEncoding.fPosScale);
case plSpanEncoding::kPos161616:
return hsVector3(fPos161616[0] * fEncoding.fPosScale,
fPos161616[1] * fEncoding.fPosScale,
fPos161616[2] * fEncoding.fPosScale);
case plSpanEncoding::kPos101010:
return hsVector3(int(*fPos101010 & 0x3f) * fEncoding.fPosScale,
int((*fPos101010 >> 10) & 0x3f) * fEncoding.fPosScale,
int((*fPos101010 >> 20) & 0x3f) * fEncoding.fPosScale);
case plSpanEncoding::kPos008:
return hsVector3(0,0, *fPos888 * fEncoding.fPosScale);
}
return hsVector3(0,0,0);
};
hsPoint3 Position(const hsPoint3& p) const
{
hsPoint3 pos(p);
pos += DelPos();
return pos;
};
uint32_t Color(uint32_t c) const
{
switch(fEncoding.fCode & plSpanEncoding::kColMask)
{
case plSpanEncoding::kColA8:
return (c & 0x00ffffff) | *fA8;
case plSpanEncoding::kColI8:
return (c & 0xff000000)
| (*fI8 << 16)
| (*fI8 << 8)
| (*fI8 << 0);
case plSpanEncoding::kColAI88:
{
const uint32_t col = *fAI88 & 0xff;
return ((*fAI88 & 0xff00) << 24)
| (col << 16)
| (col << 8)
| (col << 0);
}
case plSpanEncoding::kColRGB888:
return (c & 0xff000000)
| (fRGB888[0] << 16)
| (fRGB888[1] << 8)
| (fRGB888[2] << 0);
case plSpanEncoding::kColARGB8888:
return *fARGB8888;
}
return c;
};
};
#endif // plSpanInstance_inc
|
gpl-3.0
|
BlisterBoy/Player
|
src/window_varlist.h
|
1773
|
/*
* This file is part of EasyRPG Player.
*
* EasyRPG Player is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EasyRPG Player 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef EP_WINDOW_VARLIST_H
#define EP_WINDOW_VARLIST_H
// Headers
#include "window_command.h"
class Window_VarList : public Window_Command
{
public:
enum Mode {
eNone,
eSwitch,
eVariable,
eItem,
eTroop,
eMap,
eHeal,
eCommonEvent,
eMapEvent,
};
/**
* Constructor.
*
* @param commands commands to display.
*/
Window_VarList(std::vector<std::string> commands);
~Window_VarList() override;
/**
* UpdateList.
*
* @param first_value starting value.
*/
void UpdateList(int first_value);
/**
* Refreshes the window contents.
*/
void Refresh();
/**
* Indicate what to display.
*
* @param mode the mode to set.
*/
void SetMode(Mode mode);
/**
* Returns the current mode.
*/
Mode GetMode() const;
private:
/**
* Draws the value of a variable standing on a row.
*
* @param index row with the var
*/
void DrawItemValue(int index);
Mode mode = eNone;
int first_var = 0;
bool DataIsValid(int range_index);
};
inline Window_VarList::Mode Window_VarList::GetMode() const {
return mode;
}
#endif
|
gpl-3.0
|
ETICAGNU/eticagnuwptheme
|
proyectos.php
|
1313
|
<?php
/*
Template Name: Proyectos
*/
get_header();
the_post();
?>
<div id="primary" class="content-area col-md-9 col-xs-12">
<div id="content" class="site-content col-xs-12">
<article id="post-<?php the_ID() ?>" <?php post_class() ?>>
<header class="entry-header">
<h1 class="entry-title"><?php the_title() ?></h1>
</header>
<div class="entry-content">
<?php the_content() ?>
<?php edit_post_link('Editar', '<span class="edit-link">', '</span>') ?>
<?php $team_posts = get_posts(array( 'post_type' => 'project', 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'ASC')) ?>
<div class="row projects">
<?php foreach ($team_posts as $post): ?>
<?php setup_postdata($post); ?>
<div class="col-sm-6 project">
<?php if (has_post_thumbnail()) : ?>
<?php the_post_thumbnail('full') ?>
<?php endif ?>
<h3 class="project-title"><?php the_title() ?></h3>
<p>
<a rel="follow" href="http://<?php the_field('sitio_web') ?>.eticagnu.org/">http://<?php the_field('sitio_web') ?>.eticagnu.org/</a>
</p>
<div class="project-content">
<?php the_content(); ?>
</div>
</div>
<?php endforeach ?>
</div>
</div>
</article>
</div>
</div>
<?php
get_sidebar();
get_footer();
|
gpl-3.0
|
just-paja/improtresk-2015
|
lib/module/car/offer/admin/detail.php
|
1186
|
<?
namespace Module\Car\Offer\Admin
{
class Detail extends \System\Module
{
public function run()
{
$rq = $this->request;
$res = $this->response;
$ident = $this->req('ident');
$offer = \Car\Offer::get_first()
->where(array(
'ident' => $ident,
'visible' => true
))
->fetch();
if ($offer) {
$cfg = $rq->fconfig;
$cfg['ui']['data'] = array(
array(
'model' => 'Car.Offer',
'items' => array(
$offer->to_object_with_perms($rq->user)
)
)
);
$rq->fconfig = $cfg;
$res->subtitle = 'úpravy nabídky na sdílení auta';
$this->propagate('offer', $offer);
$this->partial('pages/carshare-detail', array(
"item" => $offer,
"free" => $offer->seats - $offer->requests->where(array('status' => 2))->count(),
"show_form" => false,
"show_rq" => true,
"requests" => $offer->requests->add_filter(array(
'attr' => 'status',
'type' => 'exact',
'exact' => array(1,2)
))->fetch(),
));
$this->partial('pages/carshare-admin-links', array(
"ident" => $ident
));
} else throw new \System\Error\NotFound();
}
}
}
|
gpl-3.0
|
pupitetris/rectpack
|
src/ConflictBT.cc
|
5723
|
/**
* Copyright (C) 2011 Eric Huang
*
* This file is part of rectpack.
*
* rectpack is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* rectpack 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 rectpack. If not, see <http://www.gnu.org/licenses/>.
*/
#include "BoundingBoxes.h"
#include "Globals.h"
#include "HeapBox.h"
#include "Parameters.h"
#include "ConflictBT.h"
#include "SimpleSums.h"
#include "SpaceFill.h"
ConflictBT::ConflictBT() :
m_pWidths(NULL),
m_pHeights(NULL) {
}
ConflictBT::~ConflictBT() {
}
bool ConflictBT::packX() {
m_nDeepestConflict = 0;
UInt nTrash(0);
m_vSums.clear();
m_vSums.insert(0);
m_vSums.push();
return(nextVariable(m_vRectPtrs.begin(), nTrash));
}
void ConflictBT::initialize(const Parameters* pParams) {
RatPack::initialize(pParams);
m_vDomains.initialize(pParams);
/**
* If the subset sums computed by the bounding boxes is invalid,
* we'll have to compute our own. Otherwise, we can use the
* precomputed sums.
*/
if(m_pBoxes == NULL ||
m_pBoxes->m_bAllIntegralBoxes ||
m_pBoxes->m_Widths.empty() ||
m_pBoxes->m_Heights.empty()) {
m_Widths.initializeW(m_vRects.begin(), m_vRects.end());
m_pWidths = &m_Widths;
m_Heights.initializeH(m_vRects.begin(), m_vRects.end());
m_pHeights = &m_Heights;
}
else {
m_pWidths = &m_pBoxes->m_Widths;
m_pHeights = &m_pBoxes->m_Heights;
}
}
void ConflictBT::initialize(const HeapBox* pBox) {
RatPack::initialize(pBox);
m_vDomains.initialize(this);
m_vDomains.initialize(&pBox->m_Box);
}
void ConflictBT::initialize(const BoundingBoxes* pBoxes) {
RatPack::initialize(pBoxes);
}
bool ConflictBT::packInterval(RectPtrArray::iterator i,
UInt& nDeepest) {
Rectangle* r(*i);
const DomConfig* dc(&m_vDomains.get(r)[0]); // Change 0 to note dominance rules.
for(DomConfig::const_iterator j = dc->begin(); j != dc->end(); ++j) {
if(m_vX.canFit(*j)) {
m_Nodes.tick(XI);
m_vX.pushHinted(*j);
if(m_vX.propagate())
if(nextVariable(i + 1, nDeepest))
return(true);
m_vX.pop();
}
}
return(false);
}
bool ConflictBT::packSingle(const Compulsory* c,
RectPtrArray::iterator i,
UInt& nDeepest) {
/**
* Now process all rectangles that haven't gotten any commitments
* made.
*/
UInt nNext;
{
SimpleSums ss2(m_vSums);
for(RectPtrArray::iterator i2 = i; i2 != m_iFirstUnit; ++i2) {
if((*i2)->rotatable())
ss2.add((*i2)->m_nWidth, c->m_nStart.m_nRight);
else
ss2.add((*i2)->m_nWidth, (*i2)->m_nHeight,
c->m_nStart.m_nRight);
}
for(UInt m = c->m_pRect->m_nID + 1; m < (UInt) (i - m_vRectPtrs.begin()); ++m)
ss2.add(m_vX.values()[m].m_nValue, c->m_nStart.m_nRight);
SimpleSums::const_iterator j(ss2.lower_bound(c->m_nStart.m_nLeft));
if(j == ss2.end())
nNext = c->m_nStart.m_nRight + 1;
else
nNext = *j;
}
nDeepest = std::max(nDeepest, c->m_pRect->m_nID);
while(nNext <= c->m_nStart.m_nRight) {
UInt nLocalDeepest = c->m_pRect->m_nID;
m_Nodes.tick(XF);
m_vSums.push(nNext + c->m_pRect->m_nWidth);
m_vX.push(c->m_pRect, nNext);
if(m_vX.propagate())
if(nextVariable(i, nLocalDeepest))
return(true);
m_vX.pop();
m_vSums.pop();
nDeepest = std::max(nDeepest, nLocalDeepest);
{
SimpleSums ss2(m_vSums);
for(RectPtrArray::iterator i2 = i;
i2 != m_iFirstUnit && (*i2)->m_nID <= nLocalDeepest; ++i2) {
if((*i2)->rotatable())
ss2.add((*i2)->m_nWidth, c->m_nStart.m_nRight);
else
ss2.add((*i2)->m_nWidth, (*i2)->m_nHeight,
c->m_nStart.m_nRight);
}
for(UInt m = c->m_pRect->m_nID + 1; m < (UInt) (i - m_vRectPtrs.begin()); ++m)
ss2.add(m_vX.values()[m].m_nValue, c->m_nStart.m_nRight);
SimpleSums::const_iterator k(ss2.upper_bound(nNext));
if(k == ss2.end())
nNext = c->m_nStart.m_nRight + 1;
else
nNext = *k;
}
}
return(false);
}
bool ConflictBT::orientation(RectPtrArray::iterator i,
UInt& nDeepest) {
if(packInterval(i, nDeepest)) return(true);
if((*i)->rotatable()) {
(*i)->rotate();
if(packInterval(i, nDeepest)) return(true);
}
return(false);
}
bool ConflictBT::nextVariable(RectPtrArray::iterator i, UInt& nDeepest) {
if(bQuit) return(false);
/**
* In the base case we're at the end of our packing sequence.
*/
if(i == m_iFirstUnit) {
m_nDeepestConflict = m_vRectPtrs.size() - 1;
/**
* We're potentially done with everything. Before we pack the
* other dimension, however, we must ensure that we have
* completely finished with packing even the singular values.
*/
const Compulsory* c(NULL);
UInt nLargestArea(0);
m_vX.largestAreaPlacement(nLargestArea, c);
if(c) return(packSingle(c, i, nDeepest));
else return(packY());
}
m_nDeepestConflict = std::max(m_nDeepestConflict, (*i)->m_nID);
const Compulsory* c(NULL);
UInt nLargestArea(0);
m_vX.largestAreaPlacement(nLargestArea, c);
if(c && nLargestArea > m_vDomains.get(*i)[0][0].area())
return(packSingle(c, i, nDeepest));
else return(orientation(i, nDeepest));
}
bool ConflictBT::packY() {
if(m_pParams->m_bScheduling)
return(true);
else
return(m_pSpaceFill->packY(m_vX, m_pHeights));
}
|
gpl-3.0
|
NotEnoughMods/NotEnoughModPolling
|
NotEnoughMods_Tools.py
|
19543
|
import simplejson
import traceback
import logging
import os
import requests
from collections import OrderedDict
from string import ascii_letters, digits
ID = "nem"
permission = 1
nem_logger = logging.getLogger("NEM_Tools")
# Colour Constants for List and Multilist command
COLOURPREFIX = unichr(3)
COLOUREND = COLOURPREFIX
BOLD = unichr(2)
DARKGREEN = COLOURPREFIX + "03"
RED = COLOURPREFIX + "05"
PURPLE = COLOURPREFIX + "06"
ORANGE = COLOURPREFIX + "07"
BLUE = COLOURPREFIX + "12"
PINK = COLOURPREFIX + "13"
GRAY = COLOURPREFIX + "14"
LIGHTGRAY = COLOURPREFIX + "15"
ALLOWED_IN_FILENAME = "-_.() %s%s" % (ascii_letters, digits)
# Colour Constants End
class NotEnoughClasses():
def getLatestVersion(self):
try:
return self.fetch_json("https://bot.notenoughmods.com/?json")
except:
print("Failed to get NEM versions, falling back to hard-coded")
nem_logger.exception("Failed to get NEM versions, falling back to hard-coded.")
#traceb = str(traceback.format_exc())
# print(traceb)
return ["1.4.5", "1.4.6-1.4.7", "1.5.1", "1.5.2", "1.6.1", "1.6.2", "1.6.4",
"1.7.2", "1.7.4", "1.7.5", "1.7.7", "1.7.9", "1.7.10"]
def __init__(self):
self.requests_session = requests.Session()
self.requests_session.headers = {
'User-agent': 'NotEnoughMods:Tools/1.X (+https://github.com/NotEnoughMods/NotEnoughModPolling)'
}
self.requests_session.max_redirects = 5
self.cache_dir = os.path.join("commands", "NEM", "cache")
self.cache_last_modified = {}
self.cache_etag = {}
self.versions = self.getLatestVersion()
self.version = self.versions[len(self.versions) - 1]
def normalize_filename(self, name):
return ''.join(c for c in name if c in ALLOWED_IN_FILENAME)
def fetch_page(self, url, timeout=10, decode_json=False, cache=False):
try:
if cache:
fname = self.normalize_filename(url)
filepath = os.path.join(self.cache_dir, fname)
if os.path.exists(filepath):
# get it (conditionally) and, if necessary, store the new version
headers = {}
# set etag if it exists
etag = self.cache_etag.get(url)
if etag:
headers['If-None-Match'] = etag
# set last-modified if it exists
last_modified = self.cache_last_modified.get(url)
if last_modified:
headers['If-Modified-Since'] = '"{}"'.format(last_modified)
request = self.requests_session.get(url, timeout=timeout, headers=headers)
if request.status_code == 304:
# load from cache
with open(filepath, 'r') as f:
# and return it
if decode_json:
return simplejson.load(f)
else:
return f.read()
else:
# cache the new version
with open(filepath, 'w') as f:
f.write(request.content)
self.cache_etag[url] = request.headers.get('etag')
self.cache_last_modified[url] = request.headers.get('last-modified')
# and return it
if decode_json:
return request.json()
else:
return request.content
else:
# get it and cache it
request = self.requests_session.get(url, timeout=timeout)
with open(filepath, 'w') as f:
f.write(request.content)
self.cache_etag[url] = request.headers.get('etag')
self.cache_last_modified[url] = request.headers.get('last-modified')
if decode_json:
return request.json()
else:
return request.content
else:
# no caching
request = self.requests_session.get(url, timeout=timeout)
if decode_json:
return request.json()
else:
return request.content
except:
traceback.print_exc()
pass
# most likely a timeout
def fetch_json(self, *args, **kwargs):
return self.fetch_page(*args, decode_json=True, **kwargs)
NEM = NotEnoughClasses()
def execute(self, name, params, channel, userdata, rank):
try:
command = commands[params[0]]
command(self, name, params, channel, userdata, rank)
except:
self.sendMessage(channel, "Invalid sub-command!")
self.sendMessage(channel, "See \"=nem help\" for help")
def setlist(self, name, params, channel, userdata, rank):
if len(params) != 2:
self.sendMessage(channel,
"{name}: Insufficient amount of parameters provided.".format(name=name)
)
self.sendMessage(channel,
"{name}: {setlistHelp}".format(name=name,
setlistHelp=help["setlist"][0])
)
else:
NEM.version = str(params[1])
self.sendMessage(channel,
"switched list to: "
"{bold}{blue}{version}{colourEnd}".format(bold=BOLD,
blue=BLUE,
version=params[1],
colourEnd=COLOUREND)
)
def multilist(self, name, params, channel, userdata, rank):
if len(params) != 2:
self.sendMessage(channel,
"{name}: Insufficient amount of parameters provided.".format(name=name))
self.sendMessage(channel,
"{name}: {multilistHelp}".format(name=name,
multilistHelp=help["multilist"][0])
)
else:
try:
jsonres = {}
results = OrderedDict()
modName = params[1]
for version in NEM.versions:
jsonres[version] = NEM.fetch_json("https://bot.notenoughmods.com/" + requests.utils.quote(version) + ".json", cache=True)
for i, mod in enumerate(jsonres[version]):
if modName.lower() == mod["name"].lower():
results[version] = i
break
else:
aliases = [mod_alias.lower() for mod_alias in mod["aliases"]]
if modName.lower() in aliases:
results[version] = i
count = len(results)
if count == 0:
self.sendMessage(channel, name + ": mod not present in NEM.")
return
elif count == 1:
count = str(count) + " MC version"
else:
count = str(count) + " MC versions"
self.sendMessage(channel, "Listing " + count + " for \"" + params[1] + "\":")
for version in results.iterkeys():
alias = ""
modData = jsonres[version][results[version]]
if modData["aliases"]:
alias_joinText = "{colourEnd}, {colour}".format(colourEnd=COLOUREND,
colour=PINK)
alias_text = alias_joinText.join(modData["aliases"])
alias = "({colour}{text}{colourEnd}) ".format(colourEnd=COLOUREND,
colour=PINK,
text=alias_text)
comment = ""
if modData["comment"] != "":
comment = "({colour}{text}{colourEnd}) ".format(colourEnd=COLOUREND,
colour=GRAY,
text=modData["comment"])
dev = ""
try:
if modData["dev"] != "":
dev = ("({colour}dev{colourEnd}: "
"{colour2}{version}{colourEnd}) ".format(colourEnd=COLOUREND,
colour=GRAY,
colour2=RED,
version=modData["dev"])
)
except Exception as error:
print(error)
traceback.print_exc()
self.sendMessage(channel,
"{bold}{blue}{mcversion}{colourEnd}{bold}: "
"{purple}{name}{colourEnd} {aliasString}"
"{darkgreen}{version}{colourEnd} {devString}"
"{comment}{orange}{shorturl}{colourEnd}".format(name=modData["name"],
aliasString=alias,
devString=dev,
comment=comment,
version=modData["version"],
shorturl=modData["shorturl"],
mcversion=version,
bold=BOLD,
blue=BLUE,
purple=PURPLE,
darkgreen=DARKGREEN,
orange=ORANGE,
colourEnd=COLOUREND)
)
except Exception as error:
self.sendMessage(channel, name + ": " + str(error))
traceback.print_exc()
def list(self, name, params, channel, userdata, rank):
if len(params) < 2:
self.sendMessage(channel,
"{name}: Insufficient amount of parameters provided.".format(name=name))
self.sendMessage(channel,
"{name}: {helpEntry}".format(name=name,
helpEntry=help["list"][0])
)
return
if len(params) >= 3:
version = params[2]
else:
version = NEM.version
try:
result = NEM.fetch_page("https://bot.notenoughmods.com/" + requests.utils.quote(version) + ".json", cache=True)
if not result:
self.sendMessage(channel,
"{0}: Could not fetch the list. Are you sure it exists?".format(name)
)
return
jsonres = simplejson.loads(result, strict=False)
results = []
i = -1
for mod in jsonres:
i = i + 1
if str(params[1]).lower() in mod["name"].lower():
results.append(i)
continue
else:
aliases = mod["aliases"]
for alias in aliases:
if params[1].lower() in alias.lower():
results.append(i)
break
count = len(results)
if count == 0:
self.sendMessage(channel, name + ": no results found.")
return
elif count == 1:
count = str(count) + " result"
else:
count = str(count) + " results"
self.sendMessage(channel,
"Listing {count} for \"{term}\" in "
"{bold}{colour}{version}"
"{colourEnd}{bold}".format(count=count,
term=params[1],
version=version,
bold=BOLD,
colourEnd=COLOUREND,
colour=BLUE)
)
for line in results:
alias = COLOURPREFIX
if jsonres[line]["aliases"]:
alias_joinText = "{colourEnd}, {colour}".format(colourEnd=COLOUREND,
colour=PINK)
alias_text = alias_joinText.join(jsonres[line]["aliases"])
alias = "({colour}{text}{colourEnd}) ".format(colourEnd=COLOUREND,
colour=PINK,
text=alias_text)
comment = ""
if jsonres[line]["comment"] != "":
comment = "({colour}{text}{colourEnd}) ".format(colourEnd=COLOUREND,
colour=GRAY,
text=jsonres[line]["comment"])
dev = ""
try:
if jsonres[line]["dev"] != "":
dev = ("({colour}dev{colourEnd}): "
"{colour2}{version}{colourEnd})".format(colourEnd=COLOUREND,
colour=GRAY,
colour2=RED,
version=jsonres[line]["dev"])
)
except Exception as error:
print(error)
traceback.print_exc()
self.sendMessage(channel,
"{purple}{name}{colourEnd} {aliasString}"
"{darkgreen}{version}{colourEnd} {devString}"
"{comment}{orange}{shorturl}{colourEnd}".format(name=jsonres[line]["name"],
aliasString=alias,
devString=dev,
comment=comment,
version=jsonres[line]["version"],
shorturl=jsonres[line]["shorturl"],
purple=PURPLE,
darkgreen=DARKGREEN,
orange=ORANGE,
colourEnd=COLOUREND)
)
except Exception as error:
self.sendMessage(channel, "{0}: {1}".format(name, error))
traceback.print_exc()
def compare(self, name, params, channel, userdata, rank):
try:
oldVersion, newVersion = params[1], params[2]
oldJson = NEM.fetch_json("https://bot.notenoughmods.com/" + requests.utils.quote(oldVersion) + ".json", cache=True)
newJson = NEM.fetch_json("https://bot.notenoughmods.com/" + requests.utils.quote(newVersion) + ".json", cache=True)
newMods = {modInfo["name"].lower(): True for modInfo in newJson}
missingMods = []
for modInfo in oldJson:
old_modName = modInfo["name"].lower()
if old_modName not in newMods:
missingMods.append(modInfo["name"])
path = "commands/modbot.mca.d3s.co/htdocs/compare/{0}...{1}.json".format(oldVersion, newVersion)
with open(path, "w") as f:
f.write(simplejson.dumps(missingMods, sort_keys=True, indent=4 * ' '))
self.sendMessage(channel,
"{0} mods died trying to update to {1}".format(len(missingMods), newVersion)
)
except Exception as error:
self.sendMessage(channel, "{0}: {1}".format(name, error))
traceback.print_exc()
def about(self, name, params, channel, userdata, rank):
self.sendMessage(channel, "Not Enough Mods toolkit for IRC by SinZ & Yoshi2 v4.0")
def help(self, name, params, channel, userdata, rank):
if len(params) == 1:
self.sendMessage(channel,
"{0}: Available commands: {1}".format(name,
", ".join(help))
)
else:
command = params[1]
if command in help:
for line in help[command]:
self.sendMessage(channel, name + ": " + line)
else:
self.sendMessage(channel, name + ": Invalid command provided")
def force_cacheRedownload(self, name, params, channel, userdata, rank):
if self.rankconvert[rank] >= 3:
for version in NEM.versions:
url = "https://bot.notenoughmods.com/" + requests.utils.quote(version) + ".json"
normalized = NEM.normalize_filename(url)
filepath = os.path.join(NEM.cache_dir, normalized)
if os.path.exists(filepath):
NEM.cache_last_modified[normalized] = 0
self.sendMessage(channel, "Cache Timestamps have been reset. Cache will be redownloaded on the next fetching.")
commands = {
"list": list,
"multilist": multilist,
"about": about,
"help": help,
"setlist": setlist,
"compare": compare,
"forceredownload": force_cacheRedownload
}
help = {
"list": ["=nem list <search> <version>",
"Searches the NotEnoughMods database for <search> and returns all results to IRC."],
"about": ["=nem about",
"Shows some info about the NEM plugin."],
"help": ["=nem help [command]",
"Shows the help info about [command] or lists all commands for this plugin."],
"setlist": ["=nem setlist <version>",
"Sets the default version to be used by other commands to <version>."],
"multilist": ["=nem multilist <modName or alias>",
"Searches the NotEnoughMods database for modName or alias in all MC versions."],
"compare": ["=nem compare <oldVersion> <newVersion>",
"Compares the NEMP entries for two different MC versions and says how many mods haven't been updated to the new version."]
}
|
gpl-3.0
|
mokuki082/EggDrop
|
code/build/bdist.macosx-10.6-intel/python3.4-standalone/app/temp/pygame/imageext.py
|
397
|
def __load():
import imp, os, sys
ext = 'pygame/imageext.so'
for path in sys.path:
if not path.endswith('lib-dynload'):
continue
ext_path = os.path.join(path, ext)
if os.path.exists(ext_path):
mod = imp.load_dynamic(__name__, ext_path)
break
else:
raise ImportError(repr(ext) + " not found")
__load()
del __load
|
gpl-3.0
|
robotage/SyntroApps
|
SyntroCommon/GL/VRWidgetLib/VRPlaneWidget.cpp
|
2597
|
//
// Copyright (c) 2014 richards-tech
//
// This file is part of VRWidgetLib
//
// VRWidgetLib is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// VRWidgetLib 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 VRWidgetLib. If not, see <http://www.gnu.org/licenses/>.
//
#include "VRPlaneWidget.h"
#include <qdebug.h>
VRPlaneWidget::VRPlaneWidget(QObject *parent, VRWIDGET_TYPE widgetType)
: VRWidget(parent, widgetType)
{
m_image = NULL;
}
VRPlaneWidget::~VRPlaneWidget()
{
if (m_image != NULL)
delete m_image;
}
void VRPlaneWidget::VRWidgetInit()
{
m_plane.generate(m_width, m_height);
m_plane.setShader(globalShader[QTGLSHADER_TEXTURE]);
m_image = new QImage(QSize(1280, 720), QImage::Format_RGB888);
m_image->fill(QColor(40, 80, 20, 255));
m_font.setFamily("Arial");
m_font.setPixelSize(8);
m_font.setFixedPitch(true);
}
void VRPlaneWidget::VRWidgetRender()
{
startWidgetRender();
startComponentRender();
m_plane.draw();
endComponentRender(m_plane.getBoundMinus(), m_plane.getBoundPlus());
endWidgetRender();
}
void VRPlaneWidget::paintText(const QString& text, int x, int y, int width)
{
if (m_image == NULL)
return;
QPainter painter(m_image);
QFontMetrics metrics = QFontMetrics(m_font);
int border = qMax(4, metrics.leading());
QRect rect;
rect = metrics.boundingRect(text);
painter.setRenderHint(QPainter::TextAntialiasing);
painter.fillRect(QRect(x, y, width + 2 * border, rect.height() + 2 * border),
QColor(0, 0, 0, 128));
painter.setPen(Qt::white);
painter.drawText(x + border, y + border,
width + border, rect.height() + border,
Qt::AlignLeft | Qt::TextWordWrap, text);
painter.end();
m_plane.setTexture(*m_image);
}
void VRPlaneWidget::paintFileImage(const char *fileName)
{
m_image->load(fileName);
m_image->convertToFormat(QImage::Format_RGB888);
m_plane.setTexture(*m_image);
}
void VRPlaneWidget::paintImage(const QImage& image)
{
*m_image = image;
m_plane.setTexture(*m_image);
}
|
gpl-3.0
|
halilkaya/minetest-mods
|
streets/concretestairs/init.lua
|
597
|
--[[
StreetsMod: Concrete stairs (compatible to circular saw)
]]
if type(register_stair_slab_panel_mirco) == "function" and streets.extendedBy.prefab == false then
register_stair_slab_panel_micro("streets", "concrete", "streets:concrete", {cracky=2}, {"streets_concrete.png"}, "Concrete", "concrete", nil)
table.insert(circular_saw.known_stairs,"streets:concrete")
minetest.register_alias("stairs:stair_concrete","streets:stair_concrete")
else
minetest.register_alias("stairs:stair_concrete","prefab:concrete_stair")
minetest.register_alias("stairs:slab_concrete","prefab:concrete_slab")
end
|
gpl-3.0
|
mx-studio/mx-individual-css-js
|
README.ru.md
|
5889
|
>Прочитать этот документ на другом языке: [Английский / English](/README.md)
# Wordpress-плагин "MX Individual CSS/JS"
Как правило, вы пишите разный CSS/JS-код для разных страниц (для главной страниц, для страницы одиночной записи, для страницы отдельного товара и т.д.) в одном CSS- или JS-файле. Когда ваш проект разрастается и количество CSS/JS-кода становится большим, становится все более и более очевидным, что большое кол-во CSS/JS-кода не релевантно отдельным страницам сайта. Из-за этого лишнего кода размер отдельных страниц сайта больше, чем он мог бы быть.
Было бы полезным, если бы мы могли писать разный CSS/JS-код для отдельных типов страниц. Этот плагин как раз и дает эту возможность. Например, достаточно создать файл single.css и данный плагин автоматически подключит этот css-файл к каждой странице одиночной записи. Если вы хотите написать CSS-код для страницы товара Woocommerce, просто добавьте single-product.css. От вас не требуется никаких дополнительных действий, кроме создания CSS/JS-файла, предназначенного для определенного типа страниц. Плагин автоматически проверяет существование CSS/JS-файлов, которые относятся к текущему типу страницы и подключается их.
## Правило именования файлов для автоматического подключения
Правила именования CSS/JS-файлов схоже с правилами именования файлов wordpress-шаблона:
- *admin.css / admin.js* — подключается для всех страниц административной панели
- *home.css / home.js* — подключается на главной странице
- *search.css / search.js* — подключается на странице с результатами поиска
- *404.css / 404.js* — подключается на странице 404-й ошибки
- *singular.css / singular.js* — подключается к каждой одиночной странице или записи
- *single.css / single.js* — подключается к каждой одиночной записи (любого типа, не только встроенного типа "post")
- *single-{posttype}.css / single-{posttype}.js* — подключается к каждой странице определенного типа "{posttype}"
- *page.css / page.js* — подключается к каждой одиночной странице
- *page-{id}.css / page-{id}.js* — подключается к странице с заданным ID {id}
- *page-{slug}.css / page-{slug}.js* — подключается к странице с заданным слагом {slug}
- *archive.css / archive.js* — подключается к каждой архивной странице
- *category.css / category.js* — подключается к каждой странице категории
- *category-{id}.css / category-{id}.js* — подключается к странице категории с заданным ID {id}
- *category-{slug}.css / category-{slug}.js* — подключается к странице категории с заданным слагом {slug}
CSS/JS-файлы должны быть размещены в папках, которые заданы на странице с настройками плагина. ***По умолчанию, папки для CSS- и JS-файлов - подпапки "css" и "js" в директории темы***.
>Другим преимущество такого распределения CSS/JS-кода по разным файлам в том, что вы логически структуризуете свой код. Таким образом, становится легче найти нужный участок кода для правки страницы определенного типа. Чем больше код вашего проекта, тем более ощутимым становится данное преимущество.
## Поддержка минифицированных версий CSS/JS-файлов
Этот плагин также обнаруживает минифицированные версии CSS/JS-файлов (.min.css и .min.js) и подключает их вместо полных версий файлов.
## Установка
1. Скачать [последний релиз](https://github.com/mx-studio/mx-individual-css-js/releases/latest) плагина
2. В административной панели Wordpress перейти к разделу Плагины->Добавить новый
3. Нажмите кнопку "Загрузить плагин"
4. Загрузите zip-архив, который вы скачали на 1-м шаге
5. Активируйте плагин
## Лицензия
Данный продукт распространяются под лицензией GPLv3+
|
gpl-3.0
|
CCAFS/MARLO
|
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/DeliverableUserPartnershipMySQLDAO.java
|
4091
|
/*****************************************************************
* This file is part of Managing Agricultural Research for Learning &
* Outcomes Platform (MARLO).
* MARLO is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option) any later version.
* MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************/
package org.cgiar.ccafs.marlo.data.dao.mysql;
import org.cgiar.ccafs.marlo.data.dao.DeliverableUserPartnershipDAO;
import org.cgiar.ccafs.marlo.data.model.DeliverableUserPartnership;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
@Named
public class DeliverableUserPartnershipMySQLDAO extends AbstractMarloDAO<DeliverableUserPartnership, Long>
implements DeliverableUserPartnershipDAO {
@Inject
public DeliverableUserPartnershipMySQLDAO(SessionFactory sessionFactory) {
super(sessionFactory);
}
@Override
public void deleteDeliverableUserPartnership(long deliverableUserPartnershipId) {
DeliverableUserPartnership deliverableUserPartnership = this.find(deliverableUserPartnershipId);
deliverableUserPartnership.setActive(false);
this.update(deliverableUserPartnership);
}
@Override
public boolean existDeliverableUserPartnership(long deliverableUserPartnershipID) {
DeliverableUserPartnership deliverableUserPartnership = this.find(deliverableUserPartnershipID);
if (deliverableUserPartnership == null) {
return false;
}
return true;
}
@Override
public DeliverableUserPartnership find(long id) {
return super.find(DeliverableUserPartnership.class, id);
}
@Override
public List<DeliverableUserPartnership> findAll() {
String query = "from " + DeliverableUserPartnership.class.getName() + " where is_active=1";
List<DeliverableUserPartnership> list = super.findAll(query);
if (list.size() > 0) {
return list;
}
return null;
}
@Override
public List<DeliverableUserPartnership> findByDeliverableID(long deliverableID) {
String query =
"from " + DeliverableUserPartnership.class.getName() + " where is_active=1 and deliverable_id = " + deliverableID;
List<DeliverableUserPartnership> list = super.findAll(query);
if (list.isEmpty()) {
return list;
}
return null;
}
@Override
public List<DeliverableUserPartnership> findPartnershipsByInstitutionProjectAndPhase(long institutionId,
long projectId, long phaseId) {
String query = "select dup from DeliverableUserPartnership dup where dup.institution.id = :institutionId and "
+ "dup.phase.id = :phaseId and dup.deliverable.project.id = :projectId and dup.deliverable.active = true";
Query createQuery = this.getSessionFactory().getCurrentSession().createQuery(query);
createQuery.setParameter("phaseId", phaseId);
createQuery.setParameter("institutionId", institutionId);
createQuery.setParameter("projectId", projectId);
List<DeliverableUserPartnership> deliverables = super.findAll(createQuery);
return deliverables;
}
@Override
public DeliverableUserPartnership save(DeliverableUserPartnership deliverableUserPartnership) {
if (deliverableUserPartnership.getId() == null) {
super.saveEntity(deliverableUserPartnership);
} else {
deliverableUserPartnership = super.update(deliverableUserPartnership);
}
return deliverableUserPartnership;
}
}
|
gpl-3.0
|
TheWhiteShadow3/cuina
|
CuinaEclipse/cuina.editor.map/src/cuina/map/Map.java
|
2507
|
package cuina.map;
import cuina.database.KeyReference;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Rasterbasiertes Spielfeld mit Terraininformationen.
* <p>
* Enthält weitere Daten:
* <dl>
* <dt>objects</dt>
* <dd>Liste von Objekten welche Spielobjekte auf der Karte darstellen.</dd>
* </dl>
* <dt>events</dt>
* <dd>Liste von Objekten welche kartenbezogene Events darstellen.</dd>
* </dl>
* </p>
* @author TheWhiteShadow
*/
public class Map implements Serializable
{
private static final long serialVersionUID = 7126463419853704389L;
public static final int LAYERS = 4;
/** Schlüssel der Map. */
private String key;
/** Feldanzahl in horizontaler Richtung. */
public int width;
/** Feldanzahl in vertikaler Richtung. */
public int height;
// transient, da Mapdaten optimiert serialisiert werden.
/** 3D-Array mit den IDs der einzelnen Felder. */
transient public short[][][] data;
/** Spielobjekte auf der Karte. */
public List<Object> objects;
public List<Object> areas;
public List<Object> paths;
// Referenz zur Tileset-Datenbank
@KeyReference(name="Tileset")
public String tilesetKey = "";
public Map(String key, int width, int height)
{
this.key = key;
this.width = width;
this.height = height;
this.data = new short[width][height][LAYERS];
this.objects = new ArrayList<Object>();
this.areas = new ArrayList<Object>();
this.paths = new ArrayList<Object>();
}
public String getKey()
{
return key;
}
private final synchronized void writeObject( ObjectOutputStream s ) throws IOException
{
s.defaultWriteObject();
short[] dataStream = new short[width * height * LAYERS];
for(int x = 0; x < width; x++)
for(int y = 0; y < height; y++)
for(int z = 0; z < LAYERS; z++)
{
dataStream[x*height*LAYERS + y*LAYERS + z] = data[x][y][z];
}
s.writeObject(dataStream);
}
private final synchronized void readObject( ObjectInputStream s ) throws IOException, ClassNotFoundException
{
s.defaultReadObject();
short[] dataStream = (short[])s.readObject();
data = new short[width][height][LAYERS];
for(int x = 0; x < width; x++)
for(int y = 0; y < height; y++)
for(int z = 0; z < LAYERS; z++)
{
data[x][y][z] = dataStream[x*height*LAYERS + y*LAYERS + z];
// if (version < 1 && data[x][y][z] > 0)
// data[x][y][z] += Tileset.AUTOTILES_OFFSET;
}
// version = 1;
}
}
|
gpl-3.0
|
y123456yz/Reading-and-comprehense-linux-Kernel-network-protocol-stack
|
linux-net-kernel/net/ipv4/arp.c
|
37200
|
/* linux/net/ipv4/arp.c
*
* Copyright (C) 1994 by Florian La Roche
*
* This module implements the Address Resolution Protocol ARP (RFC 826),
* which is used to convert IP addresses (or in the future maybe other
* high-level addresses) into a low-level hardware address (like an Ethernet
* address).
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Fixes:
* Alan Cox : Removed the Ethernet assumptions in
* Florian's code
* Alan Cox : Fixed some small errors in the ARP
* logic
* Alan Cox : Allow >4K in /proc
* Alan Cox : Make ARP add its own protocol entry
* Ross Martin : Rewrote arp_rcv() and arp_get_info()
* Stephen Henson : Add AX25 support to arp_get_info()
* Alan Cox : Drop data when a device is downed.
* Alan Cox : Use init_timer().
* Alan Cox : Double lock fixes.
* Martin Seine : Move the arphdr structure
* to if_arp.h for compatibility.
* with BSD based programs.
* Andrew Tridgell : Added ARP netmask code and
* re-arranged proxy handling.
* Alan Cox : Changed to use notifiers.
* Niibe Yutaka : Reply for this device or proxies only.
* Alan Cox : Don't proxy across hardware types!
* Jonathan Naylor : Added support for NET/ROM.
* Mike Shaver : RFC1122 checks.
* Jonathan Naylor : Only lookup the hardware address for
* the correct hardware type.
* Germano Caronni : Assorted subtle races.
* Craig Schlenter : Don't modify permanent entry
* during arp_rcv.
* Russ Nelson : Tidied up a few bits.
* Alexey Kuznetsov: Major changes to caching and behaviour,
* eg intelligent arp probing and
* generation
* of host down events.
* Alan Cox : Missing unlock in device events.
* Eckes : ARP ioctl control errors.
* Alexey Kuznetsov: Arp free fix.
* Manuel Rodriguez: Gratuitous ARP.
* Jonathan Layes : Added arpd support through kerneld
* message queue (960314)
* Mike Shaver : /proc/sys/net/ipv4/arp_* support
* Mike McLagan : Routing by source
* Stuart Cheshire : Metricom and grat arp fixes
* *** FOR 2.1 clean this up ***
* Lawrence V. Stefani: (08/12/96) Added FDDI support.
* Alan Cox : Took the AP1000 nasty FDDI hack and
* folded into the mainstream FDDI code.
* Ack spit, Linus how did you allow that
* one in...
* Jes Sorensen : Make FDDI work again in 2.1.x and
* clean up the APFDDI & gen. FDDI bits.
* Alexey Kuznetsov: new arp state machine;
* now it is in net/core/neighbour.c.
* Krzysztof Halasa: Added Frame Relay ARP support.
* Arnaldo C. Melo : convert /proc/net/arp to seq_file
* Shmulik Hen: Split arp_send to arp_create and
* arp_xmit so intermediate drivers like
* bonding can change the skb before
* sending (e.g. insert 8021q tag).
* Harald Welte : convert to make use of jenkins hash
* Jesper D. Brouer: Proxy ARP PVLAN RFC 3069 support.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/capability.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/errno.h>
#include <linux/in.h>
#include <linux/mm.h>
#include <linux/inet.h>
#include <linux/inetdevice.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/fddidevice.h>
#include <linux/if_arp.h>
#include <linux/trdevice.h>
#include <linux/skbuff.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/net.h>
#include <linux/rcupdate.h>
#include <linux/jhash.h>
#include <linux/slab.h>
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
#endif
#include <net/net_namespace.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/route.h>
#include <net/protocol.h>
#include <net/tcp.h>
#include <net/sock.h>
#include <net/arp.h>
#include <net/ax25.h>
#include <net/netrom.h>
#if defined(CONFIG_ATM_CLIP) || defined(CONFIG_ATM_CLIP_MODULE)
#include <net/atmclip.h>
struct neigh_table *clip_tbl_hook;
#endif
#include <asm/system.h>
#include <asm/uaccess.h>
#include <linux/netfilter_arp.h>
/*
* Interface to generic neighbour cache.
*/
static u32 arp_hash(const void *pkey, const struct net_device *dev);
static int arp_constructor(struct neighbour *neigh);
static void arp_solicit(struct neighbour *neigh, struct sk_buff *skb);
static void arp_error_report(struct neighbour *neigh, struct sk_buff *skb);
static void parp_redo(struct sk_buff *skb);
static const struct neigh_ops arp_generic_ops = {
.family = AF_INET,
.solicit = arp_solicit,
.error_report = arp_error_report,
.output = neigh_resolve_output,
.connected_output = neigh_connected_output,
.hh_output = dev_queue_xmit,
.queue_xmit = dev_queue_xmit,
};
static const struct neigh_ops arp_hh_ops = {
.family = AF_INET,
.solicit = arp_solicit,
.error_report = arp_error_report,
.output = neigh_resolve_output,
.connected_output = neigh_resolve_output,
.hh_output = dev_queue_xmit,
.queue_xmit = dev_queue_xmit,
};
static const struct neigh_ops arp_direct_ops = {
.family = AF_INET,
.output = dev_queue_xmit,
.connected_output = dev_queue_xmit,
.hh_output = dev_queue_xmit,
.queue_xmit = dev_queue_xmit,
};
const struct neigh_ops arp_broken_ops = {//ÁÚ¾Ó³õʼ»¯µÄʱºòµ÷Óà ÔÚº¯Êýarp_constructorÀïÃæµ÷ÓÃ
.family = AF_INET,
.solicit = arp_solicit,
.error_report = arp_error_report,
.output = neigh_compat_output,
.connected_output = neigh_compat_output,
.hh_output = dev_queue_xmit,
.queue_xmit = dev_queue_xmit,
};
//ARPÈ«¾Ö±äÁ¿£¬ARP»º´æ±í ÁÚ¾Ó±í
struct neigh_table arp_tbl = {
.family = AF_INET,
.entry_size = sizeof(struct neighbour) + 4,
.key_len = 4,
.hash = arp_hash,
.constructor = arp_constructor,
.proxy_redo = parp_redo,
.id = "arp_cache",
.parms = {
.tbl = &arp_tbl,
.base_reachable_time = 30 * HZ,
.retrans_time = 1 * HZ,
.gc_staletime = 60 * HZ,
.reachable_time = 30 * HZ,
.delay_probe_time = 5 * HZ,
.queue_len = 3,
.ucast_probes = 3,
.mcast_probes = 3,
.anycast_delay = 1 * HZ,
.proxy_delay = (8 * HZ) / 10,
.proxy_qlen = 64,
.locktime = 1 * HZ,
},
.gc_interval = 30 * HZ,
.gc_thresh1 = 128,
.gc_thresh2 = 512,
.gc_thresh3 = 1024,
};
int arp_mc_map(__be32 addr, u8 *haddr, struct net_device *dev, int dir)
{
switch (dev->type) {
case ARPHRD_ETHER:
case ARPHRD_FDDI:
case ARPHRD_IEEE802:
ip_eth_mc_map(addr, haddr);
return 0;
case ARPHRD_IEEE802_TR:
ip_tr_mc_map(addr, haddr);
return 0;
case ARPHRD_INFINIBAND:
ip_ib_mc_map(addr, dev->broadcast, haddr);
return 0;
default:
if (dir) {
memcpy(haddr, dev->broadcast, dev->addr_len);
return 0;
}
}
return -EINVAL;
}
static u32 arp_hash(const void *pkey, const struct net_device *dev)
{
return jhash_2words(*(u32 *)pkey, dev->ifindex, arp_tbl.hash_rnd);
}
//ARPÁÚ¾Ó³õʼ»¯º¯Êý£¬ÓÃÀ´³õʼ»¯ÐµÄneibour½á¹¹ÊµÀý¡£ÔÚÁÚ¾Ó±í´´½¨º¯Êýneibour_createÖб»µ÷Óà ¸Ãº¯ÊýÔÚarp_tblÖгõʼ»¯
static int arp_constructor(struct neighbour *neigh)
{
__be32 addr = *(__be32*)neigh->primary_key;
struct net_device *dev = neigh->dev;
struct in_device *in_dev;
struct neigh_parms *parms;
rcu_read_lock();
in_dev = __in_dev_get_rcu(dev);
if (in_dev == NULL) {
rcu_read_unlock();
return -EINVAL;
}
neigh->type = inet_addr_type(dev_net(dev), addr);
parms = in_dev->arp_parms;
__neigh_parms_put(neigh->parms);
neigh->parms = neigh_parms_clone(parms);
rcu_read_unlock();
if (!dev->header_ops) {
neigh->nud_state = NUD_NOARP;
neigh->ops = &arp_direct_ops;
neigh->output = neigh->ops->queue_xmit;
} else {
/* Good devices (checked by reading texts, but only Ethernet is
tested)
ARPHRD_ETHER: (ethernet, apfddi)
ARPHRD_FDDI: (fddi)
ARPHRD_IEEE802: (tr)
ARPHRD_METRICOM: (strip)
ARPHRD_ARCNET:
etc. etc. etc.
ARPHRD_IPDDP will also work, if author repairs it.
I did not it, because this driver does not work even
in old paradigm.
*/
#if 1
/* So... these "amateur" devices are hopeless.
The only thing, that I can say now:
It is very sad that we need to keep ugly obsolete
code to make them happy.
They should be moved to more reasonable state, now
they use rebuild_header INSTEAD OF hard_start_xmit!!!
Besides that, they are sort of out of date
(a lot of redundant clones/copies, useless in 2.1),
I wonder why people believe that they work.
*/
switch (dev->type) {
default:
break;
case ARPHRD_ROSE:
#if defined(CONFIG_AX25) || defined(CONFIG_AX25_MODULE)
case ARPHRD_AX25:
#if defined(CONFIG_NETROM) || defined(CONFIG_NETROM_MODULE)
case ARPHRD_NETROM:
#endif
neigh->ops = &arp_broken_ops;
neigh->output = neigh->ops->output;
return 0;
#endif
;}
#endif
if (neigh->type == RTN_MULTICAST) {
neigh->nud_state = NUD_NOARP;
arp_mc_map(addr, neigh->ha, dev, 1);
} else if (dev->flags&(IFF_NOARP|IFF_LOOPBACK)) {
neigh->nud_state = NUD_NOARP;
memcpy(neigh->ha, dev->dev_addr, dev->addr_len);
} else if (neigh->type == RTN_BROADCAST || dev->flags&IFF_POINTOPOINT) {
neigh->nud_state = NUD_NOARP;
memcpy(neigh->ha, dev->broadcast, dev->addr_len);
}
if (dev->header_ops->cache)
neigh->ops = &arp_hh_ops;
else
neigh->ops = &arp_generic_ops;
if (neigh->nud_state&NUD_VALID)
neigh->output = neigh->ops->connected_output;
else
neigh->output = neigh->ops->output;
}
return 0;
}
static void arp_error_report(struct neighbour *neigh, struct sk_buff *skb)
{
dst_link_failure(skb);
kfree_skb(skb);
}
//ÔÚARPÁÚ¾ÓÏÊýÖ¸ÕëÀïÃæ±»¸³Öµ
static void arp_solicit(struct neighbour *neigh, struct sk_buff *skb)
{
__be32 saddr = 0;
u8 *dst_ha = NULL;
struct net_device *dev = neigh->dev;
__be32 target = *(__be32*)neigh->primary_key;
int probes = atomic_read(&neigh->probes);
struct in_device *in_dev = in_dev_get(dev);
if (!in_dev)
return;
switch (IN_DEV_ARP_ANNOUNCE(in_dev)) {
default:
case 0: /* By default announce any local IP */
if (skb && inet_addr_type(dev_net(dev), ip_hdr(skb)->saddr) == RTN_LOCAL)
saddr = ip_hdr(skb)->saddr;
break;
case 1: /* Restrict announcements of saddr in same subnet */
if (!skb)
break;
saddr = ip_hdr(skb)->saddr;
if (inet_addr_type(dev_net(dev), saddr) == RTN_LOCAL) {
/* saddr should be known to target */
if (inet_addr_onlink(in_dev, target, saddr))
break;
}
saddr = 0;
break;
case 2: /* Avoid secondary IPs, get a primary/preferred one */
break;
}
if (in_dev)
in_dev_put(in_dev);
if (!saddr)
saddr = inet_select_addr(dev, target, RT_SCOPE_LINK);
if ((probes -= neigh->parms->ucast_probes) < 0) {
if (!(neigh->nud_state&NUD_VALID))
printk(KERN_DEBUG "trying to ucast probe in NUD_INVALID\n");
dst_ha = neigh->ha;
read_lock_bh(&neigh->lock);
} else if ((probes -= neigh->parms->app_probes) < 0) {
#ifdef CONFIG_ARPD
neigh_app_ns(neigh);
#endif
return;
}
arp_send(ARPOP_REQUEST, ETH_P_ARP, target, dev, saddr,
dst_ha, dev->dev_addr, NULL);
if (dst_ha)
read_unlock_bh(&neigh->lock);
}
static int arp_ignore(struct in_device *in_dev, __be32 sip, __be32 tip)
{
int scope;
switch (IN_DEV_ARP_IGNORE(in_dev)) {
case 0: /* Reply, the tip is already validated */
return 0;
case 1: /* Reply only if tip is configured on the incoming interface */
sip = 0;
scope = RT_SCOPE_HOST;
break;
case 2: /*
* Reply only if tip is configured on the incoming interface
* and is in same subnet as sip
*/
scope = RT_SCOPE_HOST;
break;
case 3: /* Do not reply for scope host addresses */
sip = 0;
scope = RT_SCOPE_LINK;
break;
case 4: /* Reserved */
case 5:
case 6:
case 7:
return 0;
case 8: /* Do not reply */
return 1;
default:
return 0;
}
return !inet_confirm_addr(in_dev, sip, tip, scope);
}
static int arp_filter(__be32 sip, __be32 tip, struct net_device *dev)
{
struct flowi fl = { .nl_u = { .ip4_u = { .daddr = sip,
.saddr = tip } } };
struct rtable *rt;
int flag = 0;
/*unsigned long now; */
struct net *net = dev_net(dev);
if (ip_route_output_key(net, &rt, &fl) < 0)
return 1;
if (rt->u.dst.dev != dev) {
NET_INC_STATS_BH(net, LINUX_MIB_ARPFILTER);
flag = 1;
}
ip_rt_put(rt);
return flag;
}
/* OBSOLETE FUNCTIONS */
/*
* Find an arp mapping in the cache. If not found, post a request.
*
* It is very UGLY routine: it DOES NOT use skb->dst->neighbour,
* even if it exists. It is supposed that skb->dev was mangled
* by a virtual device (eql, shaper). Nobody but broken devices
* is allowed to use this function, it is scheduled to be removed. --ANK
*/
static int arp_set_predefined(int addr_hint, unsigned char * haddr, __be32 paddr, struct net_device * dev)
{
switch (addr_hint) {
case RTN_LOCAL:
printk(KERN_DEBUG "ARP: arp called for own IP address\n");
memcpy(haddr, dev->dev_addr, dev->addr_len);
return 1;
case RTN_MULTICAST:
arp_mc_map(paddr, haddr, dev, 1);
return 1;
case RTN_BROADCAST:
memcpy(haddr, dev->broadcast, dev->addr_len);
return 1;
}
return 0;
}
int arp_find(unsigned char *haddr, struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
__be32 paddr;
struct neighbour *n;
if (!skb_dst(skb)) {
printk(KERN_DEBUG "arp_find is called with dst==NULL\n");
kfree_skb(skb);
return 1;
}
paddr = skb_rtable(skb)->rt_gateway;
if (arp_set_predefined(inet_addr_type(dev_net(dev), paddr), haddr, paddr, dev))
return 0;
n = __neigh_lookup(&arp_tbl, &paddr, dev, 1);
if (n) {
n->used = jiffies;
if (n->nud_state&NUD_VALID || neigh_event_send(n, skb) == 0) {
read_lock_bh(&n->lock);
memcpy(haddr, n->ha, dev->addr_len);
read_unlock_bh(&n->lock);
neigh_release(n);
return 0;
}
neigh_release(n);
} else
kfree_skb(skb);
return 1;
}
/* END OF OBSOLETE FUNCTIONS */
int arp_bind_neighbour(struct dst_entry *dst)
{
struct net_device *dev = dst->dev;
struct neighbour *n = dst->neighbour;
if (dev == NULL)
return -EINVAL;
if (n == NULL) {
__be32 nexthop = ((struct rtable *)dst)->rt_gateway;
if (dev->flags&(IFF_LOOPBACK|IFF_POINTOPOINT))
nexthop = 0;
n = __neigh_lookup_errno(
#if defined(CONFIG_ATM_CLIP) || defined(CONFIG_ATM_CLIP_MODULE)
dev->type == ARPHRD_ATM ? clip_tbl_hook :
#endif
&arp_tbl, &nexthop, dev);
if (IS_ERR(n))
return PTR_ERR(n);
dst->neighbour = n;
}
return 0;
}
/*
* Check if we can use proxy ARP for this path
*/
static inline int arp_fwd_proxy(struct in_device *in_dev,
struct net_device *dev, struct rtable *rt)
{
struct in_device *out_dev;
int imi, omi = -1;
if (rt->u.dst.dev == dev)
return 0;
if (!IN_DEV_PROXY_ARP(in_dev))
return 0;
if ((imi = IN_DEV_MEDIUM_ID(in_dev)) == 0)
return 1;
if (imi == -1)
return 0;
/* place to check for proxy_arp for routes */
if ((out_dev = in_dev_get(rt->u.dst.dev)) != NULL) {
omi = IN_DEV_MEDIUM_ID(out_dev);
in_dev_put(out_dev);
}
return (omi != imi && omi != -1);
}
/*
* Check for RFC3069 proxy arp private VLAN (allow to send back to same dev)
*
* RFC3069 supports proxy arp replies back to the same interface. This
* is done to support (ethernet) switch features, like RFC 3069, where
* the individual ports are not allowed to communicate with each
* other, BUT they are allowed to talk to the upstream router. As
* described in RFC 3069, it is possible to allow these hosts to
* communicate through the upstream router, by proxy_arp'ing.
*
* RFC 3069: "VLAN Aggregation for Efficient IP Address Allocation"
*
* This technology is known by different names:
* In RFC 3069 it is called VLAN Aggregation.
* Cisco and Allied Telesyn call it Private VLAN.
* Hewlett-Packard call it Source-Port filtering or port-isolation.
* Ericsson call it MAC-Forced Forwarding (RFC Draft).
*
*/
static inline int arp_fwd_pvlan(struct in_device *in_dev,
struct net_device *dev, struct rtable *rt,
__be32 sip, __be32 tip)
{
/* Private VLAN is only concerned about the same ethernet segment */
if (rt->u.dst.dev != dev)
return 0;
/* Don't reply on self probes (often done by windowz boxes)*/
if (sip == tip)
return 0;
if (IN_DEV_PROXY_ARP_PVLAN(in_dev))
return 1;
else
return 0;
}
/*
* Interface to link layer: send routine and receive handler.
*/
/*
* Create an arp packet. If (dest_hw == NULL), we create a broadcast
* message.
*/
struct sk_buff *arp_create(int type, int ptype, __be32 dest_ip,
struct net_device *dev, __be32 src_ip,
const unsigned char *dest_hw,
const unsigned char *src_hw,
const unsigned char *target_hw)
{
struct sk_buff *skb;
struct arphdr *arp;
unsigned char *arp_ptr;
/*
* Allocate a buffer
*/
skb = alloc_skb(arp_hdr_len(dev) + LL_ALLOCATED_SPACE(dev), GFP_ATOMIC);
if (skb == NULL)
return NULL;
skb_reserve(skb, LL_RESERVED_SPACE(dev));
skb_reset_network_header(skb);
arp = (struct arphdr *) skb_put(skb, arp_hdr_len(dev));
skb->dev = dev;
skb->protocol = htons(ETH_P_ARP);
if (src_hw == NULL)
src_hw = dev->dev_addr;
if (dest_hw == NULL)
dest_hw = dev->broadcast;
/*
* Fill the device header for the ARP frame
*/
if (dev_hard_header(skb, dev, ptype, dest_hw, src_hw, skb->len) < 0)
goto out;
/*
* Fill out the arp protocol part.
*
* The arp hardware type should match the device type, except for FDDI,
* which (according to RFC 1390) should always equal 1 (Ethernet).
*/
/*
* Exceptions everywhere. AX.25 uses the AX.25 PID value not the
* DIX code for the protocol. Make these device structure fields.
*/
switch (dev->type) {
default:
arp->ar_hrd = htons(dev->type);
arp->ar_pro = htons(ETH_P_IP);
break;
#if defined(CONFIG_AX25) || defined(CONFIG_AX25_MODULE)
case ARPHRD_AX25:
arp->ar_hrd = htons(ARPHRD_AX25);
arp->ar_pro = htons(AX25_P_IP);
break;
#if defined(CONFIG_NETROM) || defined(CONFIG_NETROM_MODULE)
case ARPHRD_NETROM:
arp->ar_hrd = htons(ARPHRD_NETROM);
arp->ar_pro = htons(AX25_P_IP);
break;
#endif
#endif
#if defined(CONFIG_FDDI) || defined(CONFIG_FDDI_MODULE)
case ARPHRD_FDDI:
arp->ar_hrd = htons(ARPHRD_ETHER);
arp->ar_pro = htons(ETH_P_IP);
break;
#endif
#if defined(CONFIG_TR) || defined(CONFIG_TR_MODULE)
case ARPHRD_IEEE802_TR:
arp->ar_hrd = htons(ARPHRD_IEEE802);
arp->ar_pro = htons(ETH_P_IP);
break;
#endif
}
arp->ar_hln = dev->addr_len;
arp->ar_pln = 4;
arp->ar_op = htons(type);
arp_ptr=(unsigned char *)(arp+1);
memcpy(arp_ptr, src_hw, dev->addr_len);
arp_ptr += dev->addr_len;
memcpy(arp_ptr, &src_ip, 4);
arp_ptr += 4;
if (target_hw != NULL)
memcpy(arp_ptr, target_hw, dev->addr_len);
else
memset(arp_ptr, 0, dev->addr_len);
arp_ptr += dev->addr_len;
memcpy(arp_ptr, &dest_ip, 4);
return skb;
out:
kfree_skb(skb);
return NULL;
}
/*
* Send an arp packet.
*/
void arp_xmit(struct sk_buff *skb)
{
/* Send it off, maybe filter it using firewalling first. */
NF_HOOK(NFPROTO_ARP, NF_ARP_OUT, skb, NULL, skb->dev, dev_queue_xmit);
}
/*
* Create and send an arp packet.
*/
void arp_send(int type, int ptype, __be32 dest_ip,
struct net_device *dev, __be32 src_ip,
const unsigned char *dest_hw, const unsigned char *src_hw,
const unsigned char *target_hw)
{
struct sk_buff *skb;
/*
* No arp on this interface.
*/
if (dev->flags&IFF_NOARP)
return;
skb = arp_create(type, ptype, dest_ip, dev, src_ip,
dest_hw, src_hw, target_hw);
if (skb == NULL) {
return;
}
arp_xmit(skb);
}
/*
* Process an arp request.
*/
//Õâ¸öÊÇÊÕµ½arpÇëÇóµÄʱºò¸øarpÓ¦´ðµÄʱºò»áµ÷ÓÃ
static int arp_process(struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
struct in_device *in_dev = in_dev_get(dev);
struct arphdr *arp;
unsigned char *arp_ptr;
struct rtable *rt;
unsigned char *sha;
__be32 sip, tip;
u16 dev_type = dev->type;
int addr_type;
struct neighbour *n;
struct net *net = dev_net(dev);
/* arp_rcv below verifies the ARP header and verifies the device
* is ARP'able.
*/
if (in_dev == NULL)
goto out;
arp = arp_hdr(skb);
switch (dev_type) {
default:
if (arp->ar_pro != htons(ETH_P_IP) ||
htons(dev_type) != arp->ar_hrd)
goto out;
break;
case ARPHRD_ETHER:
case ARPHRD_IEEE802_TR:
case ARPHRD_FDDI:
case ARPHRD_IEEE802:
/*
* ETHERNET, Token Ring and Fibre Channel (which are IEEE 802
* devices, according to RFC 2625) devices will accept ARP
* hardware types of either 1 (Ethernet) or 6 (IEEE 802.2).
* This is the case also of FDDI, where the RFC 1390 says that
* FDDI devices should accept ARP hardware of (1) Ethernet,
* however, to be more robust, we'll accept both 1 (Ethernet)
* or 6 (IEEE 802.2)
*/
if ((arp->ar_hrd != htons(ARPHRD_ETHER) &&
arp->ar_hrd != htons(ARPHRD_IEEE802)) ||
arp->ar_pro != htons(ETH_P_IP))
goto out;
break;
case ARPHRD_AX25:
if (arp->ar_pro != htons(AX25_P_IP) ||
arp->ar_hrd != htons(ARPHRD_AX25))
goto out;
break;
case ARPHRD_NETROM:
if (arp->ar_pro != htons(AX25_P_IP) ||
arp->ar_hrd != htons(ARPHRD_NETROM))
goto out;
break;
}
/* Understand only these message types */
if (arp->ar_op != htons(ARPOP_REPLY) &&
arp->ar_op != htons(ARPOP_REQUEST))
goto out;
/*
* Extract fields
*/
arp_ptr= (unsigned char *)(arp+1);
sha = arp_ptr;
arp_ptr += dev->addr_len;
memcpy(&sip, arp_ptr, 4);
arp_ptr += 4;
arp_ptr += dev->addr_len;
memcpy(&tip, arp_ptr, 4);
/*
* Check for bad requests for 127.x.x.x and requests for multicast
* addresses. If this is one such, delete it.
*/
if (ipv4_is_loopback(tip) || ipv4_is_multicast(tip))
goto out;
/*
* Special case: We must set Frame Relay source Q.922 address
*/
if (dev_type == ARPHRD_DLCI)
sha = dev->broadcast;
/*
* Process entry. The idea here is we want to send a reply if it is a
* request for us or if it is a request for someone else that we hold
* a proxy for. We want to add an entry to our cache if it is a reply
* to us or if it is a request for our address.
* (The assumption for this last is that if someone is requesting our
* address, they are probably intending to talk to us, so it saves time
* if we cache their address. Their address is also probably not in
* our cache, since ours is not in their cache.)
*
* Putting this another way, we only care about replies if they are to
* us, in which case we add them to the cache. For requests, we care
* about those for us and those for our proxies. We reply to both,
* and in the case of requests for us we add the requester to the arp
* cache.
*/
/* Special case: IPv4 duplicate address detection packet (RFC2131) */
if (sip == 0) {
if (arp->ar_op == htons(ARPOP_REQUEST) &&
inet_addr_type(net, tip) == RTN_LOCAL &&
!arp_ignore(in_dev, sip, tip))
arp_send(ARPOP_REPLY, ETH_P_ARP, sip, dev, tip, sha,
dev->dev_addr, sha);
goto out;
}
if (arp->ar_op == htons(ARPOP_REQUEST) &&
ip_route_input_noref(skb, tip, sip, 0, dev) == 0) {
rt = skb_rtable(skb);
addr_type = rt->rt_type;
if (addr_type == RTN_LOCAL) {
int dont_send = 0;
if (!dont_send)
dont_send |= arp_ignore(in_dev,sip,tip);
if (!dont_send && IN_DEV_ARPFILTER(in_dev))
dont_send |= arp_filter(sip,tip,dev);
if (!dont_send) {
n = neigh_event_ns(&arp_tbl, sha, &sip, dev);
if (n) {
arp_send(ARPOP_REPLY,ETH_P_ARP,sip,dev,tip,sha,dev->dev_addr,sha);
neigh_release(n);
}
}
goto out;
} else if (IN_DEV_FORWARD(in_dev)) {
if (addr_type == RTN_UNICAST &&
(arp_fwd_proxy(in_dev, dev, rt) ||
arp_fwd_pvlan(in_dev, dev, rt, sip, tip) ||
pneigh_lookup(&arp_tbl, net, &tip, dev, 0)))
{
n = neigh_event_ns(&arp_tbl, sha, &sip, dev);
if (n)
neigh_release(n);
if (NEIGH_CB(skb)->flags & LOCALLY_ENQUEUED ||
skb->pkt_type == PACKET_HOST ||
in_dev->arp_parms->proxy_delay == 0) {
arp_send(ARPOP_REPLY,ETH_P_ARP,sip,dev,tip,sha,dev->dev_addr,sha);
} else {
pneigh_enqueue(&arp_tbl, in_dev->arp_parms, skb);
in_dev_put(in_dev);
return 0;
}
goto out;
}
}
}
/* Update our ARP tables */
n = __neigh_lookup(&arp_tbl, &sip, dev, 0);
if (IPV4_DEVCONF_ALL(dev_net(dev), ARP_ACCEPT)) {
/* Unsolicited ARP is not accepted by default.
It is possible, that this option should be enabled for some
devices (strip is candidate)
*/
if (n == NULL &&
(arp->ar_op == htons(ARPOP_REPLY) ||
(arp->ar_op == htons(ARPOP_REQUEST) && tip == sip)) &&
inet_addr_type(net, sip) == RTN_UNICAST)
n = __neigh_lookup(&arp_tbl, &sip, dev, 1);
}
if (n) {
int state = NUD_REACHABLE;
int override;
/* If several different ARP replies follows back-to-back,
use the FIRST one. It is possible, if several proxy
agents are active. Taking the first reply prevents
arp trashing and chooses the fastest router.
*/
override = time_after(jiffies, n->updated + n->parms->locktime);
/* Broadcast replies and request packets
do not assert neighbour reachability.
*/
if (arp->ar_op != htons(ARPOP_REPLY) ||
skb->pkt_type != PACKET_HOST)
state = NUD_STALE;
neigh_update(n, sha, state, override ? NEIGH_UPDATE_F_OVERRIDE : 0);
neigh_release(n);
}
out:
if (in_dev)
in_dev_put(in_dev);
consume_skb(skb);
return 0;
}
static void parp_redo(struct sk_buff *skb)
{
arp_process(skb);
}
/*
* Receive an arp request from the device layer.
*/
static int arp_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct arphdr *arp;
/* ARP header, plus 2 device addresses, plus 2 IP addresses. */
if (!pskb_may_pull(skb, arp_hdr_len(dev)))
goto freeskb;
arp = arp_hdr(skb);
if (arp->ar_hln != dev->addr_len ||
dev->flags & IFF_NOARP ||
skb->pkt_type == PACKET_OTHERHOST ||
skb->pkt_type == PACKET_LOOPBACK ||
arp->ar_pln != 4)
goto freeskb;
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
goto out_of_mem;
memset(NEIGH_CB(skb), 0, sizeof(struct neighbour_cb));
return NF_HOOK(NFPROTO_ARP, NF_ARP_IN, skb, dev, NULL, arp_process);
freeskb:
kfree_skb(skb);
out_of_mem:
return 0;
}
/*
* User level interface (ioctl)
*/
/*
* Set (create) an ARP cache entry.
*/
static int arp_req_set_proxy(struct net *net, struct net_device *dev, int on)
{
if (dev == NULL) {
IPV4_DEVCONF_ALL(net, PROXY_ARP) = on;
return 0;
}
if (__in_dev_get_rtnl(dev)) {
IN_DEV_CONF_SET(__in_dev_get_rtnl(dev), PROXY_ARP, on);
return 0;
}
return -ENXIO;
}
static int arp_req_set_public(struct net *net, struct arpreq *r,
struct net_device *dev)
{
__be32 ip = ((struct sockaddr_in *)&r->arp_pa)->sin_addr.s_addr;
__be32 mask = ((struct sockaddr_in *)&r->arp_netmask)->sin_addr.s_addr;
if (mask && mask != htonl(0xFFFFFFFF))
return -EINVAL;
if (!dev && (r->arp_flags & ATF_COM)) {
dev = dev_getbyhwaddr(net, r->arp_ha.sa_family,
r->arp_ha.sa_data);
if (!dev)
return -ENODEV;
}
if (mask) {
if (pneigh_lookup(&arp_tbl, net, &ip, dev, 1) == NULL)
return -ENOBUFS;
return 0;
}
return arp_req_set_proxy(net, dev, 1);
}
static int arp_req_set(struct net *net, struct arpreq *r,
struct net_device * dev)
{
__be32 ip;
struct neighbour *neigh;
int err;
if (r->arp_flags & ATF_PUBL)
return arp_req_set_public(net, r, dev);
ip = ((struct sockaddr_in *)&r->arp_pa)->sin_addr.s_addr;
if (r->arp_flags & ATF_PERM)
r->arp_flags |= ATF_COM;
if (dev == NULL) {
struct flowi fl = { .nl_u = { .ip4_u = { .daddr = ip,
.tos = RTO_ONLINK } } };
struct rtable * rt;
if ((err = ip_route_output_key(net, &rt, &fl)) != 0)
return err;
dev = rt->u.dst.dev;
ip_rt_put(rt);
if (!dev)
return -EINVAL;
}
switch (dev->type) {
#if defined(CONFIG_FDDI) || defined(CONFIG_FDDI_MODULE)
case ARPHRD_FDDI:
/*
* According to RFC 1390, FDDI devices should accept ARP
* hardware types of 1 (Ethernet). However, to be more
* robust, we'll accept hardware types of either 1 (Ethernet)
* or 6 (IEEE 802.2).
*/
if (r->arp_ha.sa_family != ARPHRD_FDDI &&
r->arp_ha.sa_family != ARPHRD_ETHER &&
r->arp_ha.sa_family != ARPHRD_IEEE802)
return -EINVAL;
break;
#endif
default:
if (r->arp_ha.sa_family != dev->type)
return -EINVAL;
break;
}
neigh = __neigh_lookup_errno(&arp_tbl, &ip, dev);
err = PTR_ERR(neigh);
if (!IS_ERR(neigh)) {
unsigned state = NUD_STALE;
if (r->arp_flags & ATF_PERM)
state = NUD_PERMANENT;
err = neigh_update(neigh, (r->arp_flags&ATF_COM) ?
r->arp_ha.sa_data : NULL, state,
NEIGH_UPDATE_F_OVERRIDE|
NEIGH_UPDATE_F_ADMIN);
neigh_release(neigh);
}
return err;
}
static unsigned arp_state_to_flags(struct neighbour *neigh)
{
unsigned flags = 0;
if (neigh->nud_state&NUD_PERMANENT)
flags = ATF_PERM|ATF_COM;
else if (neigh->nud_state&NUD_VALID)
flags = ATF_COM;
return flags;
}
/*
* Get an ARP cache entry.
*/
static int arp_req_get(struct arpreq *r, struct net_device *dev)
{
__be32 ip = ((struct sockaddr_in *) &r->arp_pa)->sin_addr.s_addr;
struct neighbour *neigh;
int err = -ENXIO;
neigh = neigh_lookup(&arp_tbl, &ip, dev);
if (neigh) {
read_lock_bh(&neigh->lock);
memcpy(r->arp_ha.sa_data, neigh->ha, dev->addr_len);
r->arp_flags = arp_state_to_flags(neigh);
read_unlock_bh(&neigh->lock);
r->arp_ha.sa_family = dev->type;
strlcpy(r->arp_dev, dev->name, sizeof(r->arp_dev));
neigh_release(neigh);
err = 0;
}
return err;
}
static int arp_req_delete_public(struct net *net, struct arpreq *r,
struct net_device *dev)
{
__be32 ip = ((struct sockaddr_in *) &r->arp_pa)->sin_addr.s_addr;
__be32 mask = ((struct sockaddr_in *)&r->arp_netmask)->sin_addr.s_addr;
if (mask == htonl(0xFFFFFFFF))
return pneigh_delete(&arp_tbl, net, &ip, dev);
if (mask)
return -EINVAL;
return arp_req_set_proxy(net, dev, 0);
}
static int arp_req_delete(struct net *net, struct arpreq *r,
struct net_device * dev)
{
int err;
__be32 ip;
struct neighbour *neigh;
if (r->arp_flags & ATF_PUBL)
return arp_req_delete_public(net, r, dev);
ip = ((struct sockaddr_in *)&r->arp_pa)->sin_addr.s_addr;
if (dev == NULL) {
struct flowi fl = { .nl_u = { .ip4_u = { .daddr = ip,
.tos = RTO_ONLINK } } };
struct rtable * rt;
if ((err = ip_route_output_key(net, &rt, &fl)) != 0)
return err;
dev = rt->u.dst.dev;
ip_rt_put(rt);
if (!dev)
return -EINVAL;
}
err = -ENXIO;
neigh = neigh_lookup(&arp_tbl, &ip, dev);
if (neigh) {
if (neigh->nud_state&~NUD_NOARP)
err = neigh_update(neigh, NULL, NUD_FAILED,
NEIGH_UPDATE_F_OVERRIDE|
NEIGH_UPDATE_F_ADMIN);
neigh_release(neigh);
}
return err;
}
/*
* Handle an ARP layer I/O control request.
*/
int arp_ioctl(struct net *net, unsigned int cmd, void __user *arg)
{
int err;
struct arpreq r;
struct net_device *dev = NULL;
switch (cmd) {
case SIOCDARP:
case SIOCSARP:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
case SIOCGARP:
err = copy_from_user(&r, arg, sizeof(struct arpreq));
if (err)
return -EFAULT;
break;
default:
return -EINVAL;
}
if (r.arp_pa.sa_family != AF_INET)
return -EPFNOSUPPORT;
if (!(r.arp_flags & ATF_PUBL) &&
(r.arp_flags & (ATF_NETMASK|ATF_DONTPUB)))
return -EINVAL;
if (!(r.arp_flags & ATF_NETMASK))
((struct sockaddr_in *)&r.arp_netmask)->sin_addr.s_addr =
htonl(0xFFFFFFFFUL);
rtnl_lock();
if (r.arp_dev[0]) {
err = -ENODEV;
if ((dev = __dev_get_by_name(net, r.arp_dev)) == NULL)
goto out;
/* Mmmm... It is wrong... ARPHRD_NETROM==0 */
if (!r.arp_ha.sa_family)
r.arp_ha.sa_family = dev->type;
err = -EINVAL;
if ((r.arp_flags & ATF_COM) && r.arp_ha.sa_family != dev->type)
goto out;
} else if (cmd == SIOCGARP) {
err = -ENODEV;
goto out;
}
switch (cmd) {
case SIOCDARP:
err = arp_req_delete(net, &r, dev);
break;
case SIOCSARP:
err = arp_req_set(net, &r, dev);
break;
case SIOCGARP:
err = arp_req_get(&r, dev);
if (!err && copy_to_user(arg, &r, sizeof(r)))
err = -EFAULT;
break;
}
out:
rtnl_unlock();
return err;
}
static int arp_netdev_event(struct notifier_block *this, unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
switch (event) {
case NETDEV_CHANGEADDR:
neigh_changeaddr(&arp_tbl, dev);
rt_cache_flush(dev_net(dev), 0);
break;
default:
break;
}
return NOTIFY_DONE;
}
static struct notifier_block arp_netdev_notifier = {
.notifier_call = arp_netdev_event,
};
/* Note, that it is not on notifier chain.
It is necessary, that this routine was called after route cache will be
flushed.
*/
void arp_ifdown(struct net_device *dev)
{
neigh_ifdown(&arp_tbl, dev);
}
/*
* Called once on startup.
*/
static struct packet_type arp_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_ARP),
.func = arp_rcv,
};
static int arp_proc_init(void);
void __init arp_init(void)
{
neigh_table_init(&arp_tbl);
dev_add_pack(&arp_packet_type);
arp_proc_init();
#ifdef CONFIG_SYSCTL
neigh_sysctl_register(NULL, &arp_tbl.parms, "ipv4", NULL);
#endif
register_netdevice_notifier(&arp_netdev_notifier);
}
#ifdef CONFIG_PROC_FS
#if defined(CONFIG_AX25) || defined(CONFIG_AX25_MODULE)
/* ------------------------------------------------------------------------ */
/*
* ax25 -> ASCII conversion
*/
static char *ax2asc2(ax25_address *a, char *buf)
{
char c, *s;
int n;
for (n = 0, s = buf; n < 6; n++) {
c = (a->ax25_call[n] >> 1) & 0x7F;
if (c != ' ') *s++ = c;
}
*s++ = '-';
if ((n = ((a->ax25_call[6] >> 1) & 0x0F)) > 9) {
*s++ = '1';
n -= 10;
}
*s++ = n + '0';
*s++ = '\0';
if (*buf == '\0' || *buf == '-')
return "*";
return buf;
}
#endif /* CONFIG_AX25 */
#define HBUFFERLEN 30
static void arp_format_neigh_entry(struct seq_file *seq,
struct neighbour *n)
{
char hbuffer[HBUFFERLEN];
int k, j;
char tbuf[16];
struct net_device *dev = n->dev;
int hatype = dev->type;
read_lock(&n->lock);
/* Convert hardware address to XX:XX:XX:XX ... form. */
#if defined(CONFIG_AX25) || defined(CONFIG_AX25_MODULE)
if (hatype == ARPHRD_AX25 || hatype == ARPHRD_NETROM)
ax2asc2((ax25_address *)n->ha, hbuffer);
else {
#endif
for (k = 0, j = 0; k < HBUFFERLEN - 3 && j < dev->addr_len; j++) {
hbuffer[k++] = hex_asc_hi(n->ha[j]);
hbuffer[k++] = hex_asc_lo(n->ha[j]);
hbuffer[k++] = ':';
}
if (k != 0)
--k;
hbuffer[k] = 0;
#if defined(CONFIG_AX25) || defined(CONFIG_AX25_MODULE)
}
#endif
sprintf(tbuf, "%pI4", n->primary_key);
seq_printf(seq, "%-16s 0x%-10x0x%-10x%s * %s\n",
tbuf, hatype, arp_state_to_flags(n), hbuffer, dev->name);
read_unlock(&n->lock);
}
static void arp_format_pneigh_entry(struct seq_file *seq,
struct pneigh_entry *n)
{
struct net_device *dev = n->dev;
int hatype = dev ? dev->type : 0;
char tbuf[16];
sprintf(tbuf, "%pI4", n->key);
seq_printf(seq, "%-16s 0x%-10x0x%-10x%s * %s\n",
tbuf, hatype, ATF_PUBL | ATF_PERM, "00:00:00:00:00:00",
dev ? dev->name : "*");
}
static int arp_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN) {
seq_puts(seq, "IP address HW type Flags "
"HW address Mask Device\n");
} else {
struct neigh_seq_state *state = seq->private;
if (state->flags & NEIGH_SEQ_IS_PNEIGH)
arp_format_pneigh_entry(seq, v);
else
arp_format_neigh_entry(seq, v);
}
return 0;
}
static void *arp_seq_start(struct seq_file *seq, loff_t *pos)
{
/* Don't want to confuse "arp -a" w/ magic entries,
* so we tell the generic iterator to skip NUD_NOARP.
*/
return neigh_seq_start(seq, pos, &arp_tbl, NEIGH_SEQ_SKIP_NOARP);
}
/* ------------------------------------------------------------------------ */
static const struct seq_operations arp_seq_ops = {
.start = arp_seq_start,
.next = neigh_seq_next,
.stop = neigh_seq_stop,
.show = arp_seq_show,
};
static int arp_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &arp_seq_ops,
sizeof(struct neigh_seq_state));
}
static const struct file_operations arp_seq_fops = {
.owner = THIS_MODULE,
.open = arp_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static int __net_init arp_net_init(struct net *net)
{
if (!proc_net_fops_create(net, "arp", S_IRUGO, &arp_seq_fops))
return -ENOMEM;
return 0;
}
static void __net_exit arp_net_exit(struct net *net)
{
proc_net_remove(net, "arp");
}
static struct pernet_operations arp_net_ops = {
.init = arp_net_init,
.exit = arp_net_exit,
};
static int __init arp_proc_init(void)
{
return register_pernet_subsys(&arp_net_ops);
}
#else /* CONFIG_PROC_FS */
static int __init arp_proc_init(void)
{
return 0;
}
#endif /* CONFIG_PROC_FS */
EXPORT_SYMBOL(arp_broken_ops);
EXPORT_SYMBOL(arp_find);
EXPORT_SYMBOL(arp_create);
EXPORT_SYMBOL(arp_xmit);
EXPORT_SYMBOL(arp_send);
EXPORT_SYMBOL(arp_tbl);
#if defined(CONFIG_ATM_CLIP) || defined(CONFIG_ATM_CLIP_MODULE)
EXPORT_SYMBOL(clip_tbl_hook);
#endif
|
gpl-3.0
|
ndlib/annex-ims
|
db/migrate/20150428155251_create_issues.rb
|
418
|
class CreateIssues < ActiveRecord::Migration[4.2]
def change
create_table :issues do |t|
t.references :user, null: false, index: true, foreign_key: true
t.string :barcode, null: false
t.text :message, null: false
t.integer :resolver_id, index: true
t.timestamp :resolved_at
t.timestamps null: false
end
add_foreign_key :issues, :users, column: :resolver_id
end
end
|
gpl-3.0
|
CARLORION/PrincipiosSOLID
|
EP.SOLID/5 - DIP/DIP.Solucao/Cliente.cs
|
794
|
using System;
using EP.SOLID.DIP.Solucao.Interfaces;
namespace EP.SOLID.DIP.Solucao
{
public class Cliente
{
private readonly ICPFServices _cpfServices;
private readonly IEmailServices _emailServices;
public Cliente(
ICPFServices cpfServices,
IEmailServices emailServices)
{
_cpfServices = cpfServices;
_emailServices = emailServices;
}
public int ClienteId { get; set; }
public string Nome { get; set; }
public string Email { get; set; }
public string CPF { get; set; }
public DateTime DataCadastro { get; set; }
public bool IsValid()
{
return _emailServices.IsValid(Email) && _cpfServices.IsValid(CPF);
}
}
}
|
gpl-3.0
|
InstantKhabar/_source
|
_source/news/28840-lucknow.html
|
2567
|
---
title: "ड्राइविंग लाइसेन्स के लिए अब आॅनलाइन टेस्ट"
layout: item
category: lucknow
date: 2016-01-25T16:02:23.000Z
image: 982bdf702e4bc1a6bc3b244c562f0044.jpg
---
<p style="text-align: justify;">लखनऊ: उत्तर प्रदेश के परिवहन राज्य मंत्री (स्वतंत्र प्रभार) यासर शाह के निर्देशानुसार परिवहन विभाग अपने सम्भागीय परिवहन कार्यालय ट्रांसपोर्ट नगर, लखनऊ में 27 जनवरी, 2016 से लर्निंग ड्राइविंग लाइसेन्स (डी0एल0) बनवाने वाले आवेदकों का आॅनलाइन परीक्षा लेगा। लर्निंग ड्राइविंग लाइसेन्स के लिए आवेदकों को सम्भागीय परिवहन कार्यालय में स्थापित लैब में कम्प्यूटर पर टेस्ट देना होगा। आवेदकों को हिन्दी व अंग्रेजी में टेस्ट देने की सुविधा होगी। </p>
<p style="text-align: justify;">15 मिनट की आॅनलाइन परीक्षा में 15 बहुविकल्पीय प्रश्न यातायात के नियम तथा यातायात चिन्ह से पूंछे जायेंगे। इसमें से 09 प्रश्नों का सही जवाब देने वाले आवेदकों को लर्निंग ड्राइविंग लाइसेन्स जारी किया जाएगा तथा फेल होने वाले आवेदकों को दोबारा परीक्षा देनी होगी।</p>
<p style="text-align: justify;">परिवहन राज्य मंत्री श्री यासर शाह 27 जनवरी, 2016 को पूर्वांह 11ः00 बजे कम्प्यूटर आधारित इस आॅनलाइन परीक्षा प्रणाली का उद्घाटन सम्भागीय परिवहन कार्यालय में करेंगे।</p>
|
gpl-3.0
|
rivasd/djPsych
|
djreceive/migrations/0025_auto_20170201_1516.py
|
1227
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-02-01 20:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('djreceive', '0024_auto_20170131_1732'),
]
operations = [
migrations.RemoveField(
model_name='audioabxtrial',
name='result',
),
migrations.AddField(
model_name='audioabxtrial',
name='A',
field=models.CharField(max_length=1024, null=True),
),
migrations.AddField(
model_name='audioabxtrial',
name='B',
field=models.CharField(max_length=1024, null=True),
),
migrations.AddField(
model_name='audioabxtrial',
name='X',
field=models.CharField(max_length=1024, null=True),
),
migrations.AddField(
model_name='audioabxtrial',
name='correct',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='audioabxtrial',
name='key_press',
field=models.IntegerField(null=True),
),
]
|
gpl-3.0
|
LennonLab/Micro-Encounter
|
model/ODD/ODD_Protocol.md
|
27629
|
# Model description following the ODD Protocol
The ODD protocol is an accepted standard for describing individual-based models (IBMs), Grimm et al. 2006. ODD stands for Overview, Design concepts, and Details. Here, we descibe our IBM framework according to the ODD protocol.
## PURPOSE
Our modeling platform simulates the life history of individual organisms and their encounters with resource particles under varying degrees of ecological complexity to explore and understand the emergence of microbial seed banks. Additionally, our platform provides a individual-based simulation framework for how understanding how microscale properties (e.g., encounter rates) and macroscale properties (e.g., resource concentration) differentially influence the emergence of seed banks and the growth and activity dynamics of communities. The models produced by our platform simulate dimensions of complexity in space, resources, and trophic interactions and include large degrees of variation in model parameters and ecological processes. The resulting complexity also results in realistic life history trade-offs emerging from combinations of randomly chosen trait values.
## ENTITIES
###Individual organisms
Individuals are distinguished by collections of elements within lists. Individuals undergo changes when randomly sampled from these lists. Each specific position in each list corresponds to the same individual. For example, in simulating growth, a model will choose a random position from the list of cell quotas. The first position in this list as well in other lists corresponds to the same individual.
Example:
IndIDs = [1, 2, 33, 14]
CellQuotas = [0.1, 0.99, 0.14, 0.05]
IndX = [45, 23, 456, 1]
IndY = [765, 87, 21, 34]
The individual with ID of 1 has a cell quota of 0.1 and is located at position x=45, y=765
These are the lists of attributes for individual organisms:
* time each individual spends in the system
* species ID
* individual ID
* 2D spatial location
* endogenous level of a single primary limiting resource (i.e., cell quota)
* species-specific:
* metabolic maintenance cost
* maximum dispersal rate
* maximum growth rate
* resource use efficiency
* environmental optima
* individual-level (varies as a normally distributed random variable with the specific-specific value as the mean):
* metabolic maintenance cost
* maximum dispersal rate
* maximum growth rate
* resource use efficiency
* products of individual-level metabolism
###Species
Each species is characterized by the individuals that share a common set of traits, such as maximum growth rate and environmental optima. Species information is stored in Python dictionaries. In this way, if simplex requires the species ID of an individual it will access the species ID list where each element corresponds to a specific individual. But, if simplex requires the maximum growth rate for an individual, then it finds the species ID and then uses that to access the Python dictionary for maximum specific growth rates of species.
Example:
IndIDs = [1, 2, 33, 14]
spIDs = [12, 32, 11, 6]
MaxGrowthDict = {12: 0.9, 32: 0.5, 11: 0.8, 6: 0.4}
The individual with ID of 1 belongs to species 12, which has a
theoretical maximum growth rate of 0.9.
The following are the types of species-level information that are stored in Python dictionaries:
* metabolic maintenance cost
* maximum dispersal rate
* maximum theoretical growth rate
* resource use efficiency for each resource
* environmental optima
###Resources
Resources are simulated at two levels (molecules, particles). Resource particles are designated as 'a', 'b', or 'c'. Particles are then joined together to form molecules (e.g., 'aaaa'). Depending on the model, chemical complexity is simulated by introducing bonds (e.g., '-') that must be broken in order to consume resource particles (e.g., 'aa-aa'). The breaking of these bonds is done via random draws of positions along the molecule, where for example an 'aa-aa' is less likely to be split than is an 'a-a-a-a' particle.
Depending on the model, resource molecules can enter the system in clusters. The degree of spatial aggregation of incoming resource molecules is determined by a 2-dimensional Gaussian distribution, where the standard deviation (dispersion) is chosen at random at the start of the model and the mean (x-y position) is chosen at random at each time point.
Each molecule or resource particle is distinguished by information stored in lists, where each position in each list corresponds to the same molecule or independent particle.
Example:
resIDs = ['a', 'bb', 'aaaa', 'b']
Xpos = [5.6, 3.4, 5.67, 2.0]
Ypos = [8.76, 9.8, 3.2, 4.5]
The particle with ID of 0 is 'a' and is
located at position x=5.6, y=8.76
The following are the types of information stored about each resource (molecule, particle):
* time in the system
* resource type: a, b, c, or d
* size and complexity, e.g., 'a', 'bb', 'cc-cc'
* 2D spatial location
###Physcial barriers
These objects are simulated as discrete 2D spatial coordinates that cannot be occupied by any individual entities. The number, size, and location of physical barriers are chosen at random at the start of each model.
## SYSTEM STATE VARIABLES
Each run of an IBM begins with random choices for the values of:
* width (5 to 20)
* height (5 to 20)
* basal flow rate (1.0 to 0.0)
* number, size, and location of physical barriers
* number and direction of environmental gradients
* rate of stochastic fluctuation in basal flow rate
* degree of stochastic fluctuation
* degree of syncronized flow of individual particles
* completely in-sync or completely out of sync
For example:
from randparams.py:
width = randint(5,100)
height = randint(5,100)
# number of barriers
barriers = randint(1,10)
# log-series alpha for metacommunity structure
alpha = np.random.uniform(0.99, 0.999)
reproduction = choice(['fission', 'sexual'])
speciation = choice(['yes', 'no'])
# size of starting community
seedCom = choice([10, 100, 1000])
# m = probability of immigration
m = choice([0.0, 0.0001, 0.0005, 0.001, 0.005])
...
## SPATIAL AND TEMPORAL SCALE
The two general aspects of scale are grain (a.k.a. resolution) and extent (e.g. total area).
###Spatial extent
The environment of the IBMs is two dimensional and can vary along each axis from 5 to 20 discrete units. This makes for a potential total extent of 25 to 10,000 discrete patches, each with a grain of 1 square unit.
Note that all individuals and/or resources move in decimal units the limit of which is determined by Python's decimal precision. This means that individual particles can occupy practically infinite locations within patches and likewise, squeeze through barriers (which only occupy integer x-y coordinates).
###Temporal extent
Each IBM was run to a state of mean reversion in total abundance, that is, a point where the number of individuals in the system fluctuates around an average value. Greater detail is given under 'Process overview and scheduling'.
###Grain
Grain is the smallest unit over which change can happen. For example, as per the original ODD documentation: “One time step represents one year and simulations were run for 100 years.” In our IBMs, one time step represented a single generation.
## PROCESS OVERVIEW AND SCHEDULING
###Assembly
The user runs a core program (i.e., model.py) that chooses random values for system-level state variables including:
* Number of incoming resource molecules:
* 0 to 90 per time step
* Maximum specific growth rate:
* 10 - 50% of cell quota
* Maximum maintenance cost for individuals:
* 1 - 5% of cell quota
* Maximum specific dispersal rate:
* 1 to 10% of the environment
* Maximum specific resuscitation rate:
* probability of 0.1 - 1.0
* Maximum maintenance energy reduction factor:
* Going dormant can reduce maintenance energy between 20 and 100 times
* Incoming resource aggregation:
* Determined by the standard deviation of a Normal distribution (0.1 - 0.4)
The core program also decides at random whether fluid dynamics will occur and at what rate of flow.
###Core simulation and life history
The IBM begins to run immediately after assembly. After each iteration of resource inflow where varied number of molecules and particles enter the system, each individual is given the chance to consume, grow, reproduce, starve, die, and to disperse towards resources and environmental optima.
Our IBMs simulate these life history processes via random sampling. This simulates the partly probabilistic and partly deterministic nature of environmental filtering and individual-level interactions.
*Immigration*
Individuals enter from any point in the environment. Species identities of inflowing propagules are chosen at random from a uniform distribution. Along with a species ID and species-specific maximum rates of resource uptake, active dispersal, resource efficiencies, cell maintenance, an environmental optima, each propagule is given a unique ID and a starting cell quota that represents the state of internal resources. The cell quota also determines the chance of reproduction.
*Dispersal*
Our IBMs allow individuals to move towards resource particles. This happens by choosing a random sample of resource particles from the environment, and then moving the individual towards the nearest consumable resource particle at a rate determined by its cell quota and maximum dispersal rate.
*Consumption & growth*
Sampled individuals consume resources according to their species-specific maximum rates of uptake and grow according to species-specific resource efficiencies and maintenance costs. Uptake increases the individual cell quotas and decreases ambient resources. Individual cell quotas are then decreased according to a specific physiological maintenance cost. Likewise, faster rates of uptake incurred a larger energetic cost and hence, lower growth efficiency.
*Reproduction*
Reproduction is limited to asexual reproduction with the possibility of mutation. Individuals reproduce with a probability determined by the combination of mean cell quota and the proportional match to the environmental optima. The cell quota of each resource is evenly divided between the individual and its daughter. The daughter is given a unique individual ID and the species ID of its mother, but is allowed small mutations in individual-level life history parameters.
*Death*
Individuals sampled at random will die if their cell quota is equal to or less than maintenance energy.
*Emigration*
Emigration can result from fluid flow, from random spatial movement, or from active dispersal. Individuals and resource particles are considered to have left the local environment when they pass beyond the 2-dimensional edges.
###Duration: A run to mean reversion
Once assembled, each IBM simulates ecological processes (birth, death, dispersal, growth, consumption, etc.) until the system reaches a point of mean reversion, i.e., the tendency of a system to reverse a directional change. Mean reversion captures whether a system is fluctuating around a mean value. At each time point past 200 generations, the modeling program conducts an Augmented Dickey-Fuller (ADF) test on the previous 100 generations to determine whether a state of mean reversion has been reached. The ADF is well-explained here: https://www.quantstart.com/articles/Basics-of-Statistical-Mean-Reversion-Testing.
Once mean reversion is reached (p < 0.05), the model runs for an additional 100 generations and then stops. The following is then recorded for each model:
* Values of randomly chosen state variables:
* length
* width
*
* Mean and variance for:
* Total abundance, $N$
* Species richness, $S$
* Growth rate (per species & per capita)
* Maintenance cost (per species & per capita)
* Resource efficiency (per species & per capita)
* Active dispersal rate (per species & per capita)
* Compositional turnover
* Bray-Curtis
* Sorensen's
* Species turnover
* Whittaker's $\beta$
* Species evenness
* Smith and Wilson's evenness, $E_{var}$
* Simpson's evenness, $E_{1/D}$
* Species diversity
* Shannon's diversity, $H'$
* Simpson's diversity, $D_{1/D}$
* Dominance
* Absolute, $N_{max}$
* Relative, $N_{max}/N$
* Productivity
* In number of individuals
* In amount of cell quota
* Individual residence time, i.e., amount of time individuals spend in the system
These data are stored in file as csv files and can are directly imported into the Python environment via the scripts provided in the project repository: https://github.com/LennonLab/Micro-Encounter/tree/master/fig-scripts
Unless the number of desired models has been reached, the IBM framework simply constructs another model and runs it to mean reversion.
## INITIALIZATION AND INPUTS
###Initialization
The model initiates with a random set of values for state-variables, 100 individuals whose species IDs are drawn at random from a uniform distribution. These values are saved, so that a simplex model could be programmed to replicate an analysis.
###Inputs
The modeling platform requires no input data other than those parameters that are chosen at random.
## DESIGN CONCEPTS
###Ecological complexity
Our IBM platform assembles models from random combinations of variables and processes to generate output data that allow the user to test the general influence of particular variables, processes, or dynamics.
*Spatial complexity*
Our IBMs simulate three levels of spatial complexity.
* White noise: Locations of individual organisms and resource molecules changed at each time step in an uncorrelated way. Hence, every organism and resource particle had the same chance of moving to any location within the environment at each time step in the model. This white-noise model created a well-mixed environment with no dispersal limitation.
* Aggregation and random walks: Resource molecules enter the environment in clusters. Individuals undergo random walks. The average length of the random walk was a species-specific parameter, and larger dispersal distances carried greater energetic costs. The degree of spatial dispersion among incoming resource clusters was chosen at random.
* Aggregation and chemotaxis: Resource molecules enter in clusters but individuals were capable of sensing resource molecules based on resource density and distance.
*Trophic complexity*
Our IBMs simulate four levels of trophic complexity, with the last being a combination of two others.
* The first level had only one trophic interaction, which we refer to as a simple "consumer-resource" model. At this level of trophic complexity, all individuals were solely consumers of inflowing resources.
* The second level of trophic complexity allowed for the consumption of resources contained in dead bacteria (e.g., Rozen et al., 2009), which is a trophic interaction that we referred to as "scavenging".
* The third level of trophic complexity simulated a situation in which one group of consumer species generated a metabolic byproduct that could be taken up by a second group of consumer species, which in turn generated a byproduct that served as a resource for a third group of species. This situation was meant to simulate conditions that are characteristic of cross-feeding or syntrophy (Pande et al., 2015). A final level of trophic complexity was characterized by a combination scavenging and cross-feeding, which we saw as more ecologically realistic and complex than scavenging or cross-feeding alone.
*Resource complexity*
Our IBMs simulate three levels of resource complexity.
* Monoculture: The simplest condition wherein only one type of resource molecule was supplied. These molecules had no chemical complexity and could be consumed without extracellular enzymatic breakdown (Figure 1). Resource molecules were represented by strings of individual particles (e.g., ‘aaaa’) that could be broken down from each end when encountered by organisms. The number, size, and dispersion of resource molecules were chosen at random (Table 1).
* Polyculture: The second level supplied three different types of resources (e.g., ‘aaaa’, ‘bbbb’, ‘cccc’) that could only be used by a specialist consumer (Figure 1).
* Lock and key: Simulates the structural complexity of resource molecules, i.e., chemical complexity. Consumers must break down resource molecules at specific locations. For example, a molecule would have a hyphen that simulates a chemical bond separating two groups of resource particles (e.g., ‘aaaa-aaaa’). In order to consume a resource particle, i.e., ‘a’, individuals would need to cleave the ‘aaaa-aaaa’ molecule at the bond and then consume an ‘a’ from one of the two resulting ‘aaaa’ molecules. Because molecules are cleaved at random locations, there is a 1/9 chance of cleaving the ‘aaaa-aaaa’ particle and, likewise, a 1/5 chance of cleaving a ‘bb-bb’ particle, and a 2/8 chance of cleaving a ‘bb-bb-bb’ particle (Figure 1). Therefore, a molecule with a proportionately larger number of bonds requires greater time, and hence, energy to break down.
_Note:_ The average total number of individual resource particles (e.g., ‘a’, ‘b’, ‘c’) entering the system at a given time and inflow rate was made to be consistent across levels of resource complexity.
###Nutrient limited growth
Individual growth and activity is fueled and limited by resources. Individuals cannot grow in the absence of resources. Without resources, individuals eventually go dormant or die.
###Energetic costs
All life history processes impose an energetic cost that is manifested as a reduction in cell quota. In some cases these energetic costs are the results of multiplicative outcomes. For example, the energetic cost of actively dispering x units is the product of x and the energetic cost of moving a single unit.
###Emergence
Community- and ecosystem-level patterns emerge from the life history and competitive dynamics at the individual level. These dynamics likewise emerge from initially random combinations of species-specific vital rates (e.g. of growth, dispersal, resuscitation, etc.).
###Fluid dynamics
IBMs are chosen at random to simulate fluid and non-fluid dynamics. Our IBM framework uses the Lattice-Boltzmann Method (LBM) to simulate fluid flow. An LBM discretizes the environment into a lattice and attaches to each position in the lattice a number of particle densities and velocities for each of nine directions of movement possible in a 2D environment (N, S, E, W, NE, NW, SE, SW, current position).
###Ecological theory
Our IBM platform implicitly draws from multiple bodies of ecological theory.
*Life history theory*
Life history theory seeks to understand aspects of ontogeny, reproduction, life span, etc. as the result of natural selection. Trade-offs play a central role in life history theory, where investing in one trait (e.g., rapid growth) leads to a decrease in another (e.g., growth efficiency). There are several trade-offs that emerge within the models.
* Mobility vs. metabolic maintenance: Greater active dispersal allows organisms to find resources
* Growth rate vs. metabolic maintenance
* Generalist vs. specialist
* R vs. K selection
*Resource-limitation theory*
Proposes that growth-limiting resources are the primary determinants of competition and community structure. Our IBMs enforce resource limitation by making all biological processes dependent on levels of endogenous resources. Resources are the primary sources of inter- and intra-specific competition among individuals.
*Ecological niche theory*
Proposes that each ecological species has a unique range envirommental characteristics within which it can experience positive growth. The more similar the niche of two species, the more intense the competition is likely to be between them. While definitions of ecological niches and how to test niche theory has long been argued, the importance of the ecological niche is a central principle of ecological theory. Our IBMs inherently give each species an ecological niche by assigning each species an environmental optima, a specific resource to use which a subset of other species can also grow on, and unique combination of traits that produce life history trade-offs and differential success in specific environments.
*Ecological neutral theory and idiosyncrasy theory*
Our IBMs operate via random sampling and can vary from being completely neutral (all individuals having equal vital rates) to completely idiosyncratic (all individual and species are as different as possible). However, there is little chance that any given model will be 100% neutral or idiosyncratic. One aspect of neutral theory that our modeling adopts is the importance of stochastic life history processes. This process-based stochasticity is simulated via unweighted random draws among individuals. Once drawn from the community at random, individuals undergo life history processes according to probabilities that are effectively weighted by their cell quota and specific-specific vital rates.
###Hypotheses
We used the inherent ecological complexity of our modeling framework to test for robust ecological relationships related to our primary hypothesis that microscale properties of resource encounter rates have a stronger influence on growth, abundance, and activity than macroscale properties of resource inflow and concentration.
###Adaptation
Individuals can move towards their environmental optima. Populations can become aggregated in areas that provide favorable intersections of species optima. Species canevolve by the action of the environmental filter on subpopulation variation in state variables.
###Objectives
Individuals can seek conditions that match them to their environmental optima and can also seek to acquire resources through active searching, i.e., chemotaxis.
###Learning
There is no aspect of individual-based learning in our modeling framework.
###Prediction
Individuals do not have the ability to anticipate conditions.
###Sensing
In models that include chemotaxis, individuals can sense the proximity of usable resources. In models that include fluid dynamics, individuals can move against the direction of flow.
###Interaction
At the moment, individuals interact through excluding each other from resources (e.g. preemption) and by producing resources (i.e., cross-feeding). There is currently no communication.
###Stochasticity
The occurrence of life history processes are conducted via random sampling. In this way, population and community dynamics result, in part, from demographic stochasticity. Likewise, the emergence of suites of life history traits proceeds from initially random combinations of traits.
###Collectives
Individuals belong to species. Species belong to communities. Depending on the model, communities belong to trophic levels.
## SUBMODELS AND EQUATIONS
###Cell quota model of Droop
In simplex models, individuals grow according to their amounts of endogenous resources (cell quota).
Droop (1968, 1983) gave a relationship between specific growth rate ($\mu$) and cell quota ($Q$):
$$\mu = \mu'_{m} (1 - k_{q}/Q)$$
where $k_{q}$ is the minimum cell quota needed for life, also referred to as the subsistence quota. $\mu'$ is the
###Maintenance cost of Pirt
Pirt (1965) states "The variation, with growth rate, of the yield of organism from the substrate used as energy source is attributed to consumption of energy at a constant rate for cell maintenance." He derives a relationships between the growth yield (biomass), the growth rate, and metabolic maintenance.
simplex models use Pirt's concept of a constant maintenance requirement. simplex also draws from Pirt's simple relation for substrate use:
$$use(total) = use(maintenance) + use(growth)$$
Respiration and activity without growth is not accounted for.
# Notes on simplex source code
Our models operate primarily on lists in a programmatic way, e.g., quickly sorting lists, and removing and returning an element from lists with very little overhead. Likewise, our models generate and hold a lot of information about all the particles and elements in the system, which can become a computationally intensive task. To this end, the modeling coded is written in Python, an easy to read high-level programming language that has many scientific, plotting, and animation libraries. Python gives greater control over the operating system than data analysis languages (e.g. R, Matlab) that can be comparatively slow at purely computational tasks and can greatly limit the amount of memory held in any data object, and even fail to import large amounts of data. Python can also obtain C-like speeds when implementing certain software, e.g., Cython. The output is a broad array of information held in a single csv file.
## SPEED & MEMORY
Our models do not complete until the time series of total abundance values reaches a state of mean reversion (i.e., stationarity). Because simplex models can range from quickly flowing systems with high disturbance to barely flowing and highly stable but depleted systems, simulations can potentially take several minutes or more to complete. Likewise, the ability to simulate many complex scenarios also allows for very large total abundances, the values of which cannot be predicted *a priori* and can even potentially outstrip a computer's memory.
Tests of our models' efficiency were ran on a Mid 2010 MacBook Pro (OS X 10.9.5) with a 2.4 GHz Intel Core 2 Duo processor and 4GB of Memory. This system probably represents a below average capacity for modern personal computers, which for this study, was desirable as simplex should be able to be ran on both personal computers and high capacity remote servers. I present results for time to completion and required memory in the Results.
## UNIT TESTS
### Accuracy and computation
*Diversity*
Our models pass all unit tests for 15 diversity indices, ensuring that each index returns either the correct calculated value, or 'NaN' if given any values that cannot be used (e.g., negative numbers, string characters, empty lists).
## EFFICIENCY
### Results from 100 randomly assembled models
*Speed & Memory*
Analyses from 100 randomly assembled models can be run using the SpeedMemory.Rmd file located in the results/TestResults directory. On average, our models require 96.60 +- 32.70 seconds to run, had an average total abundance (*N*) of 31,367 +- 879. The longest any model took to complete was 49 minutes. The shortest any model took to complete was 5.8 seconds. On average, our models required 161 +- 4.3 megabytes of RAM. The longest running model requried 261MB of RAM and had generated the greatest total abundance (*N* = 68,808). The least amount of memory any model required was 90MB.
## PRODUCTS
### Output data
*SimData.csv*
A .csv file where each row is a run of a randomly assembled model and each column holds a piece of data about the system that was modeled (e.g., length, width, mean total abundance, number of incoming resources, etc.).
### Animations
*.avi movie files*
Our modeling platform can generate animations of models and store them in various image file formats. It does this using the matplotlib animation libary. Choosing whether to animate or not animate a model is done by commenting out lines of code in model.py.
|
gpl-3.0
|
JElchison/iframe-kiosk
|
docs/radar.html
|
346
|
<html>
<head>
<style type="text/css">
html {
background: url(https://s.w-x.co/staticmaps/wu/wu/wxtype1200_cur/usday/current.png) no-repeat center center fixed;
-webkit-background-size: contain;
-moz-background-size: contain;
-o-background-size: contain;
background-size: contain;
background-color: black;
}
</style>
</head>
</html>
|
gpl-3.0
|
rtezli/Blitzableiter
|
BlitzableiterCommandLine/style.css
|
476
|
body
{
margin: 0px;
padding: 10px;
font-family: Arial;
font-size: 12px;
background-color: Black;
color: #fff;
}
table
{
border: none;
background-color: transparent;
}
td
{
margin: 2px;
padding: 5px;
border: none;
background-color: #888;
}
h1
{
color: #000;
}
a
{
color: #fff;
}
a:hover
{
color: #fff;
}
a:visited
{
color: #fff;
}
a:active
{
color: #fff;
}
|
gpl-3.0
|
wp-plugins/responsive-progress-bar
|
assets/js/responsive-progressbar.js
|
642
|
// Core functionality inspired by http://www.ghosthorses.co.uk/production-diary/super-simple-responsive-progress-bar/
jQuery(function($) {
moveProgressBar();
$(window).resize(function() {
moveProgressBar();
});
function moveProgressBar() {
$('.rprogress-wrap').each(function(i, e) {
var getPercent = ($(e).data('progress-percent') / 100);
var getProgressWrapWidth = $(e).width();
var progressTotal = getPercent * getProgressWrapWidth;
var animationLength = $(e).data('speed');
$(e).find('.rprogress-bar').stop().animate({
left: progressTotal
}, animationLength);
});
}
});
|
gpl-3.0
|
neptoess/opengl-superbible-fourth
|
ch03/Pointsz/src/main.cpp
|
3535
|
#include <SFML/Window.hpp>
#include <SFML/OpenGL.hpp>
#include <stdio.h>
#include <math.h>
//CONSTANTS
#define GL_PI (3.141592653f)
//GLOBALS
GLboolean g_vsync = false;
GLboolean g_run = true;
//WIN VARS (Start square)
GLuint win_w = 600;
GLuint win_h = 600;
//LIMITS
GLfloat limit = 100.0f;
GLfloat rot_inc = GL_PI / 36.0f;
GLfloat max_ang = 6.0f * GL_PI;
GLfloat ang_inc = 0.1f;
void draw_axes()
{
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_LINES);
glVertex3f(-100.0f, 0.0f, 0.0f);
glVertex3f(100.0f, 0.0f, 0.0f);
glEnd();
glColor3f(0.0f, 0.0f, 1.0f);
glBegin(GL_LINES);
glVertex3f(0.0f, -100.0f, 0.0f);
glVertex3f(0.0f, 100.0f, 0.0f);
glEnd();
glColor3f(1.0f, 1.0f, 0.0f);
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, -100.0f);
glVertex3f(0.0f, 0.0f, 100.0f);
glEnd();
}
void render_scene()
{
GLfloat x;
GLfloat y;
GLfloat z;
GLfloat theta;
GLfloat sizes[2];
GLfloat size_inc;
GLfloat point_size;
glGetFloatv(GL_POINT_SIZE_RANGE, sizes);
glGetFloatv(GL_POINT_SIZE_GRANULARITY, &size_inc);
point_size = sizes[0];
glClear(GL_COLOR_BUFFER_BIT);
draw_axes();
glColor3f(0.0f, 1.0f, 0.0f);
z = -limit / 2.0f;
for (theta = 0.0f; theta <= max_ang; theta += ang_inc) {
x = limit / 2.0f * cos(theta);
y = limit / 2.0f * sin(theta);
glPointSize(point_size);
glBegin(GL_POINTS);
glVertex3f(x, y, z);
glEnd();
z += 5.0f * ang_inc;
point_size += size_inc;
if (point_size > sizes[1])
point_size = sizes[0];
}
}
void win_resized(GLsizei w, GLsizei h)
{
GLfloat ar;
GLfloat max_x;
GLfloat max_y;
GLfloat max_z;
win_w = w;
win_h = h;
if (win_h == 0)
win_h = 1;
glViewport(0, 0, win_w, win_h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
ar = (GLfloat)w / (GLfloat)h;
if (w <= h) {
max_x = limit;
max_y = limit / ar;
} else {
max_x = limit * ar;
max_y = limit;
}
max_z = limit;
glOrtho(-max_x, max_x, -max_y, max_y, -max_z, max_z);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void setup_render_state()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
win_resized(win_w, win_h);
}
void process_key(sf::Event::KeyEvent e)
{
switch (e.code) {
case (sf::Keyboard::Right):
glRotatef(-rot_inc * 180.0f / GL_PI, 0.0f, 1.0f, 0.0f);
break;
case (sf::Keyboard::Left):
glRotatef(rot_inc * 180.0f / GL_PI, 0.0f, 1.0f, 0.0f);
break;
case (sf::Keyboard::Up):
glRotatef(rot_inc * 180.0f / GL_PI, 1.0f, 0.0f, 0.0f);
break;
case (sf::Keyboard::Down):
glRotatef(-rot_inc * 180.0f / GL_PI, 1.0f, 0.0f, 0.0f);
break;
case (sf::Keyboard::Escape):
g_run = false;
break;
case (sf::Keyboard::Space):
glLoadIdentity();
break;
default:
break;
}
}
void handle_event(sf::Event e)
{
switch (e.type) {
case sf::Event::Closed:
fprintf(stderr,
"OpenGL Version String: %s\n",
glGetString(GL_VERSION));
g_run = false;
break;
case sf::Event::Resized:
win_resized(e.size.width, e.size.height);
break;
case sf::Event::KeyPressed:
process_key(e.key);
break;
default:
break;
}
}
int main(int argc, const char * const argv[])
{
sf::Event e;
sf::Window win;
sf::VideoMode vm;
sf::Clock c;
std::string win_title;
win_title = "Pointsz";
vm.width = win_w;
vm.height = win_h;
vm.bitsPerPixel = 32;
win.create(vm, win_title);
win.setFramerateLimit(60);
win.setVerticalSyncEnabled(g_vsync);
win.setActive();
setup_render_state();
c.restart();
while(g_run) {
while (win.pollEvent(e))
handle_event(e);
render_scene();
win.display();
}
win.close();
return 0;
}
|
gpl-3.0
|
IWillFindYou/SecurityBootManager
|
core/ipxe/src/arch/x86/drivers/hyperv/hyperv.c
|
15466
|
/*
* Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
* You can also choose to distribute this program under the terms of
* the Unmodified Binary Distribution Licence (as given in the file
* COPYING.UBDL), provided that you have satisfied its requirements.
*/
FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
/** @file
*
* Hyper-V driver
*
*/
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <errno.h>
#include <byteswap.h>
#include <pic8259.h>
#include <ipxe/malloc.h>
#include <ipxe/device.h>
#include <ipxe/cpuid.h>
#include <ipxe/msr.h>
#include <ipxe/hyperv.h>
#include <ipxe/vmbus.h>
#include "hyperv.h"
/** Maximum time to wait for a message response
*
* This is a policy decision.
*/
#define HV_MESSAGE_MAX_WAIT_MS 1000
/**
* Convert a Hyper-V status code to an iPXE status code
*
* @v status Hyper-V status code
* @ret rc iPXE status code (before negation)
*/
#define EHV( status ) EPLATFORM ( EINFO_EPLATFORM, (status) )
/**
* Allocate zeroed pages
*
* @v hv Hyper-V hypervisor
* @v ... Page addresses to fill in, terminated by NULL
* @ret rc Return status code
*/
__attribute__ (( sentinel )) int
hv_alloc_pages ( struct hv_hypervisor *hv, ... ) {
va_list args;
void **page;
int i;
/* Allocate and zero pages */
va_start ( args, hv );
for ( i = 0 ; ( ( page = va_arg ( args, void ** ) ) != NULL ); i++ ) {
*page = malloc_dma ( PAGE_SIZE, PAGE_SIZE );
if ( ! *page )
goto err_alloc;
memset ( *page, 0, PAGE_SIZE );
}
va_end ( args );
return 0;
err_alloc:
va_end ( args );
va_start ( args, hv );
for ( ; i >= 0 ; i-- ) {
page = va_arg ( args, void ** );
free_dma ( *page, PAGE_SIZE );
}
va_end ( args );
return -ENOMEM;
}
/**
* Free pages
*
* @v hv Hyper-V hypervisor
* @v ... Page addresses, terminated by NULL
*/
__attribute__ (( sentinel )) void
hv_free_pages ( struct hv_hypervisor *hv, ... ) {
va_list args;
void *page;
va_start ( args, hv );
while ( ( page = va_arg ( args, void * ) ) != NULL )
free_dma ( page, PAGE_SIZE );
va_end ( args );
}
/**
* Allocate message buffer
*
* @v hv Hyper-V hypervisor
* @ret rc Return status code
*/
static int hv_alloc_message ( struct hv_hypervisor *hv ) {
/* Allocate buffer. Must be aligned to at least 8 bytes and
* must not cross a page boundary, so align on its own size.
*/
hv->message = malloc_dma ( sizeof ( *hv->message ),
sizeof ( *hv->message ) );
if ( ! hv->message )
return -ENOMEM;
return 0;
}
/**
* Free message buffer
*
* @v hv Hyper-V hypervisor
*/
static void hv_free_message ( struct hv_hypervisor *hv ) {
/* Free buffer */
free_dma ( hv->message, sizeof ( *hv->message ) );
}
/**
* Check whether or not we are running in Hyper-V
*
* @v hv Hyper-V hypervisor
* @ret rc Return status code
*/
static int hv_check_hv ( struct hv_hypervisor *hv ) {
struct x86_features features;
uint32_t interface_id;
uint32_t discard_ebx;
uint32_t discard_ecx;
uint32_t discard_edx;
uint32_t available;
uint32_t permissions;
/* Check for presence of a hypervisor (not necessarily Hyper-V) */
x86_features ( &features );
if ( ! ( features.intel.ecx & CPUID_FEATURES_INTEL_ECX_HYPERVISOR ) ) {
DBGC ( hv, "HV %p not running in a hypervisor\n", hv );
return -ENODEV;
}
/* Check that hypervisor is Hyper-V */
cpuid ( HV_CPUID_INTERFACE_ID, &interface_id, &discard_ebx,
&discard_ecx, &discard_edx );
if ( interface_id != HV_INTERFACE_ID ) {
DBGC ( hv, "HV %p not running in Hyper-V (interface ID "
"%#08x)\n", hv, interface_id );
return -ENODEV;
}
/* Check that required features and privileges are available */
cpuid ( HV_CPUID_FEATURES, &available, &permissions, &discard_ecx,
&discard_edx );
if ( ! ( available & HV_FEATURES_AVAIL_HYPERCALL_MSR ) ) {
DBGC ( hv, "HV %p has no hypercall MSRs (features %08x:%08x)\n",
hv, available, permissions );
return -ENODEV;
}
if ( ! ( available & HV_FEATURES_AVAIL_SYNIC_MSR ) ) {
DBGC ( hv, "HV %p has no SynIC MSRs (features %08x:%08x)\n",
hv, available, permissions );
return -ENODEV;
}
if ( ! ( permissions & HV_FEATURES_PERM_POST_MESSAGES ) ) {
DBGC ( hv, "HV %p cannot post messages (features %08x:%08x)\n",
hv, available, permissions );
return -EACCES;
}
if ( ! ( permissions & HV_FEATURES_PERM_SIGNAL_EVENTS ) ) {
DBGC ( hv, "HV %p cannot signal events (features %08x:%08x)",
hv, available, permissions );
return -EACCES;
}
return 0;
}
/**
* Map hypercall page
*
* @v hv Hyper-V hypervisor
* @ret rc Return status code
*/
static int hv_map_hypercall ( struct hv_hypervisor *hv ) {
union {
struct {
uint32_t ebx;
uint32_t ecx;
uint32_t edx;
} __attribute__ (( packed ));
char text[ 13 /* "bbbbccccdddd" + NUL */ ];
} vendor_id;
uint32_t build;
uint32_t version;
uint32_t discard_eax;
uint32_t discard_ecx;
uint32_t discard_edx;
uint64_t guest_os_id;
uint64_t hypercall;
/* Report guest OS identity */
guest_os_id = rdmsr ( HV_X64_MSR_GUEST_OS_ID );
if ( guest_os_id != 0 ) {
DBGC ( hv, "HV %p guest OS ID MSR already set to %#08llx\n",
hv, guest_os_id );
return -EBUSY;
}
guest_os_id = HV_GUEST_OS_ID_IPXE;
DBGC2 ( hv, "HV %p guest OS ID MSR is %#08llx\n", hv, guest_os_id );
wrmsr ( HV_X64_MSR_GUEST_OS_ID, guest_os_id );
/* Get hypervisor system identity (for debugging) */
cpuid ( HV_CPUID_VENDOR_ID, &discard_eax, &vendor_id.ebx,
&vendor_id.ecx, &vendor_id.edx );
vendor_id.text[ sizeof ( vendor_id.text ) - 1 ] = '\0';
cpuid ( HV_CPUID_HYPERVISOR_ID, &build, &version, &discard_ecx,
&discard_edx );
DBGC ( hv, "HV %p detected \"%s\" version %d.%d build %d\n", hv,
vendor_id.text, ( version >> 16 ), ( version & 0xffff ), build );
/* Map hypercall page */
hypercall = rdmsr ( HV_X64_MSR_HYPERCALL );
hypercall &= ( PAGE_SIZE - 1 );
hypercall |= ( virt_to_phys ( hv->hypercall ) | HV_HYPERCALL_ENABLE );
DBGC2 ( hv, "HV %p hypercall MSR is %#08llx\n", hv, hypercall );
wrmsr ( HV_X64_MSR_HYPERCALL, hypercall );
return 0;
}
/**
* Unmap hypercall page
*
* @v hv Hyper-V hypervisor
*/
static void hv_unmap_hypercall ( struct hv_hypervisor *hv ) {
uint64_t hypercall;
uint64_t guest_os_id;
/* Unmap the hypercall page */
hypercall = rdmsr ( HV_X64_MSR_HYPERCALL );
hypercall &= ( ( PAGE_SIZE - 1 ) & ~HV_HYPERCALL_ENABLE );
DBGC2 ( hv, "HV %p hypercall MSR is %#08llx\n", hv, hypercall );
wrmsr ( HV_X64_MSR_HYPERCALL, hypercall );
/* Reset the guest OS identity */
guest_os_id = 0;
DBGC2 ( hv, "HV %p guest OS ID MSR is %#08llx\n", hv, guest_os_id );
wrmsr ( HV_X64_MSR_GUEST_OS_ID, guest_os_id );
}
/**
* Map synthetic interrupt controller
*
* @v hv Hyper-V hypervisor
* @ret rc Return status code
*/
static int hv_map_synic ( struct hv_hypervisor *hv ) {
uint64_t simp;
uint64_t siefp;
uint64_t scontrol;
/* Map SynIC message page */
simp = rdmsr ( HV_X64_MSR_SIMP );
simp &= ( PAGE_SIZE - 1 );
simp |= ( virt_to_phys ( hv->synic.message ) | HV_SIMP_ENABLE );
DBGC2 ( hv, "HV %p SIMP MSR is %#08llx\n", hv, simp );
wrmsr ( HV_X64_MSR_SIMP, simp );
/* Map SynIC event page */
siefp = rdmsr ( HV_X64_MSR_SIEFP );
siefp &= ( PAGE_SIZE - 1 );
siefp |= ( virt_to_phys ( hv->synic.event ) | HV_SIEFP_ENABLE );
DBGC2 ( hv, "HV %p SIEFP MSR is %#08llx\n", hv, siefp );
wrmsr ( HV_X64_MSR_SIEFP, siefp );
/* Enable SynIC */
scontrol = rdmsr ( HV_X64_MSR_SCONTROL );
scontrol |= HV_SCONTROL_ENABLE;
DBGC2 ( hv, "HV %p SCONTROL MSR is %#08llx\n", hv, scontrol );
wrmsr ( HV_X64_MSR_SCONTROL, scontrol );
return 0;
}
/**
* Unmap synthetic interrupt controller
*
* @v hv Hyper-V hypervisor
*/
static void hv_unmap_synic ( struct hv_hypervisor *hv ) {
uint64_t scontrol;
uint64_t siefp;
uint64_t simp;
/* Disable SynIC */
scontrol = rdmsr ( HV_X64_MSR_SCONTROL );
scontrol &= ~HV_SCONTROL_ENABLE;
DBGC2 ( hv, "HV %p SCONTROL MSR is %#08llx\n", hv, scontrol );
wrmsr ( HV_X64_MSR_SCONTROL, scontrol );
/* Unmap SynIC event page */
siefp = rdmsr ( HV_X64_MSR_SIEFP );
siefp &= ( ( PAGE_SIZE - 1 ) & ~HV_SIEFP_ENABLE );
DBGC2 ( hv, "HV %p SIEFP MSR is %#08llx\n", hv, siefp );
wrmsr ( HV_X64_MSR_SIEFP, siefp );
/* Unmap SynIC message page */
simp = rdmsr ( HV_X64_MSR_SIMP );
simp &= ( ( PAGE_SIZE - 1 ) & ~HV_SIMP_ENABLE );
DBGC2 ( hv, "HV %p SIMP MSR is %#08llx\n", hv, simp );
wrmsr ( HV_X64_MSR_SIMP, simp );
}
/**
* Enable synthetic interrupt
*
* @v hv Hyper-V hypervisor
* @v sintx Synthetic interrupt number
*/
void hv_enable_sint ( struct hv_hypervisor *hv, unsigned int sintx ) {
unsigned long msr = HV_X64_MSR_SINT ( sintx );
uint64_t sint;
/* Enable synthetic interrupt
*
* We have to enable the interrupt, otherwise messages will
* not be delivered (even though the documentation implies
* that polling for messages is possible). We enable AutoEOI
* and hook the interrupt to the obsolete IRQ13 (FPU
* exception) vector, which will be implemented as a no-op.
*/
sint = rdmsr ( msr );
sint &= ~( HV_SINT_MASKED | HV_SINT_VECTOR_MASK );
sint |= ( HV_SINT_AUTO_EOI |
HV_SINT_VECTOR ( IRQ_INT ( 13 /* See comment above */ ) ) );
DBGC2 ( hv, "HV %p SINT%d MSR is %#08llx\n", hv, sintx, sint );
wrmsr ( msr, sint );
}
/**
* Disable synthetic interrupt
*
* @v hv Hyper-V hypervisor
* @v sintx Synthetic interrupt number
*/
void hv_disable_sint ( struct hv_hypervisor *hv, unsigned int sintx ) {
unsigned long msr = HV_X64_MSR_SINT ( sintx );
uint64_t sint;
/* Disable synthetic interrupt */
sint = rdmsr ( msr );
sint &= ~HV_SINT_AUTO_EOI;
sint |= HV_SINT_MASKED;
DBGC2 ( hv, "HV %p SINT%d MSR is %#08llx\n", hv, sintx, sint );
wrmsr ( msr, sint );
}
/**
* Post message
*
* @v hv Hyper-V hypervisor
* @v id Connection ID
* @v type Message type
* @v data Message
* @v len Length of message
* @ret rc Return status code
*/
int hv_post_message ( struct hv_hypervisor *hv, unsigned int id,
unsigned int type, const void *data, size_t len ) {
struct hv_post_message *msg = &hv->message->posted;
int status;
int rc;
/* Sanity check */
assert ( len <= sizeof ( msg->data ) );
/* Construct message */
memset ( msg, 0, sizeof ( *msg ) );
msg->id = cpu_to_le32 ( id );
msg->type = cpu_to_le32 ( type );
msg->len = cpu_to_le32 ( len );
memcpy ( msg->data, data, len );
DBGC2 ( hv, "HV %p connection %d posting message type %#08x:\n",
hv, id, type );
DBGC2_HDA ( hv, 0, msg->data, len );
/* Post message */
if ( ( status = hv_call ( hv, HV_POST_MESSAGE, msg, NULL ) ) != 0 ) {
rc = -EHV ( status );
DBGC ( hv, "HV %p could not post message to %#08x: %s\n",
hv, id, strerror ( rc ) );
return rc;
}
return 0;
}
/**
* Wait for received message
*
* @v hv Hyper-V hypervisor
* @v sintx Synthetic interrupt number
* @ret rc Return status code
*/
int hv_wait_for_message ( struct hv_hypervisor *hv, unsigned int sintx ) {
struct hv_message *msg = &hv->message->received;
struct hv_message *src = &hv->synic.message[sintx];
unsigned int retries;
size_t len;
/* Wait for message to arrive */
for ( retries = 0 ; retries < HV_MESSAGE_MAX_WAIT_MS ; retries++ ) {
/* Check for message */
if ( src->type ) {
/* Copy message */
memset ( msg, 0, sizeof ( *msg ) );
len = src->len;
assert ( len <= sizeof ( *msg ) );
memcpy ( msg, src,
( offsetof ( typeof ( *msg ), data ) + len ) );
DBGC2 ( hv, "HV %p SINT%d received message type "
"%#08x:\n", hv, sintx,
le32_to_cpu ( msg->type ) );
DBGC2_HDA ( hv, 0, msg->data, len );
/* Consume message */
src->type = 0;
return 0;
}
/* Trigger message delivery */
wrmsr ( HV_X64_MSR_EOM, 0 );
/* Delay */
mdelay ( 1 );
}
DBGC ( hv, "HV %p SINT%d timed out waiting for message\n",
hv, sintx );
return -ETIMEDOUT;
}
/**
* Signal event
*
* @v hv Hyper-V hypervisor
* @v id Connection ID
* @v flag Flag number
* @ret rc Return status code
*/
int hv_signal_event ( struct hv_hypervisor *hv, unsigned int id,
unsigned int flag ) {
struct hv_signal_event *event = &hv->message->signalled;
int status;
int rc;
/* Construct event */
memset ( event, 0, sizeof ( *event ) );
event->id = cpu_to_le32 ( id );
event->flag = cpu_to_le16 ( flag );
/* Signal event */
if ( ( status = hv_call ( hv, HV_SIGNAL_EVENT, event, NULL ) ) != 0 ) {
rc = -EHV ( status );
DBGC ( hv, "HV %p could not signal event to %#08x: %s\n",
hv, id, strerror ( rc ) );
return rc;
}
return 0;
}
/**
* Probe root device
*
* @v rootdev Root device
* @ret rc Return status code
*/
static int hv_probe ( struct root_device *rootdev ) {
struct hv_hypervisor *hv;
int rc;
/* Allocate and initialise structure */
hv = zalloc ( sizeof ( *hv ) );
if ( ! hv ) {
rc = -ENOMEM;
goto err_alloc;
}
/* Check we are running in Hyper-V */
if ( ( rc = hv_check_hv ( hv ) ) != 0 )
goto err_check_hv;
/* Allocate pages */
if ( ( rc = hv_alloc_pages ( hv, &hv->hypercall, &hv->synic.message,
&hv->synic.event, NULL ) ) != 0 )
goto err_alloc_pages;
/* Allocate message buffer */
if ( ( rc = hv_alloc_message ( hv ) ) != 0 )
goto err_alloc_message;
/* Map hypercall page */
if ( ( rc = hv_map_hypercall ( hv ) ) != 0 )
goto err_map_hypercall;
/* Map synthetic interrupt controller */
if ( ( rc = hv_map_synic ( hv ) ) != 0 )
goto err_map_synic;
/* Probe Hyper-V devices */
if ( ( rc = vmbus_probe ( hv, &rootdev->dev ) ) != 0 )
goto err_vmbus_probe;
rootdev_set_drvdata ( rootdev, hv );
return 0;
vmbus_remove ( hv, &rootdev->dev );
err_vmbus_probe:
hv_unmap_synic ( hv );
err_map_synic:
hv_unmap_hypercall ( hv );
err_map_hypercall:
hv_free_message ( hv );
err_alloc_message:
hv_free_pages ( hv, hv->hypercall, hv->synic.message, hv->synic.event,
NULL );
err_alloc_pages:
err_check_hv:
free ( hv );
err_alloc:
return rc;
}
/**
* Remove root device
*
* @v rootdev Root device
*/
static void hv_remove ( struct root_device *rootdev ) {
struct hv_hypervisor *hv = rootdev_get_drvdata ( rootdev );
vmbus_remove ( hv, &rootdev->dev );
hv_unmap_synic ( hv );
hv_unmap_hypercall ( hv );
hv_free_message ( hv );
hv_free_pages ( hv, hv->hypercall, hv->synic.message, hv->synic.event,
NULL );
free ( hv );
}
/** Hyper-V root device driver */
static struct root_driver hv_root_driver = {
.probe = hv_probe,
.remove = hv_remove,
};
/** Hyper-V root device */
struct root_device hv_root_device __root_device = {
.dev = { .name = "Hyper-V" },
.driver = &hv_root_driver,
};
/* Drag in objects via hv_root_device */
REQUIRING_SYMBOL ( hv_root_device );
/* Drag in netvsc driver */
REQUIRE_OBJECT ( netvsc );
|
gpl-3.0
|
beslave/space-king
|
test.sh
|
49
|
python -m unittest discover tests -p "*_test.py"
|
gpl-3.0
|
kmcurry/3Scape
|
public/bower_components/bootstrap/js/tests/unit/modal.spec.js
|
35285
|
import Modal from '../../src/modal'
import EventHandler from '../../src/dom/event-handler'
import ScrollBarHelper from '../../src/util/scrollbar'
/** Test helpers */
import { clearBodyAndDocument, clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture'
describe('Modal', () => {
let fixtureEl
beforeAll(() => {
fixtureEl = getFixture()
})
afterEach(() => {
clearFixture()
clearBodyAndDocument()
document.body.classList.remove('modal-open')
document.querySelectorAll('.modal-backdrop')
.forEach(backdrop => {
backdrop.remove()
})
})
beforeEach(() => {
clearBodyAndDocument()
})
describe('VERSION', () => {
it('should return plugin version', () => {
expect(Modal.VERSION).toEqual(jasmine.any(String))
})
})
describe('Default', () => {
it('should return plugin default config', () => {
expect(Modal.Default).toEqual(jasmine.any(Object))
})
})
describe('DATA_KEY', () => {
it('should return plugin data key', () => {
expect(Modal.DATA_KEY).toEqual('bs.modal')
})
})
describe('constructor', () => {
it('should take care of element either passed as a CSS selector or DOM element', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modalBySelector = new Modal('.modal')
const modalByElement = new Modal(modalEl)
expect(modalBySelector._element).toEqual(modalEl)
expect(modalByElement._element).toEqual(modalEl)
})
})
describe('toggle', () => {
it('should call ScrollBarHelper to handle scrollBar on body', done => {
fixtureEl.innerHTML = [
'<div class="modal"><div class="modal-dialog"></div></div>'
].join('')
spyOn(ScrollBarHelper.prototype, 'hide').and.callThrough()
spyOn(ScrollBarHelper.prototype, 'reset').and.callThrough()
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
expect(ScrollBarHelper.prototype.hide).toHaveBeenCalled()
modal.toggle()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(ScrollBarHelper.prototype.reset).toHaveBeenCalled()
done()
})
modal.toggle()
})
})
describe('show', () => {
it('should show a modal', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('show.bs.modal', event => {
expect(event).toBeDefined()
})
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toEqual('true')
expect(modalEl.getAttribute('role')).toEqual('dialog')
expect(modalEl.getAttribute('aria-hidden')).toBeNull()
expect(modalEl.style.display).toEqual('block')
expect(document.querySelector('.modal-backdrop')).not.toBeNull()
done()
})
modal.show()
})
it('should show a modal without backdrop', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: false
})
modalEl.addEventListener('show.bs.modal', event => {
expect(event).toBeDefined()
})
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toEqual('true')
expect(modalEl.getAttribute('role')).toEqual('dialog')
expect(modalEl.getAttribute('aria-hidden')).toBeNull()
expect(modalEl.style.display).toEqual('block')
expect(document.querySelector('.modal-backdrop')).toBeNull()
done()
})
modal.show()
})
it('should show a modal and append the element', done => {
const modalEl = document.createElement('div')
const id = 'dynamicModal'
modalEl.setAttribute('id', id)
modalEl.classList.add('modal')
modalEl.innerHTML = '<div class="modal-dialog"></div>'
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
const dynamicModal = document.getElementById(id)
expect(dynamicModal).not.toBeNull()
dynamicModal.remove()
done()
})
modal.show()
})
it('should do nothing if a modal is shown', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(EventHandler, 'trigger')
modal._isShown = true
modal.show()
expect(EventHandler.trigger).not.toHaveBeenCalled()
})
it('should do nothing if a modal is transitioning', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(EventHandler, 'trigger')
modal._isTransitioning = true
modal.show()
expect(EventHandler.trigger).not.toHaveBeenCalled()
})
it('should not fire shown event when show is prevented', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('show.bs.modal', event => {
event.preventDefault()
const expectedDone = () => {
expect().nothing()
done()
}
setTimeout(expectedDone, 10)
})
modalEl.addEventListener('shown.bs.modal', () => {
throw new Error('shown event triggered')
})
modal.show()
})
it('should be shown after the first call to show() has been prevented while fading is enabled ', done => {
fixtureEl.innerHTML = '<div class="modal fade"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
let prevented = false
modalEl.addEventListener('show.bs.modal', event => {
if (!prevented) {
event.preventDefault()
prevented = true
setTimeout(() => {
modal.show()
})
}
})
modalEl.addEventListener('shown.bs.modal', () => {
expect(prevented).toBeTrue()
expect(modal._isAnimated()).toBeTrue()
done()
})
modal.show()
})
it('should set is transitioning if fade class is present', done => {
fixtureEl.innerHTML = '<div class="modal fade"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('show.bs.modal', () => {
setTimeout(() => {
expect(modal._isTransitioning).toEqual(true)
})
})
modalEl.addEventListener('shown.bs.modal', () => {
expect(modal._isTransitioning).toEqual(false)
done()
})
modal.show()
})
it('should close modal when a click occurred on data-bs-dismiss="modal" inside modal', done => {
fixtureEl.innerHTML = [
'<div class="modal fade">',
' <div class="modal-dialog">',
' <div class="modal-header">',
' <button type="button" data-bs-dismiss="modal"></button>',
' </div>',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const btnClose = fixtureEl.querySelector('[data-bs-dismiss="modal"]')
const modal = new Modal(modalEl)
spyOn(modal, 'hide').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
btnClose.click()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modal.hide).toHaveBeenCalled()
done()
})
modal.show()
})
it('should close modal when a click occurred on a data-bs-dismiss="modal" with "bs-target" outside of modal element', done => {
fixtureEl.innerHTML = [
'<button type="button" data-bs-dismiss="modal" data-bs-target="#modal1"></button>',
'<div id="modal1" class="modal fade">',
' <div class="modal-dialog">',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const btnClose = fixtureEl.querySelector('[data-bs-dismiss="modal"]')
const modal = new Modal(modalEl)
spyOn(modal, 'hide').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
btnClose.click()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modal.hide).toHaveBeenCalled()
done()
})
modal.show()
})
it('should set .modal\'s scroll top to 0', done => {
fixtureEl.innerHTML = [
'<div class="modal fade">',
' <div class="modal-dialog">',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalEl.scrollTop).toEqual(0)
done()
})
modal.show()
})
it('should set modal body scroll top to 0 if modal body do not exists', done => {
fixtureEl.innerHTML = [
'<div class="modal fade">',
' <div class="modal-dialog">',
' <div class="modal-body"></div>',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const modalBody = modalEl.querySelector('.modal-body')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalBody.scrollTop).toEqual(0)
done()
})
modal.show()
})
it('should not trap focus if focus equal to false', done => {
fixtureEl.innerHTML = '<div class="modal fade"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
focus: false
})
spyOn(modal._focustrap, 'activate').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
expect(modal._focustrap.activate).not.toHaveBeenCalled()
done()
})
modal.show()
})
it('should add listener when escape touch is pressed', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal, 'hide').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
const keydownEscape = createEvent('keydown')
keydownEscape.key = 'Escape'
modalEl.dispatchEvent(keydownEscape)
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modal.hide).toHaveBeenCalled()
done()
})
modal.show()
})
it('should do nothing when the pressed key is not escape', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal, 'hide')
const expectDone = () => {
expect(modal.hide).not.toHaveBeenCalled()
done()
}
modalEl.addEventListener('shown.bs.modal', () => {
const keydownTab = createEvent('keydown')
keydownTab.key = 'Tab'
modalEl.dispatchEvent(keydownTab)
setTimeout(expectDone, 30)
})
modal.show()
})
it('should adjust dialog on resize', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal, '_adjustDialog').and.callThrough()
const expectDone = () => {
expect(modal._adjustDialog).toHaveBeenCalled()
done()
}
modalEl.addEventListener('shown.bs.modal', () => {
const resizeEvent = createEvent('resize')
window.dispatchEvent(resizeEvent)
setTimeout(expectDone, 10)
})
modal.show()
})
it('should not close modal when clicking outside of modal-content if backdrop = false', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: false
})
const shownCallback = () => {
setTimeout(() => {
expect(modal._isShown).toEqual(true)
done()
}, 10)
}
modalEl.addEventListener('shown.bs.modal', () => {
modalEl.click()
shownCallback()
})
modalEl.addEventListener('hidden.bs.modal', () => {
throw new Error('Should not hide a modal')
})
modal.show()
})
it('should not close modal when clicking outside of modal-content if backdrop = static', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: 'static'
})
const shownCallback = () => {
setTimeout(() => {
expect(modal._isShown).toEqual(true)
done()
}, 10)
}
modalEl.addEventListener('shown.bs.modal', () => {
modalEl.click()
shownCallback()
})
modalEl.addEventListener('hidden.bs.modal', () => {
throw new Error('Should not hide a modal')
})
modal.show()
})
it('should close modal when escape key is pressed with keyboard = true and backdrop is static', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: 'static',
keyboard: true
})
const shownCallback = () => {
setTimeout(() => {
expect(modal._isShown).toEqual(false)
done()
}, 10)
}
modalEl.addEventListener('shown.bs.modal', () => {
const keydownEscape = createEvent('keydown')
keydownEscape.key = 'Escape'
modalEl.dispatchEvent(keydownEscape)
shownCallback()
})
modal.show()
})
it('should not close modal when escape key is pressed with keyboard = false', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
keyboard: false
})
const shownCallback = () => {
setTimeout(() => {
expect(modal._isShown).toEqual(true)
done()
}, 10)
}
modalEl.addEventListener('shown.bs.modal', () => {
const keydownEscape = createEvent('keydown')
keydownEscape.key = 'Escape'
modalEl.dispatchEvent(keydownEscape)
shownCallback()
})
modalEl.addEventListener('hidden.bs.modal', () => {
throw new Error('Should not hide a modal')
})
modal.show()
})
it('should not overflow when clicking outside of modal-content if backdrop = static', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog" style="transition-duration: 20ms;"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: 'static'
})
modalEl.addEventListener('shown.bs.modal', () => {
modalEl.click()
setTimeout(() => {
expect(modalEl.clientHeight).toEqual(modalEl.scrollHeight)
done()
}, 20)
})
modal.show()
})
it('should not queue multiple callbacks when clicking outside of modal-content and backdrop = static', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog" style="transition-duration: 50ms;"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: 'static'
})
modalEl.addEventListener('shown.bs.modal', () => {
const spy = spyOn(modal, '_queueCallback').and.callThrough()
modalEl.click()
modalEl.click()
setTimeout(() => {
expect(spy).toHaveBeenCalledTimes(1)
done()
}, 20)
})
modal.show()
})
it('should trap focus', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal._focustrap, 'activate').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
expect(modal._focustrap.activate).toHaveBeenCalled()
done()
})
modal.show()
})
})
describe('hide', () => {
it('should hide a modal', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
modal.hide()
})
modalEl.addEventListener('hide.bs.modal', event => {
expect(event).toBeDefined()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toBeNull()
expect(modalEl.getAttribute('role')).toBeNull()
expect(modalEl.getAttribute('aria-hidden')).toEqual('true')
expect(modalEl.style.display).toEqual('none')
expect(document.querySelector('.modal-backdrop')).toBeNull()
done()
})
modal.show()
})
it('should close modal when clicking outside of modal-content', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
modalEl.click()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toBeNull()
expect(modalEl.getAttribute('role')).toBeNull()
expect(modalEl.getAttribute('aria-hidden')).toEqual('true')
expect(modalEl.style.display).toEqual('none')
expect(document.querySelector('.modal-backdrop')).toBeNull()
done()
})
modal.show()
})
it('should do nothing is the modal is not shown', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modal.hide()
expect().nothing()
})
it('should do nothing is the modal is transitioning', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modal._isTransitioning = true
modal.hide()
expect().nothing()
})
it('should not hide a modal if hide is prevented', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
modal.hide()
})
const hideCallback = () => {
setTimeout(() => {
expect(modal._isShown).toEqual(true)
done()
}, 10)
}
modalEl.addEventListener('hide.bs.modal', event => {
event.preventDefault()
hideCallback()
})
modalEl.addEventListener('hidden.bs.modal', () => {
throw new Error('should not trigger hidden')
})
modal.show()
})
it('should release focus trap', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal._focustrap, 'deactivate').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
modal.hide()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modal._focustrap.deactivate).toHaveBeenCalled()
done()
})
modal.show()
})
})
describe('dispose', () => {
it('should dispose a modal', () => {
fixtureEl.innerHTML = '<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
const focustrap = modal._focustrap
spyOn(focustrap, 'deactivate').and.callThrough()
expect(Modal.getInstance(modalEl)).toEqual(modal)
spyOn(EventHandler, 'off')
modal.dispose()
expect(Modal.getInstance(modalEl)).toBeNull()
expect(EventHandler.off).toHaveBeenCalledTimes(3)
expect(focustrap.deactivate).toHaveBeenCalled()
})
})
describe('handleUpdate', () => {
it('should call adjust dialog', () => {
fixtureEl.innerHTML = '<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal, '_adjustDialog')
modal.handleUpdate()
expect(modal._adjustDialog).toHaveBeenCalled()
})
})
describe('data-api', () => {
it('should toggle modal', done => {
fixtureEl.innerHTML = [
'<button type="button" data-bs-toggle="modal" data-bs-target="#exampleModal"></button>',
'<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toEqual('true')
expect(modalEl.getAttribute('role')).toEqual('dialog')
expect(modalEl.getAttribute('aria-hidden')).toBeNull()
expect(modalEl.style.display).toEqual('block')
expect(document.querySelector('.modal-backdrop')).not.toBeNull()
setTimeout(() => trigger.click(), 10)
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toBeNull()
expect(modalEl.getAttribute('role')).toBeNull()
expect(modalEl.getAttribute('aria-hidden')).toEqual('true')
expect(modalEl.style.display).toEqual('none')
expect(document.querySelector('.modal-backdrop')).toBeNull()
done()
})
trigger.click()
})
it('should not recreate a new modal', done => {
fixtureEl.innerHTML = [
'<button type="button" data-bs-toggle="modal" data-bs-target="#exampleModal"></button>',
'<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
spyOn(modal, 'show').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
expect(modal.show).toHaveBeenCalled()
done()
})
trigger.click()
})
it('should prevent default when the trigger is <a> or <area>', done => {
fixtureEl.innerHTML = [
'<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal"></a>',
'<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
spyOn(Event.prototype, 'preventDefault').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toEqual('true')
expect(modalEl.getAttribute('role')).toEqual('dialog')
expect(modalEl.getAttribute('aria-hidden')).toBeNull()
expect(modalEl.style.display).toEqual('block')
expect(document.querySelector('.modal-backdrop')).not.toBeNull()
expect(Event.prototype.preventDefault).toHaveBeenCalled()
done()
})
trigger.click()
})
it('should focus the trigger on hide', done => {
fixtureEl.innerHTML = [
'<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal"></a>',
'<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
spyOn(trigger, 'focus')
modalEl.addEventListener('shown.bs.modal', () => {
const modal = Modal.getInstance(modalEl)
modal.hide()
})
const hideListener = () => {
setTimeout(() => {
expect(trigger.focus).toHaveBeenCalled()
done()
}, 20)
}
modalEl.addEventListener('hidden.bs.modal', () => {
hideListener()
})
trigger.click()
})
it('should not prevent default when a click occurred on data-bs-dismiss="modal" where tagName is DIFFERENT than <a> or <area>', done => {
fixtureEl.innerHTML = [
'<div class="modal">',
' <div class="modal-dialog">',
' <button type="button" data-bs-dismiss="modal"></button>',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const btnClose = fixtureEl.querySelector('button[data-bs-dismiss="modal"]')
const modal = new Modal(modalEl)
spyOn(Event.prototype, 'preventDefault').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
btnClose.click()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(Event.prototype.preventDefault).not.toHaveBeenCalled()
done()
})
modal.show()
})
it('should prevent default when a click occurred on data-bs-dismiss="modal" where tagName is <a> or <area>', done => {
fixtureEl.innerHTML = [
'<div class="modal">',
' <div class="modal-dialog">',
' <a type="button" data-bs-dismiss="modal"></a>',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const btnClose = fixtureEl.querySelector('a[data-bs-dismiss="modal"]')
const modal = new Modal(modalEl)
spyOn(Event.prototype, 'preventDefault').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
btnClose.click()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(Event.prototype.preventDefault).toHaveBeenCalled()
done()
})
modal.show()
})
it('should not focus the trigger if the modal is not visible', done => {
fixtureEl.innerHTML = [
'<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal" style="display: none;"></a>',
'<div id="exampleModal" class="modal" style="display: none;"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
spyOn(trigger, 'focus')
modalEl.addEventListener('shown.bs.modal', () => {
const modal = Modal.getInstance(modalEl)
modal.hide()
})
const hideListener = () => {
setTimeout(() => {
expect(trigger.focus).not.toHaveBeenCalled()
done()
}, 20)
}
modalEl.addEventListener('hidden.bs.modal', () => {
hideListener()
})
trigger.click()
})
it('should not focus the trigger if the modal is not shown', done => {
fixtureEl.innerHTML = [
'<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal"></a>',
'<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
spyOn(trigger, 'focus')
const showListener = () => {
setTimeout(() => {
expect(trigger.focus).not.toHaveBeenCalled()
done()
}, 10)
}
modalEl.addEventListener('show.bs.modal', event => {
event.preventDefault()
showListener()
})
trigger.click()
})
it('should call hide first, if another modal is open', done => {
fixtureEl.innerHTML = [
'<button data-bs-toggle="modal" data-bs-target="#modal2"></button>',
'<div id="modal1" class="modal fade"><div class="modal-dialog"></div></div>',
'<div id="modal2" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const trigger2 = fixtureEl.querySelector('button')
const modalEl1 = document.querySelector('#modal1')
const modalEl2 = document.querySelector('#modal2')
const modal1 = new Modal(modalEl1)
modalEl1.addEventListener('shown.bs.modal', () => {
trigger2.click()
})
modalEl1.addEventListener('hidden.bs.modal', () => {
expect(Modal.getInstance(modalEl2)).not.toBeNull()
expect(modalEl2.classList.contains('show')).toBeTrue()
done()
})
modal1.show()
})
})
describe('jQueryInterface', () => {
it('should create a modal', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
jQueryMock.fn.modal.call(jQueryMock)
expect(Modal.getInstance(div)).not.toBeNull()
})
it('should create a modal with given config', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
jQueryMock.fn.modal.call(jQueryMock, { keyboard: false })
spyOn(Modal.prototype, 'constructor')
expect(Modal.prototype.constructor).not.toHaveBeenCalledWith(div, { keyboard: false })
const modal = Modal.getInstance(div)
expect(modal).not.toBeNull()
expect(modal._config.keyboard).toBe(false)
})
it('should not re create a modal', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
const modal = new Modal(div)
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
jQueryMock.fn.modal.call(jQueryMock)
expect(Modal.getInstance(div)).toEqual(modal)
})
it('should throw error on undefined method', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
const action = 'undefinedMethod'
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
expect(() => {
jQueryMock.fn.modal.call(jQueryMock, action)
}).toThrowError(TypeError, `No method named "${action}"`)
})
it('should call show method', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
const modal = new Modal(div)
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
spyOn(modal, 'show')
jQueryMock.fn.modal.call(jQueryMock, 'show')
expect(modal.show).toHaveBeenCalled()
})
it('should not call show method', () => {
fixtureEl.innerHTML = '<div class="modal" data-bs-show="false"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
spyOn(Modal.prototype, 'show')
jQueryMock.fn.modal.call(jQueryMock)
expect(Modal.prototype.show).not.toHaveBeenCalled()
})
})
describe('getInstance', () => {
it('should return modal instance', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
const modal = new Modal(div)
expect(Modal.getInstance(div)).toEqual(modal)
expect(Modal.getInstance(div)).toBeInstanceOf(Modal)
})
it('should return null when there is no modal instance', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
expect(Modal.getInstance(div)).toBeNull()
})
})
describe('getOrCreateInstance', () => {
it('should return modal instance', () => {
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
const modal = new Modal(div)
expect(Modal.getOrCreateInstance(div)).toEqual(modal)
expect(Modal.getInstance(div)).toEqual(Modal.getOrCreateInstance(div, {}))
expect(Modal.getOrCreateInstance(div)).toBeInstanceOf(Modal)
})
it('should return new instance when there is no modal instance', () => {
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
expect(Modal.getInstance(div)).toEqual(null)
expect(Modal.getOrCreateInstance(div)).toBeInstanceOf(Modal)
})
it('should return new instance when there is no modal instance with given configuration', () => {
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
expect(Modal.getInstance(div)).toEqual(null)
const modal = Modal.getOrCreateInstance(div, {
backdrop: true
})
expect(modal).toBeInstanceOf(Modal)
expect(modal._config.backdrop).toEqual(true)
})
it('should return the instance when exists without given configuration', () => {
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
const modal = new Modal(div, {
backdrop: true
})
expect(Modal.getInstance(div)).toEqual(modal)
const modal2 = Modal.getOrCreateInstance(div, {
backdrop: false
})
expect(modal).toBeInstanceOf(Modal)
expect(modal2).toEqual(modal)
expect(modal2._config.backdrop).toEqual(true)
})
})
})
|
gpl-3.0
|
geekitude/dokuwiki-template-namespaced
|
script.js
|
4265
|
/**
* Dokuwiki Namespaced template java file
*
* @link https://www.dokuwiki.org/template:namespaced
* @author Simon DELAGE <sdelage@gmail.com>
* @license GPL 2 (https://www.gnu.org/licenses/gpl-2.0.html)
*
* Here comes java magic
*
* We handle several device classes based on browser width.
* - desktop: > __tablet_width__ (as set in style.ini)
* - mobile:
* - tablet <= __tablet_width__
* - phone <= __phone_width__
*/
var device_class = ''; // not yet known
var device_classes = 'desktop mobile tablet phone';
var $docHeight = jQuery(document).height();
var $sitenavH = 0;
if (jQuery('#namespaced__site_nav').hasClass("sticky")) $sitenavH = jQuery('#namespaced__site_nav').outerHeight();
var $pagenavH = 0;
if (jQuery('#namespaced__page_nav').hasClass("sticky")) $pagenavH = jQuery('#namespaced__page_nav').outerHeight();
var $scrollDelta = $sitenavH + $pagenavH;
//// blur when clicked
//jQuery('#dokuwiki__pagetools div.tools>ul>li>a').on('click', function(){
// this.blur();
//});
// RESIZE WATCHER
jQuery(function(){
var resizeTimer;
dw_page.makeToggle('#namespaced__aside h6.toggle','#namespaced__aside div.content');
tpl_dokuwiki_mobile();
jQuery(window).on('resize',
function(){
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(tpl_dokuwiki_mobile,200);
}
);
});
function tpl_dokuwiki_mobile(){
// the z-index in mobile.css is (mis-)used purely for detecting the screen mode here
var screen_mode = jQuery('#screen__mode').css('z-index') + '';
// determine our device pattern
// TODO: consider moving into dokuwiki core
switch (screen_mode) {
case '2002':
if (device_class.match(/extract-sidebar/)) return;
device_class = 'desktop extract-sidebar';
break;
case '2001':
if (device_class.match(/extract-toc/)) return;
device_class = 'desktop extract-toc';
break;
case '1001':
if (device_class.match(/phone/)) return;
device_class = 'mobile phone';
break;
default:
if (device_class == 'desktop') return;
device_class = 'desktop';
}
jQuery('html').removeClass(device_classes).addClass(device_class);
// handle some layout changes based on change in device
var $handle = jQuery('#namespaced__aside h6.toggle');
var $toc = jQuery('#dw__toc h3');
if (device_class == 'desktop') {
// reset for desktop mode
if($handle.length) {
$handle[0].setState(1);
//$handle.hide();
}
if($toc.length) {
$toc[0].setState(1);
}
}
if (device_class.match(/mobile/)){
// toc and sidebar hiding
if($handle.length) {
//$handle.show();
$handle[0].setState(-1);
}
if($toc.length) {
$toc[0].setState(-1);
}
}
}
// SCROLL WATCHER
// Watch scroll to show/hide got-to-top/bottom page tools
jQuery(document).scroll(function() {
var $scrollTop = jQuery(document).scrollTop();
if ($scrollTop >= 600) {
// user scrolled 600 pixels or more;
jQuery('#namespaced__pagetools ul li.top').fadeIn(500);
if ($scrollTop >= $docHeight - 1200) {
// user scrolled 600 pixels or more;
jQuery('#namespaced__pagetools ul li.bottom').fadeOut(0);
} else {
jQuery('#namespaced__pagetools ul li.bottom').fadeIn(500);
}
} else {
jQuery('#namespaced__pagetools ul li.top').fadeOut(0);
}
});
// CLICK WATCHER
// Add scroll delta from stickies when clicking a link
//jQuery('a[href*="#"]:not([href="#spacious__main"])').click(function(e) {
jQuery('a[href*="#"]').click(function() {
var $target = jQuery(this.hash);
//if ($target.length == 0) target = jQuery('a[name="' + this.hash.substr(1) + '"]');
if ($target.length == 0) $target = jQuery('html');
// Move to intended target with delta depending on stickies
jQuery('html, body').scrollTop($target.offset().top - $scrollDelta );
return false;
});
//jQuery(document).ready(function() {
// jQuery('#namespaced__updown .up').fadeIn(0);
//});
|
gpl-3.0
|
Conrad2134/pitchfx
|
src/teams.js
|
2914
|
const teams = [
{
id: "sln",
full: "St. Louis Cardinals",
location: "St. Louis",
nickname: "Cardinals",
},
{
id: "mil",
full: "Milwaukee Brewers",
location: "Milwaukee",
nickname: "Brewers",
},
{
id: "atl",
full: "Atlanta Braves",
location: "Atlanta",
nickname: "Braves",
},
{
id: "nyn",
full: "New York Mets",
location: "New York",
nickname: "Mets",
},
{
id: "nya",
full: "New York Yankees",
location: "New York",
nickname: "Yankees",
},
{
id: "was",
full: "Washington Nationals",
location: "Washington",
nickname: "Nationals",
},
{
id: "tor",
full: "Toronto Blue Jays",
location: "Toronto",
nickname: "Blue Jays",
},
{
id: "chn",
full: "Chicago Cubs",
location: "Chicago",
nickname: "Cubs",
},
{
id: "cha",
full: "Chicago White Sox",
location: "Chicago",
nickname: "White Sox",
},
{
id: "bos",
full: "Boston Red Sox",
location: "Boston",
nickname: "Red Sox",
},
{
id: "phi",
full: "Philadelphia Phillies",
location: "Philadelphia",
nickname: "Phillies",
},
{
id: "bal",
full: "Baltimore Orioles",
location: "Baltimore",
nickname: "Orioles",
},
{
id: "cin",
full: "Cincinnati Reds",
location: "Cincinnati",
nickname: "Reds",
},
{
id: "cle",
full: "Cleveland Indians",
location: "Cleveland",
nickname: "Indians",
},
{
id: "det",
full: "Detroit Tigers",
location: "Detroit",
nickname: "Tigers",
},
{
id: "min",
full: "Minnesota Twins",
location: "Minnesota",
nickname: "Twins",
},
{
id: "lan",
full: "Los Angeles Dodgers",
location: "Los Angeles",
nickname: "Dodgers",
},
{
id: "ana",
full: "Los Angeles Angels",
location: "Los Angeles",
nickname: "Angels",
},
{
id: "mia",
full: "Miami Marlins",
location: "Miami",
nickname: "Marlins",
},
{
id: "sea",
full: "Seattle Mariners",
location: "Seattle",
nickname: "Mariners",
},
{
id: "pit",
full: "Pittsburgh Pirates",
location: "Pittsburgh",
nickname: "Pirates",
},
{
id: "oak",
full: "Oakland Athletics",
location: "Oakland",
nickname: "Athletics",
},
{
id: "sfn",
full: "San Francisco Giants",
location: "San Francisco",
nickname: "Giants",
},
{
id: "col",
full: "Colorado Rockies",
location: "Colorado",
nickname: "Rockies",
},
{
id: "sdn",
full: "San Diego Padres",
location: "San Diego",
nickname: "Padres",
},
{
id: "hou",
full: "Houston Astros",
location: "Houston",
nickname: "Astros",
},
{
id: "kca",
full: "Kansas City Royals",
location: "Kansas City",
nickname: "Royals",
},
{
id: "tex",
full: "Texas Rangers",
location: "Texas",
nickname: "Rangers",
},
{
id: "tba",
full: "Tampa Bay Rays",
location: "Tampa Bay",
nickname: "Rays",
},
{
id: "ari",
full: "Arizona Diamondbacks",
location: "Arizona",
nickname: "Diamondbacks",
},
];
module.exports = teams;
|
gpl-3.0
|
Toinane/colorpicker
|
src/browsers/support.js
|
950
|
"use strict";
const { BrowserWindow } = require("electron");
module.exports = (dirname, storage) => {
let win;
let init = () => {
if (win === null || win === undefined) {
createWindow();
}
};
let createWindow = () => {
const { screen } = require("electron");
const { width, height } = screen.getPrimaryDisplay().workAreaSize;
win = new BrowserWindow({
frame: false,
autoHideMenuBar: true,
width: width,
height: height,
transparent: true,
alwaysOnTop: true,
resizable: false,
movable: false,
hasShadow: false,
});
win.loadURL(`file://${dirname}/views/support.html`);
win.on("closed", () => {
win = undefined;
});
};
let getWindow = () => win;
return {
init: init,
getWindow: getWindow,
};
};
|
gpl-3.0
|
oascigil/trafficgen
|
src/ndn-traffic-client.cpp
|
31588
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
* Copyright (C) 2014-2015 University of Arizona.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Jerald Paul Abraham <jeraldabraham@email.arizona.edu>
*/
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <string>
#include <unistd.h>
#include <vector>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <boost/noncopyable.hpp>
#include <ndn-cxx/exclude.hpp>
#include <ndn-cxx/face.hpp>
#include <ndn-cxx/name-component.hpp>
#include <ndn-cxx/util/backports.hpp>
#include "logger.hpp"
namespace ndn {
class NdnTrafficClient : boost::noncopyable
{
public:
explicit
NdnTrafficClient(const char* programName)
: m_programName(programName)
, m_logger("NdnTrafficClient")
, m_instanceId(to_string(std::rand()))
, m_hasError(false)
, m_hasQuietLogging(false)
, m_interestInterval(getDefaultInterestInterval())
, m_nMaximumInterests(-1)
, m_face(m_ioService)
, m_nInterestsSent(0)
, m_nPatternsSent(0)
, m_nInterestsReceived(0)
, m_nContentInconsistencies(0)
, m_minimumInterestRoundTripTime(std::numeric_limits<double>::max())
, m_maximumInterestRoundTripTime(0)
, m_totalInterestRoundTripTime(0)
{
}
class InterestTrafficConfiguration
{
public:
InterestTrafficConfiguration()
: m_trafficPercentage(-1)
, m_nameAppendBytes(-1)
, m_nameAppendSequenceNumber(-1)
, m_minSuffixComponents(-1)
, m_maxSuffixComponents(-1)
, m_excludeBeforeBytes(-1)
, m_excludeAfterBytes(-1)
, m_childSelector(-1)
, m_mustBeFresh(-1)
, m_nonceDuplicationPercentage(-1)
, m_interestLifetime(getDefaultInterestLifetime())
, m_nInterestsSent(0)
, m_nInterestsReceived(0)
, m_minimumInterestRoundTripTime(std::numeric_limits<double>::max())
, m_maximumInterestRoundTripTime(0)
, m_totalInterestRoundTripTime(0)
, m_nContentInconsistencies(0)
{
}
static time::milliseconds
getDefaultInterestLifetime()
{
return time::milliseconds(-1);
}
void
printTrafficConfiguration(Logger& logger)
{
std::string detail;
if (m_trafficPercentage > 0)
detail += "TrafficPercentage=" + to_string(m_trafficPercentage) + ", ";
if (!m_names.empty())
detail += "Name=" + m_names.at(0) + ", ";
if (m_nameAppendBytes > 0)
detail += "NameAppendBytes=" + to_string(m_nameAppendBytes) + ", ";
if (m_nameAppendSequenceNumber > 0)
detail += "NameAppendSequenceNumber=" + to_string(m_nameAppendSequenceNumber) + ", ";
if (m_minSuffixComponents >= 0)
detail += "MinSuffixComponents=" + to_string(m_minSuffixComponents) + ", ";
if (m_maxSuffixComponents >= 0)
detail += "MaxSuffixComponents=" + to_string(m_maxSuffixComponents) + ", ";
if (!m_excludeBefore.empty())
detail += "ExcludeBefore=" + m_excludeBefore + ", ";
if (!m_excludeAfter.empty())
detail += "ExcludeAfter=" + m_excludeAfter + ", ";
if (m_excludeBeforeBytes > 0)
detail += "ExcludeBeforeBytes=" + to_string(m_excludeBeforeBytes) + ", ";
if (m_excludeAfterBytes > 0)
detail += "ExcludeAfterBytes=" + to_string(m_excludeAfterBytes) + ", ";
if (m_childSelector >= 0)
detail += "ChildSelector=" + to_string(m_childSelector) + ", ";
if (m_mustBeFresh >= 0)
detail += "MustBeFresh=" + to_string(m_mustBeFresh) + ", ";
if (m_nonceDuplicationPercentage > 0)
detail += "NonceDuplicationPercentage=" + to_string(m_nonceDuplicationPercentage) + ", ";
if (m_interestLifetime >= time::milliseconds(0))
detail += "InterestLifetime=" + to_string(m_interestLifetime.count()) + ", ";
if (!m_expectedContents.empty())
detail += "ExpectedContent=" + m_expectedContents.at(0) + ", ";
if (detail.length() >= 2)
detail = detail.substr(0, detail.length() - 2); // Removing suffix ", "
logger.log(detail, false, false);
}
bool
extractParameterValue(const std::string& detail, std::string& parameter, std::string& value)
{
std::string allowedCharacters = ":/+._-%";
std::size_t i = 0;
parameter = "";
value = "";
while (detail[i] != '=' && i < detail.length()) {
parameter += detail[i];
i++;
}
if (i == detail.length())
return false;
i++;
while ((std::isalnum(detail[i]) ||
allowedCharacters.find(detail[i]) != std::string::npos) &&
i < detail.length()) {
value += detail[i];
i++;
}
if (parameter.empty() || value.empty())
return false;
else
return true;
}
bool
processConfigurationDetail(const std::string& detail, Logger& logger, int lineNumber)
{
std::string parameter, value;
if (extractParameterValue(detail, parameter, value))
{
if (parameter == "TrafficPercentage")
m_trafficPercentage = std::stoi(value);
else if (parameter == "Name")
{
std::cout << "Reading: "<<value<<"\n";
m_names.push_back(value);
}
else if (parameter == "NameAppendBytes")
m_nameAppendBytes = std::stoi(value);
else if (parameter == "NameAppendSequenceNumber")
m_nameAppendSequenceNumber = std::stoi(value);
else if (parameter == "MinSuffixComponents")
m_minSuffixComponents = std::stoi(value);
else if (parameter == "MaxSuffixComponents")
m_maxSuffixComponents = std::stoi(value);
else if (parameter == "ExcludeBefore")
m_excludeBefore = value;
else if (parameter == "ExcludeAfter")
m_excludeAfter = value;
else if (parameter == "ExcludeBeforeBytes")
m_excludeBeforeBytes = std::stoi(value);
else if (parameter == "ExcludeAfterBytes")
m_excludeAfterBytes = std::stoi(value);
else if (parameter == "ChildSelector")
m_childSelector = std::stoi(value);
else if (parameter == "MustBeFresh")
m_mustBeFresh = std::stoi(value);
else if (parameter == "NonceDuplicationPercentage")
m_nonceDuplicationPercentage = std::stoi(value);
else if (parameter == "InterestLifetime")
m_interestLifetime = time::milliseconds(std::stoi(value));
else if (parameter == "ExpectedContent")
{
m_expectedContents.push_back(value);
std::cout << "Reading content value: "<<value<<"\n";
}
else
logger.log("Line " + to_string(lineNumber) +
" \t- Invalid Parameter='" + parameter + "'", false, true);
}
else
{
logger.log("Line " + to_string(lineNumber) +
" \t- Improper Traffic Configuration Line- " + detail, false, true);
return false;
}
return true;
}
bool
checkTrafficDetailCorrectness()
{
return true;
}
private:
int m_trafficPercentage;
std::vector<std::string> m_names;
int m_nameAppendBytes;
int m_nameAppendSequenceNumber;
int m_minSuffixComponents;
int m_maxSuffixComponents;
std::string m_excludeBefore;
std::string m_excludeAfter;
int m_excludeBeforeBytes;
int m_excludeAfterBytes;
int m_childSelector;
int m_mustBeFresh;
int m_nonceDuplicationPercentage;
time::milliseconds m_interestLifetime;
int m_nInterestsSent;
int m_nInterestsReceived;
//round trip time is stored as milliseconds with fractional
//sub-millisecond precision
double m_minimumInterestRoundTripTime;
double m_maximumInterestRoundTripTime;
double m_totalInterestRoundTripTime;
int m_nContentInconsistencies;
std::vector<std::string> m_expectedContents;
friend class NdnTrafficClient;
}; // class InterestTrafficConfiguration
bool
hasError() const
{
return m_hasError;
}
void
usage() const
{
std::cout << "Usage:\n"
<< " " << m_programName << " [options] <Traffic_Configuration_File>\n"
<< "\n"
<< "Generate Interest traffic as per provided Traffic Configuration File.\n"
<< "Interests are continuously generated unless a total number is specified.\n"
<< "Set environment variable NDN_TRAFFIC_LOGFOLDER to redirect output to a log file.\n"
<< "\n"
<< "Options:\n"
<< " [-i interval] - set interest generation interval in milliseconds (default "
<< getDefaultInterestInterval() << ")\n"
<< " [-c count] - set total number of interests to be generated\n"
<< " [-q] - quiet mode: no interest reception/data generation logging\n"
<< " [-h] - print this help text and exit\n";
exit(EXIT_FAILURE);
}
static time::milliseconds
getDefaultInterestInterval()
{
return time::milliseconds(1000);
}
void
setInterestInterval(int interestInterval)
{
if (interestInterval <= 0)
usage();
m_interestInterval = time::milliseconds(interestInterval);
}
void
setMaximumInterests(int maximumInterests)
{
if (maximumInterests <= 0)
usage();
m_nMaximumInterests = maximumInterests;
}
void
setConfigurationFile(char* configurationFile)
{
m_configurationFile = configurationFile;
}
void
setQuietLogging()
{
m_hasQuietLogging = true;
}
void
signalHandler()
{
logStatistics();
m_logger.shutdownLogger();
m_face.shutdown();
m_ioService.stop();
exit(m_hasError ? EXIT_FAILURE : EXIT_SUCCESS);
}
void
logStatistics()
{
m_logger.log("\n\n== Interest Traffic Report ==\n", false, true);
m_logger.log("Total Traffic Pattern Types = " +
to_string(m_trafficPatterns.size()), false, true);
m_logger.log("Total Interests Sent = " +
to_string(m_nInterestsSent), false, true);
m_logger.log("Total Responses Received = " +
to_string(m_nInterestsReceived), false, true);
double loss = 0;
if (m_nInterestsSent > 0)
loss = (m_nInterestsSent - m_nInterestsReceived) * 100.0 / m_nInterestsSent;
m_logger.log("Total Interest Loss = " + to_string(loss) + "%", false, true);
if (m_nContentInconsistencies != 0 || m_nInterestsSent != m_nInterestsReceived)
m_hasError = true;
double average = 0;
double inconsistency = 0;
if (m_nInterestsReceived > 0)
{
average = m_totalInterestRoundTripTime / m_nInterestsReceived;
inconsistency = m_nContentInconsistencies * 100.0 / m_nInterestsReceived;
}
m_logger.log("Total Data Inconsistency = " +
to_string(inconsistency) + "%", false, true);
m_logger.log("Total Round Trip Time = " +
to_string(m_totalInterestRoundTripTime) + "ms", false, true);
m_logger.log("Average Round Trip Time = " +
to_string(average) + "ms\n", false, true);
for (std::size_t patternId = 0; patternId < m_trafficPatterns.size(); patternId++)
{
m_logger.log("Traffic Pattern Type #" +
to_string(patternId + 1), false, true);
m_trafficPatterns[patternId].printTrafficConfiguration(m_logger);
m_logger.log("Total Interests Sent = " +
to_string(m_trafficPatterns[patternId].m_nInterestsSent), false, true);
m_logger.log("Total Responses Received = " +
to_string(m_trafficPatterns[patternId].m_nInterestsReceived), false, true);
loss = 0;
if (m_trafficPatterns[patternId].m_nInterestsSent > 0)
{
loss = (m_trafficPatterns[patternId].m_nInterestsSent -
m_trafficPatterns[patternId].m_nInterestsReceived);
loss *= 100.0;
loss /= m_trafficPatterns[patternId].m_nInterestsSent;
}
m_logger.log("Total Interest Loss = " + to_string(loss) + "%", false, true);
average = 0;
inconsistency = 0;
if (m_trafficPatterns[patternId].m_nInterestsReceived > 0)
{
average = (m_trafficPatterns[patternId].m_totalInterestRoundTripTime /
m_trafficPatterns[patternId].m_nInterestsReceived);
inconsistency = m_trafficPatterns[patternId].m_nContentInconsistencies;
inconsistency *= 100.0 / m_trafficPatterns[patternId].m_nInterestsReceived;
}
m_logger.log("Total Data Inconsistency = " +
to_string(inconsistency) + "%", false, true);
m_logger.log("Total Round Trip Time = " +
to_string(m_trafficPatterns[patternId].m_totalInterestRoundTripTime) +
"ms", false, true);
m_logger.log("Average Round Trip Time = " +
to_string(average) + "ms\n", false, true);
}
}
bool
checkTrafficPatternCorrectness()
{
return true;
}
void
parseConfigurationFile()
{
std::string patternLine;
std::ifstream patternFile;
m_logger.log("Analyzing Traffic Configuration File: " + m_configurationFile, true, true);
patternFile.open(m_configurationFile.c_str());
if (patternFile.is_open())
{
int lineNumber = 0;
while (getline(patternFile, patternLine))
{
lineNumber++;
if (std::isalpha(patternLine[0]))
{
InterestTrafficConfiguration interestData;
bool shouldSkipLine = false;
if (interestData.processConfigurationDetail(patternLine, m_logger, lineNumber))
{
while (getline(patternFile, patternLine) && std::isalpha(patternLine[0]))
{
lineNumber++;
if (!interestData.processConfigurationDetail(patternLine,
m_logger, lineNumber))
{
shouldSkipLine = true;
break;
}
}
lineNumber++;
}
else
shouldSkipLine = true;
if (!shouldSkipLine)
{
if (interestData.checkTrafficDetailCorrectness())
m_trafficPatterns.push_back(interestData);
}
}
}
patternFile.close();
if (!checkTrafficPatternCorrectness())
{
m_logger.log("ERROR - Traffic Configuration Provided Is Not Proper- " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
m_logger.log("Traffic Configuration File Processing Completed\n", true, false);
for (std::size_t patternId = 0; patternId < m_trafficPatterns.size(); patternId++)
{
m_logger.log("Traffic Pattern Type #" +
to_string(patternId + 1), false, false);
m_trafficPatterns[patternId].printTrafficConfiguration(m_logger);
m_logger.log("", false, false);
}
}
else
{
m_logger.log("ERROR - Unable To Open Traffic Configuration File: " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
}
void
initializeTrafficConfiguration()
{
if (boost::filesystem::exists(boost::filesystem::path(m_configurationFile)))
{
if (boost::filesystem::is_regular_file(boost::filesystem::path(m_configurationFile)))
{
parseConfigurationFile();
}
else
{
m_logger.log("ERROR - Traffic Configuration File Is Not A Regular File: " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
}
else
{
m_logger.log("ERROR - Traffic Configuration File Does Not Exist: " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
}
uint32_t
getOldNonce()
{
if (m_nonces.size() == 0)
return getNewNonce();
int randomNonceIndex = std::rand() % m_nonces.size();
return m_nonces[randomNonceIndex];
}
uint32_t
getNewNonce()
{
//Performance Enhancement
if (m_nonces.size() > 1000)
m_nonces.clear();
uint32_t randomNonce = static_cast<uint32_t>(std::rand());
while (std::find(m_nonces.begin(), m_nonces.end(), randomNonce) != m_nonces.end())
randomNonce = static_cast<uint32_t>(std::rand());
m_nonces.push_back(randomNonce);
return randomNonce;
}
static name::Component
generateRandomNameComponent(size_t length)
{
Buffer buffer(length);
for (size_t i = 0; i < length; i++) {
buffer[i] = static_cast<uint8_t>(std::rand() % 256);
}
return name::Component(buffer);
}
void
onData(const ndn::Interest& interest,
ndn::Data& data,
int globalReference,
int localReference,
int patternId,
time::steady_clock::TimePoint sentTime)
{
std::string logLine = "Data Received - PatternType=" + to_string(patternId + 1);
logLine += ", GlobalID=" + to_string(globalReference);
logLine += ", LocalID=" + to_string(localReference);
logLine += ", Name=" + interest.getName().toUri();
unsigned int i;
bool consistent=false;
m_nInterestsReceived++;
m_trafficPatterns[patternId].m_nInterestsReceived++;
if (!m_trafficPatterns[patternId].m_expectedContents.empty())
{
std::string receivedContent = reinterpret_cast<const char*>(data.getContent().value());
int receivedContentLength = data.getContent().value_size();
receivedContent = receivedContent.substr(0, receivedContentLength);
for (i = 0; i < m_trafficPatterns[patternId].m_expectedContents.size(); i++)
{
std::cout <<"Comparing "<<receivedContent<<" with "<<m_trafficPatterns[patternId].m_expectedContents.at(i)<<"\n";
if (receivedContent == m_trafficPatterns[patternId].m_expectedContents.at(i))
{
logLine += ", IsConsistent=Yes";
consistent = true;
break;
}
}
if(!consistent)
{
m_nContentInconsistencies++;
m_trafficPatterns[patternId].m_nContentInconsistencies++;
logLine += ", IsConsistent=No";
}
}
else
logLine += ", IsConsistent=NotChecked";
if (!m_hasQuietLogging)
m_logger.log(logLine, true, false);
double roundTripTime = (time::steady_clock::now() - sentTime).count() / 1000000.0;
if (m_minimumInterestRoundTripTime > roundTripTime)
m_minimumInterestRoundTripTime = roundTripTime;
if (m_maximumInterestRoundTripTime < roundTripTime)
m_maximumInterestRoundTripTime = roundTripTime;
if (m_trafficPatterns[patternId].m_minimumInterestRoundTripTime > roundTripTime)
m_trafficPatterns[patternId].m_minimumInterestRoundTripTime = roundTripTime;
if (m_trafficPatterns[patternId].m_maximumInterestRoundTripTime < roundTripTime)
m_trafficPatterns[patternId].m_maximumInterestRoundTripTime = roundTripTime;
m_totalInterestRoundTripTime += roundTripTime;
m_trafficPatterns[patternId].m_totalInterestRoundTripTime += roundTripTime;
if (m_nMaximumInterests >= 0 && globalReference == m_nMaximumInterests)
{
logStatistics();
m_logger.shutdownLogger();
m_face.shutdown();
m_ioService.stop();
}
}
void
onTimeout(const ndn::Interest& interest,
int globalReference,
int localReference,
int patternId)
{
std::string logLine = "Interest Timed Out - PatternType=" + to_string(patternId + 1);
logLine += ", GlobalID=" + to_string(globalReference);
logLine += ", LocalID=" + to_string(localReference);
logLine += ", Name=" + interest.getName().toUri();
m_logger.log(logLine, true, false);
if (m_nMaximumInterests >= 0 && globalReference == m_nMaximumInterests)
{
logStatistics();
m_logger.shutdownLogger();
m_face.shutdown();
m_ioService.stop();
}
}
void
generateTraffic(boost::asio::deadline_timer* timer)
{
if (m_nMaximumInterests < 0 || m_nPatternsSent < m_nMaximumInterests)
{
int trafficKey = std::rand() % 100;
int cumulativePercentage = 0;
std::size_t patternId;
for (patternId = 0; patternId < m_trafficPatterns.size(); patternId++)
{
cumulativePercentage += m_trafficPatterns[patternId].m_trafficPercentage;
if (trafficKey <= cumulativePercentage)
{
m_nPatternsSent++;
std::cout<<"Size of the m_names is "<<m_trafficPatterns[patternId].m_names.size()<<"\n";
bool timer_scheduled = false;
for(unsigned int i = 0; i < m_trafficPatterns[patternId].m_names.size(); i++)
{
//Name interestName(m_trafficPatterns[patternId].m_name);
Name interestName(m_trafficPatterns[patternId].m_names.at(i));
std::cout <<"Name in interest: "<<interestName<<"\n";
if (m_trafficPatterns[patternId].m_nameAppendBytes > 0)
interestName.append(generateRandomNameComponent(m_trafficPatterns[patternId].m_nameAppendBytes));
if (m_trafficPatterns[patternId].m_nameAppendSequenceNumber >= 0)
{
interestName.append(to_string(m_trafficPatterns[patternId].m_nameAppendSequenceNumber));
m_trafficPatterns[patternId].m_nameAppendSequenceNumber++;
}
Interest interest(interestName);
if (m_trafficPatterns[patternId].m_minSuffixComponents >= 0)
interest.setMinSuffixComponents(
m_trafficPatterns[patternId].m_minSuffixComponents);
if (m_trafficPatterns[patternId].m_maxSuffixComponents >= 0)
interest.setMaxSuffixComponents(
m_trafficPatterns[patternId].m_maxSuffixComponents);
Exclude exclude;
if (!m_trafficPatterns[patternId].m_excludeBefore.empty() &&
!m_trafficPatterns[patternId].m_excludeAfter.empty())
{
exclude.excludeRange(
name::Component(
m_trafficPatterns[patternId].m_excludeAfter),
name::Component(m_trafficPatterns[patternId].m_excludeBefore));
interest.setExclude(exclude);
}
else if (!m_trafficPatterns[patternId].m_excludeBefore.empty())
{
exclude.excludeBefore(
name::Component(m_trafficPatterns[patternId].m_excludeBefore));
interest.setExclude(exclude);
}
else if (!m_trafficPatterns[patternId].m_excludeAfter.empty())
{
exclude.excludeAfter(
name::Component(m_trafficPatterns[patternId].m_excludeAfter));
interest.setExclude(exclude);
}
if (m_trafficPatterns[patternId].m_excludeBeforeBytes > 0 &&
m_trafficPatterns[patternId].m_excludeAfterBytes > 0)
{
exclude.excludeRange(
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeAfterBytes),
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeBeforeBytes));
interest.setExclude(exclude);
}
else if (m_trafficPatterns[patternId].m_excludeBeforeBytes > 0)
{
exclude.excludeBefore(
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeBeforeBytes));
interest.setExclude(exclude);
}
else if (m_trafficPatterns[patternId].m_excludeAfterBytes > 0)
{
exclude.excludeAfter(
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeAfterBytes));
interest.setExclude(exclude);
}
if (m_trafficPatterns[patternId].m_childSelector >= 0)
interest.setChildSelector(m_trafficPatterns[patternId].m_childSelector);
if (m_trafficPatterns[patternId].m_mustBeFresh == 0)
interest.setMustBeFresh(false);
else if (m_trafficPatterns[patternId].m_mustBeFresh > 0)
interest.setMustBeFresh(true);
if (m_trafficPatterns[patternId].m_nonceDuplicationPercentage > 0)
{
int duplicationPercentage = std::rand() % 100;
if (m_trafficPatterns[patternId].m_nonceDuplicationPercentage <=
duplicationPercentage)
interest.setNonce(getOldNonce());
else
interest.setNonce(getNewNonce());
}
else
interest.setNonce(getNewNonce());
if (m_trafficPatterns[patternId].m_interestLifetime >= time::milliseconds(0))
interest.setInterestLifetime(m_trafficPatterns[patternId].m_interestLifetime);
try {
m_nInterestsSent++;
m_trafficPatterns[patternId].m_nInterestsSent++;
time::steady_clock::TimePoint sentTime = time::steady_clock::now();
m_face.expressInterest(interest,
bind(&NdnTrafficClient::onData,
this, _1, _2, m_nPatternsSent,
m_trafficPatterns[patternId].m_nInterestsSent,
patternId, sentTime),
bind(&NdnTrafficClient::onTimeout,
this, _1, m_nInterestsSent,
m_trafficPatterns[patternId].m_nInterestsSent,
patternId));
if (!m_hasQuietLogging) {
std::string logLine =
"Sending Interest - PatternType=" + to_string(patternId + 1) +
", GlobalID=" + to_string(m_nInterestsSent) +
", LocalID=" +
to_string(m_trafficPatterns[patternId].m_nInterestsSent) +
", Name=" + interest.getName().toUri();
m_logger.log(logLine, true, false);
}
if(!timer_scheduled)
{
timer->expires_at(timer->expires_at() +
boost::posix_time::millisec(m_interestInterval.count()));
timer->async_wait(bind(&NdnTrafficClient::generateTraffic, this, timer));
timer_scheduled = true;
}
}
catch (const std::exception& e) {
m_logger.log("ERROR: " + std::string(e.what()), true, true);
}
}
break;
}
}
if (patternId == m_trafficPatterns.size())
{
timer->expires_at(timer->expires_at() +
boost::posix_time::millisec(m_interestInterval.count()));
timer->async_wait(bind(&NdnTrafficClient::generateTraffic, this, timer));
}
}
}
void
run()
{
boost::asio::signal_set signalSet(m_ioService, SIGINT, SIGTERM);
signalSet.async_wait(bind(&NdnTrafficClient::signalHandler, this));
m_logger.initializeLog(m_instanceId);
initializeTrafficConfiguration();
if (m_nMaximumInterests == 0)
{
logStatistics();
m_logger.shutdownLogger();
return;
}
boost::asio::deadline_timer deadlineTimer(m_ioService,
boost::posix_time::millisec(m_interestInterval.count()));
deadlineTimer.async_wait(bind(&NdnTrafficClient::generateTraffic, this, &deadlineTimer));
try {
m_face.processEvents();
}
catch (const std::exception& e) {
m_logger.log("ERROR: " + std::string(e.what()), true, true);
m_logger.shutdownLogger();
m_hasError = true;
m_ioService.stop();
}
}
private:
std::string m_programName;
Logger m_logger;
std::string m_instanceId;
bool m_hasError;
bool m_hasQuietLogging;
time::milliseconds m_interestInterval;
int m_nMaximumInterests;
std::string m_configurationFile;
boost::asio::io_service m_ioService;
Face m_face;
std::vector<InterestTrafficConfiguration> m_trafficPatterns;
std::vector<uint32_t> m_nonces;
int m_nInterestsSent;
int m_nPatternsSent;
int m_nInterestsReceived;
int m_nContentInconsistencies;
//round trip time is stored as milliseconds with fractional
//sub-milliseconds precision
double m_minimumInterestRoundTripTime;
double m_maximumInterestRoundTripTime;
double m_totalInterestRoundTripTime;
};
} // namespace ndn
int
main(int argc, char* argv[])
{
std::srand(std::time(nullptr));
ndn::NdnTrafficClient client(argv[0]);
int option;
while ((option = getopt(argc, argv, "hqi:c:")) != -1) {
switch (option) {
case 'h':
client.usage();
break;
case 'i':
client.setInterestInterval(atoi(optarg));
break;
case 'c':
client.setMaximumInterests(atoi(optarg));
break;
case 'q':
client.setQuietLogging();
break;
default:
client.usage();
break;
}
}
argc -= optind;
argv += optind;
if (!argc)
client.usage();
client.setConfigurationFile(argv[0]);
client.run();
return client.hasError() ? EXIT_FAILURE : EXIT_SUCCESS;
}
|
gpl-3.0
|
obspy/TauPy
|
taupy/tests/test_tauPyModel.py
|
645
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import *
from unittest import TestCase
__author__ = 'nicolas'
import os
class TestTauPyModel(TestCase):
def test_create_taup_model(self):
"""
See if the create model function in the tau interface runs smoothly.
"""
from taupy import tau
try:
os.remove("ak135.taup")
except FileNotFoundError:
pass
ak135 = tau.TauPyModel("ak135", taup_model_path=".")
os.remove("ak135.taup")
|
gpl-3.0
|
lesLaitues/laitues-blog
|
imports/ui/layouts/main-layout.html
|
130
|
<template name="mainLayout">
<div id="main-layout">
{{> Template.dynamic template=content}}
</div>
{{> sAlert}}
</template>
|
gpl-3.0
|
DaviMenezes/DviCodeIgniter
|
application/views/examples/mailbox/read_mail.php
|
12385
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* View
* @copyright (c) 2017, Davi Menezes (davimenezes.dvi@gmail.com)
*/
?>
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Read Mail <small> https://bitbucket.org/DaviMenezes</small>
</h1>
<ol class="breadcrumb">
<li><a href="<?= base_url() ?>"><i class="fa fa-dashboard"></i> Home </a></li>
<!--'<li class="active"></li>'-->
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-3">
<a href="<?= base_url("page/mail_compose") ?>" class="btn btn-primary btn-block margin-bottom">Compose</a>
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">Folders</h3>
<div class="box-tools">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body no-padding">
<ul class="nav nav-pills nav-stacked">
<li><a href="<?= base_url("page/mailbox") ?>">
<i class = "fa fa-inbox"></i> Inbox
<span class="label label-primary pull-right">12</span>
</a>
</li>
<li><a href="#"><i class="fa fa-envelope-o"></i> Sent</a></li>
<li><a href="#"><i class="fa fa-file-text-o"></i> Drafts</a></li>
<li><a href="#"><i class="fa fa-filter"></i> Junk <span class="label label-warning pull-right">65</span></a>
</li>
<li><a href="#"><i class="fa fa-trash-o"></i> Trash</a></li>
</ul>
</div>
<!-- /.box-body -->
</div>
<!-- /. box -->
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">Labels</h3>
<div class="box-tools">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body no-padding">
<ul class="nav nav-pills nav-stacked">
<li><a href="#"><i class="fa fa-circle-o text-red"></i> Important</a></li>
<li><a href="#"><i class="fa fa-circle-o text-yellow"></i> Promotions</a></li>
<li><a href="#"><i class="fa fa-circle-o text-light-blue"></i> Social</a></li>
</ul>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
<div class="col-md-9">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Read Mail</h3>
<div class="box-tools pull-right">
<a href="#" class="btn btn-box-tool" data-toggle="tooltip" title="Previous"><i class="fa fa-chevron-left"></i></a>
<a href="#" class="btn btn-box-tool" data-toggle="tooltip" title="Next"><i class="fa fa-chevron-right"></i></a>
</div>
</div>
<!-- /.box-header -->
<div class="box-body no-padding">
<div class="mailbox-read-info">
<h3>Message Subject Is Placed Here</h3>
<h5>From: help@example.com
<span class="mailbox-read-time pull-right">15 Feb. 2016 11:03 PM</span></h5>
</div>
<!-- /.mailbox-read-info -->
<div class="mailbox-controls with-border text-center">
<div class="btn-group">
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" data-container="body" title="Delete">
<i class="fa fa-trash-o"></i></button>
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" data-container="body" title="Reply">
<i class="fa fa-reply"></i></button>
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" data-container="body" title="Forward">
<i class="fa fa-share"></i></button>
</div>
<!-- /.btn-group -->
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" title="Print">
<i class="fa fa-print"></i></button>
</div>
<!-- /.mailbox-controls -->
<div class="mailbox-read-message">
<p>Hello John,</p>
<p>Keffiyeh blog actually fashion axe vegan, irony biodiesel. Cold-pressed hoodie chillwave put a bird
on it aesthetic, bitters brunch meggings vegan iPhone. Dreamcatcher vegan scenester mlkshk. Ethical
master cleanse Bushwick, occupy Thundercats banjo cliche ennui farm-to-table mlkshk fanny pack
gluten-free. Marfa butcher vegan quinoa, bicycle rights disrupt tofu scenester chillwave 3 wolf moon
asymmetrical taxidermy pour-over. Quinoa tote bag fashion axe, Godard disrupt migas church-key tofu
blog locavore. Thundercats cronut polaroid Neutra tousled, meh food truck selfies narwhal American
Apparel.</p>
<p>Raw denim McSweeney's bicycle rights, iPhone trust fund quinoa Neutra VHS kale chips vegan PBR&B
literally Thundercats +1. Forage tilde four dollar toast, banjo health goth paleo butcher. Four dollar
toast Brooklyn pour-over American Apparel sustainable, lumbersexual listicle gluten-free health goth
umami hoodie. Synth Echo Park bicycle rights DIY farm-to-table, retro kogi sriracha dreamcatcher PBR&B
flannel hashtag irony Wes Anderson. Lumbersexual Williamsburg Helvetica next level. Cold-pressed
slow-carb pop-up normcore Thundercats Portland, cardigan literally meditation lumbersexual crucifix.
Wayfarers raw denim paleo Bushwick, keytar Helvetica scenester keffiyeh 8-bit irony mumblecore
whatever viral Truffaut.</p>
<p>Post-ironic shabby chic VHS, Marfa keytar flannel lomo try-hard keffiyeh cray. Actually fap fanny
pack yr artisan trust fund. High Life dreamcatcher church-key gentrify. Tumblr stumptown four dollar
toast vinyl, cold-pressed try-hard blog authentic keffiyeh Helvetica lo-fi tilde Intelligentsia. Lomo
locavore salvia bespoke, twee fixie paleo cliche brunch Schlitz blog McSweeney's messenger bag swag
slow-carb. Odd Future photo booth pork belly, you probably haven't heard of them actually tofu ennui
keffiyeh lo-fi Truffaut health goth. Narwhal sustainable retro disrupt.</p>
<p>Skateboard artisan letterpress before they sold out High Life messenger bag. Bitters chambray
leggings listicle, drinking vinegar chillwave synth. Fanny pack hoodie American Apparel twee. American
Apparel PBR listicle, salvia aesthetic occupy sustainable Neutra kogi. Organic synth Tumblr viral
plaid, shabby chic single-origin coffee Etsy 3 wolf moon slow-carb Schlitz roof party tousled squid
vinyl. Readymade next level literally trust fund. Distillery master cleanse migas, Vice sriracha
flannel chambray chia cronut.</p>
<p>Thanks,<br>Jane</p>
</div>
<!-- /.mailbox-read-message -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<ul class="mailbox-attachments clearfix">
<li>
<span class="mailbox-attachment-icon"><i class="fa fa-file-pdf-o"></i></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-paperclip"></i> Sep2014-report.pdf</a>
<span class="mailbox-attachment-size">
1,245 KB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
<li>
<span class="mailbox-attachment-icon"><i class="fa fa-file-word-o"></i></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-paperclip"></i> App Description.docx</a>
<span class="mailbox-attachment-size">
1,245 KB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
<li>
<span class="mailbox-attachment-icon has-img"><img src="<?= base_url('assets/img/photo1.png') ?>" alt="Attachment"></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-camera"></i> photo1.png</a>
<span class="mailbox-attachment-size">
2.67 MB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
<li>
<span class="mailbox-attachment-icon has-img"><img src="<?= base_url('assets/img/photo2.png') ?>" alt="Attachment"></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-camera"></i> photo2.png</a>
<span class="mailbox-attachment-size">
1.9 MB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
</ul>
</div>
<!-- /.box-footer -->
<div class="box-footer">
<div class="pull-right">
<button type="button" class="btn btn-default"><i class="fa fa-reply"></i> Reply</button>
<button type="button" class="btn btn-default"><i class="fa fa-share"></i> Forward</button>
</div>
<button type="button" class="btn btn-default"><i class="fa fa-trash-o"></i> Delete</button>
<button type="button" class="btn btn-default"><i class="fa fa-print"></i> Print</button>
</div>
<!-- /.box-footer -->
</div>
<!-- /. box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
|
gpl-3.0
|
bastiao/EsgrimaJS
|
README.md
|
3585
|

# EsgrimaJS: Distributed Javascript Test Runner for Front-end Web Applications
Do you need to do Javascript testing in a distributed way? With
multiple windows, multiple screen, remote places or whatever?
And all the tests need to communicate? Use this framework!
* Worked in distributed web applications - easy way to communicate between them.
* Supports UI Tests.
* You can execute the already exists Unit Tests for the modules.
* Define a pipeline with the tests between different enviroments.
* Loop the pipeline and use the tests as a "stress-tests" also.
* Test in chrome app?
* Test in the mobile enviroments?
* Any other web sandbox?
## Why we built another framework?
Common, there are a lot of frameworks to test javascript. And it is not
another one. We take advantage of the tests frameworks that already exists.
But is it a test runner? Yes. And yes, we also take advantage of what exists in
the moment. And we hope we can propose an integration of this one with
a most broader and used framework by the community (we are quite new, and nobody
knows it.)
Everything started, because we have to test a chrome app (see Chrome App) with
multi monitor. Yes, you click a button in one screen, an action happened in
another monitor. And yes, we need also test interface. The most impartant issue that we face, was related with testing in
the same application, different things, and how can we execute an operation
in one window and check if the value changed in other one (tipically multi monitor
scenario).
Let's mix it together, and do a real test framework for javascript and
web browser framework. We do not real Web Drivers, or whatever. We are embeeded on
the application.
Another clear advantage, is the possibility to run any javascript code. While in Nightwatch.js you
are limited to their API to run your interface tests, here, you can handle javascript triggers
and do it in a different way, like for instance, run unit tests and so on.
The philosophy of EsgrimaJS is totally different from the others. The key idea is each test module
will belong to a group. And each test will run in a group, which mean that it is in
one machine or one thousand machines.
Finally, did you plan interface tests in Mobile devices? Do you want to do? No idea? EsgrimaJS solves it for you!
## How to use?
- [How To Install and Use?](docs/HOWTO.md)
## Architecture

- [Pipeline](docs/Pipeline.md)
- [Communication](docs/Communication.md)
## Technology
The server and client are built in Javascript mainly using ECMAScript 6. The websockets is based on socket.io.
The framework can works over HTTP or HTTPS.
## Known issues
- Clock: how to syncrhonize the clock between several tests running?
- How to access the external components in Javascript AMD? They do not have access to
all components, so it is really hard to get access to them. It is possible to instance
new components.
### Ubuntu workaround
```
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
```
### Windows 8 isues
Follow the same recomendations: https://github.com/TooTallNate/node-gyp#installation
# Authorship & Inspiring
- Luís A. Bastião Silva <bastiao@ua.pt>
- Ideas/Contributions from: Eriksson Monteiro and David Campos.
Many of the philosofy is taken from Karma. So kudos for Karma and for
Vojtech Jína, that are the author of the master thesis.
So, if something is not good with licenses or code or whatever, feel free
to let me know, and will fix it of course.
|
gpl-3.0
|
SteadyStill/rfid
|
src/edu/xjtu/wwh/rmi/ThirdParty.java
|
1997
|
package edu.xjtu.wwh.rmi;
import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import edu.xjtu.wwh.core.OperHDFS;
import edu.xjtu.wwh.parameter.DefaultParameter;
public class ThirdParty {
public static void main(String[] args) {
// TODO Auto-generated method stub
//First First get unique clientID and attr_str and base path.
String base=getBase();
String clientID=getClientID();
String attr_str=getAttrStr();
//在RMI服务注册表中查找名称为eci的对象,并调用其上的方法
CoreFunc cf=null;
try {
cf=(CoreFunc) Naming.lookup("rmi://localhost:8888/cf");
cf.init(base, clientID);
} catch (MalformedURLException | RemoteException | NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Generate related private keys using attr_str
try {
cf.keyInitial(attr_str);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Call decFun
byte[] cipher=OperHDFS.readFromHDFS("cipher").getBytes();
System.out.println(""+cipher.length);
try {
byte[] rs=cf.decFunc(cipher);
System.out.println("DEC:"+new String(rs));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//upd decFun
byte[] newCipher=OperHDFS.readFromHDFS("newCipher").getBytes();
System.out.println(newCipher.length);
try {
byte[] rs=cf.decFunc(newCipher);
System.out.println("UPD:"+new String(rs));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String getBase() {
// TODO Auto-generated method stub
return DefaultParameter.BASE;
}
public static String getClientID(){
return DefaultParameter.TEST_CLIENT_ID;
}
public static String getAttrStr(){
return DefaultParameter.TEST_ATTR_STR;
}
}
|
gpl-3.0
|
ftisunpar/BlueTape
|
vendor/google/apiclient-services/src/Google/Service/YouTube.php
|
70431
|
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Service definition for YouTube (v3).
*
* <p>
* The YouTube Data API v3 is an API that provides access to YouTube data, such
* as videos, playlists, and channels.</p>
*
* <p>
* For more information about this service, see the API
* <a href="https://developers.google.com/youtube/" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_YouTube extends Google_Service
{
/** Manage your YouTube account. */
const YOUTUBE =
"https://www.googleapis.com/auth/youtube";
/** See a list of your current active channel members, their current level, and when they became a member. */
const YOUTUBE_CHANNEL_MEMBERSHIPS_CREATOR =
"https://www.googleapis.com/auth/youtube.channel-memberships.creator";
/** See, edit, and permanently delete your YouTube videos, ratings, comments and captions. */
const YOUTUBE_FORCE_SSL =
"https://www.googleapis.com/auth/youtube.force-ssl";
/** View your YouTube account. */
const YOUTUBE_READONLY =
"https://www.googleapis.com/auth/youtube.readonly";
/** Manage your YouTube videos. */
const YOUTUBE_UPLOAD =
"https://www.googleapis.com/auth/youtube.upload";
/** View and manage your assets and associated content on YouTube. */
const YOUTUBEPARTNER =
"https://www.googleapis.com/auth/youtubepartner";
/** View private information of your YouTube channel relevant during the audit process with a YouTube partner. */
const YOUTUBEPARTNER_CHANNEL_AUDIT =
"https://www.googleapis.com/auth/youtubepartner-channel-audit";
public $abuseReports;
public $activities;
public $captions;
public $channelBanners;
public $channelSections;
public $channels;
public $commentThreads;
public $comments;
public $i18nLanguages;
public $i18nRegions;
public $liveBroadcasts;
public $liveChatBans;
public $liveChatMessages;
public $liveChatModerators;
public $liveStreams;
public $members;
public $membershipsLevels;
public $playlistItems;
public $playlists;
public $search;
public $sponsors;
public $subscriptions;
public $superChatEvents;
public $tests;
public $thirdPartyLinks;
public $thumbnails;
public $videoAbuseReportReasons;
public $videoCategories;
public $videos;
public $watermarks;
/**
* Constructs the internal representation of the YouTube service.
*
* @param Google_Client $client The client used to deliver requests.
* @param string $rootUrl The root URL used for requests to the service.
*/
public function __construct(Google_Client $client, $rootUrl = null)
{
parent::__construct($client);
$this->rootUrl = $rootUrl ?: 'https://youtube.googleapis.com/';
$this->servicePath = '';
$this->batchPath = 'batch';
$this->version = 'v3';
$this->serviceName = 'youtube';
$this->abuseReports = new Google_Service_YouTube_Resource_AbuseReports(
$this,
$this->serviceName,
'abuseReports',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/abuseReports',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->activities = new Google_Service_YouTube_Resource_Activities(
$this,
$this->serviceName,
'activities',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/activities',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'home' => array(
'location' => 'query',
'type' => 'boolean',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'publishedBefore' => array(
'location' => 'query',
'type' => 'string',
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'publishedAfter' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->captions = new Google_Service_YouTube_Resource_Captions(
$this,
$this->serviceName,
'captions',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'download' => array(
'path' => 'youtube/v3/captions/{id}',
'httpMethod' => 'GET',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'tfmt' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'tlang' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'sync' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'GET',
'parameters' => array(
'videoId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'sync' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->channelBanners = new Google_Service_YouTube_Resource_ChannelBanners(
$this,
$this->serviceName,
'channelBanners',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/channelBanners/insert',
'httpMethod' => 'POST',
'parameters' => array(
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->channelSections = new Google_Service_YouTube_Resource_ChannelSections(
$this,
$this->serviceName,
'channelSections',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'update' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->channels = new Google_Service_YouTube_Resource_Channels(
$this,
$this->serviceName,
'channels',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/channels',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'mySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
'forUsername' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'categoryId' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'managedByMe' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'update' => array(
'path' => 'youtube/v3/channels',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->commentThreads = new Google_Service_YouTube_Resource_CommentThreads(
$this,
$this->serviceName,
'commentThreads',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/commentThreads',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/commentThreads',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'searchTerms' => array(
'location' => 'query',
'type' => 'string',
),
'videoId' => array(
'location' => 'query',
'type' => 'string',
),
'order' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'moderationStatus' => array(
'location' => 'query',
'type' => 'string',
),
'textFormat' => array(
'location' => 'query',
'type' => 'string',
),
'allThreadsRelatedToChannelId' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'update' => array(
'path' => 'youtube/v3/commentThreads',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->comments = new Google_Service_YouTube_Resource_Comments(
$this,
$this->serviceName,
'comments',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'textFormat' => array(
'location' => 'query',
'type' => 'string',
),
'parentId' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),'markAsSpam' => array(
'path' => 'youtube/v3/comments/markAsSpam',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'setModerationStatus' => array(
'path' => 'youtube/v3/comments/setModerationStatus',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'moderationStatus' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'banAuthor' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'update' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->i18nLanguages = new Google_Service_YouTube_Resource_I18nLanguages(
$this,
$this->serviceName,
'i18nLanguages',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/i18nLanguages',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->i18nRegions = new Google_Service_YouTube_Resource_I18nRegions(
$this,
$this->serviceName,
'i18nRegions',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/i18nRegions',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveBroadcasts = new Google_Service_YouTube_Resource_LiveBroadcasts(
$this,
$this->serviceName,
'liveBroadcasts',
array(
'methods' => array(
'bind' => array(
'path' => 'youtube/v3/liveBroadcasts/bind',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'streamId' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'control' => array(
'path' => 'youtube/v3/liveBroadcasts/control',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'displaySlate' => array(
'location' => 'query',
'type' => 'boolean',
),
'offsetTimeMs' => array(
'location' => 'query',
'type' => 'string',
),
'walltime' => array(
'location' => 'query',
'type' => 'string',
),
),
),'delete' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'broadcastStatus' => array(
'location' => 'query',
'type' => 'string',
),
'broadcastType' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'transition' => array(
'path' => 'youtube/v3/liveBroadcasts/transition',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'broadcastStatus' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveChatBans = new Google_Service_YouTube_Resource_LiveChatBans(
$this,
$this->serviceName,
'liveChatBans',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveChat/bans',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/liveChat/bans',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->liveChatMessages = new Google_Service_YouTube_Resource_LiveChatMessages(
$this,
$this->serviceName,
'liveChatMessages',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveChat/messages',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/liveChat/messages',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/liveChat/messages',
'httpMethod' => 'GET',
'parameters' => array(
'liveChatId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'profileImageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveChatModerators = new Google_Service_YouTube_Resource_LiveChatModerators(
$this,
$this->serviceName,
'liveChatModerators',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveChat/moderators',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/liveChat/moderators',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/liveChat/moderators',
'httpMethod' => 'GET',
'parameters' => array(
'liveChatId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveStreams = new Google_Service_YouTube_Resource_LiveStreams(
$this,
$this->serviceName,
'liveStreams',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->members = new Google_Service_YouTube_Resource_Members(
$this,
$this->serviceName,
'members',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/members',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'mode' => array(
'location' => 'query',
'type' => 'string',
),
'filterByMemberChannelId' => array(
'location' => 'query',
'type' => 'string',
),
'hasAccessToLevel' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->membershipsLevels = new Google_Service_YouTube_Resource_MembershipsLevels(
$this,
$this->serviceName,
'membershipsLevels',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/membershipsLevels',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->playlistItems = new Google_Service_YouTube_Resource_PlaylistItems(
$this,
$this->serviceName,
'playlistItems',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'videoId' => array(
'location' => 'query',
'type' => 'string',
),
'playlistId' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'update' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->playlists = new Google_Service_YouTube_Resource_Playlists(
$this,
$this->serviceName,
'playlists',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->search = new Google_Service_YouTube_Resource_Search(
$this,
$this->serviceName,
'search',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/search',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'location' => array(
'location' => 'query',
'type' => 'string',
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'publishedAfter' => array(
'location' => 'query',
'type' => 'string',
),
'channelType' => array(
'location' => 'query',
'type' => 'string',
),
'order' => array(
'location' => 'query',
'type' => 'string',
),
'videoDuration' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'locationRadius' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'safeSearch' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'publishedBefore' => array(
'location' => 'query',
'type' => 'string',
),
'relatedToVideoId' => array(
'location' => 'query',
'type' => 'string',
),
'type' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'videoDefinition' => array(
'location' => 'query',
'type' => 'string',
),
'forContentOwner' => array(
'location' => 'query',
'type' => 'boolean',
),
'videoCaption' => array(
'location' => 'query',
'type' => 'string',
),
'relevanceLanguage' => array(
'location' => 'query',
'type' => 'string',
),
'videoSyndicated' => array(
'location' => 'query',
'type' => 'string',
),
'videoLicense' => array(
'location' => 'query',
'type' => 'string',
),
'forDeveloper' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'videoDimension' => array(
'location' => 'query',
'type' => 'string',
),
'eventType' => array(
'location' => 'query',
'type' => 'string',
),
'q' => array(
'location' => 'query',
'type' => 'string',
),
'videoCategoryId' => array(
'location' => 'query',
'type' => 'string',
),
'topicId' => array(
'location' => 'query',
'type' => 'string',
),
'videoEmbeddable' => array(
'location' => 'query',
'type' => 'string',
),
'videoType' => array(
'location' => 'query',
'type' => 'string',
),
'forMine' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->sponsors = new Google_Service_YouTube_Resource_Sponsors(
$this,
$this->serviceName,
'sponsors',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/sponsors',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'filter' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->subscriptions = new Google_Service_YouTube_Resource_Subscriptions(
$this,
$this->serviceName,
'subscriptions',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/subscriptions',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/subscriptions',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/subscriptions',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'order' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'forChannelId' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'mySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'myRecentSubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->superChatEvents = new Google_Service_YouTube_Resource_SuperChatEvents(
$this,
$this->serviceName,
'superChatEvents',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/superChatEvents',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->tests = new Google_Service_YouTube_Resource_Tests(
$this,
$this->serviceName,
'tests',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/tests',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->thirdPartyLinks = new Google_Service_YouTube_Resource_ThirdPartyLinks(
$this,
$this->serviceName,
'thirdPartyLinks',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'DELETE',
'parameters' => array(
'linkingToken' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'type' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'linkingToken' => array(
'location' => 'query',
'type' => 'string',
),
'type' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->thumbnails = new Google_Service_YouTube_Resource_Thumbnails(
$this,
$this->serviceName,
'thumbnails',
array(
'methods' => array(
'set' => array(
'path' => 'youtube/v3/thumbnails/set',
'httpMethod' => 'POST',
'parameters' => array(
'videoId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->videoAbuseReportReasons = new Google_Service_YouTube_Resource_VideoAbuseReportReasons(
$this,
$this->serviceName,
'videoAbuseReportReasons',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/videoAbuseReportReasons',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->videoCategories = new Google_Service_YouTube_Resource_VideoCategories(
$this,
$this->serviceName,
'videoCategories',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/videoCategories',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->videos = new Google_Service_YouTube_Resource_Videos(
$this,
$this->serviceName,
'videos',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'getRating' => array(
'path' => 'youtube/v3/videos/getRating',
'httpMethod' => 'GET',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'stabilize' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'autoLevels' => array(
'location' => 'query',
'type' => 'boolean',
),
'notifySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'locale' => array(
'location' => 'query',
'type' => 'string',
),
'maxHeight' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'videoCategoryId' => array(
'location' => 'query',
'type' => 'string',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'myRating' => array(
'location' => 'query',
'type' => 'string',
),
'chart' => array(
'location' => 'query',
'type' => 'string',
),
'maxWidth' => array(
'location' => 'query',
'type' => 'integer',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'rate' => array(
'path' => 'youtube/v3/videos/rate',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'rating' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'reportAbuse' => array(
'path' => 'youtube/v3/videos/reportAbuse',
'httpMethod' => 'POST',
'parameters' => array(
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->watermarks = new Google_Service_YouTube_Resource_Watermarks(
$this,
$this->serviceName,
'watermarks',
array(
'methods' => array(
'set' => array(
'path' => 'youtube/v3/watermarks/set',
'httpMethod' => 'POST',
'parameters' => array(
'channelId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'unset' => array(
'path' => 'youtube/v3/watermarks/unset',
'httpMethod' => 'POST',
'parameters' => array(
'channelId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
}
}
|
gpl-3.0
|
chergert/libdazzle
|
src/panel/dzl-dock-revealer.h
|
4634
|
/* dzl-dock-revealer.h
*
* Copyright (C) 2016 Christian Hergert <christian@hergert.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(DAZZLE_INSIDE) && !defined(DAZZLE_COMPILATION)
# error "Only <dzl.h> can be included directly."
#endif
#ifndef DZL_DOCK_REVEALER_H
#define DZL_DOCK_REVEALER_H
#include "dzl-version-macros.h"
#include "widgets/dzl-bin.h"
G_BEGIN_DECLS
#define DZL_TYPE_DOCK_REVEALER_TRANSITION_TYPE (dzl_dock_revealer_transition_type_get_type())
#define DZL_TYPE_DOCK_REVEALER (dzl_dock_revealer_get_type())
DZL_AVAILABLE_IN_ALL
G_DECLARE_DERIVABLE_TYPE (DzlDockRevealer, dzl_dock_revealer, DZL, DOCK_REVEALER, DzlBin)
typedef enum
{
DZL_DOCK_REVEALER_TRANSITION_TYPE_NONE,
DZL_DOCK_REVEALER_TRANSITION_TYPE_SLIDE_RIGHT,
DZL_DOCK_REVEALER_TRANSITION_TYPE_SLIDE_LEFT,
DZL_DOCK_REVEALER_TRANSITION_TYPE_SLIDE_UP,
DZL_DOCK_REVEALER_TRANSITION_TYPE_SLIDE_DOWN,
} DzlDockRevealerTransitionType;
struct _DzlDockRevealerClass
{
DzlBinClass parent;
gpointer _reserved1;
gpointer _reserved2;
gpointer _reserved3;
gpointer _reserved4;
gpointer _reserved5;
gpointer _reserved6;
gpointer _reserved7;
gpointer _reserved8;
};
DZL_AVAILABLE_IN_ALL
GType dzl_dock_revealer_transition_type_get_type (void);
DZL_AVAILABLE_IN_ALL
GtkWidget *dzl_dock_revealer_new (void);
DZL_AVAILABLE_IN_ALL
void dzl_dock_revealer_animate_to_position (DzlDockRevealer *self,
gint position,
guint transition_duration);
DZL_AVAILABLE_IN_ALL
DzlDockRevealerTransitionType dzl_dock_revealer_get_transition_type (DzlDockRevealer *self);
DZL_AVAILABLE_IN_ALL
void dzl_dock_revealer_set_transition_type (DzlDockRevealer *self,
DzlDockRevealerTransitionType transition_type);
DZL_AVAILABLE_IN_ALL
gboolean dzl_dock_revealer_get_child_revealed (DzlDockRevealer *self);
DZL_AVAILABLE_IN_ALL
void dzl_dock_revealer_set_reveal_child (DzlDockRevealer *self,
gboolean reveal_child);
DZL_AVAILABLE_IN_ALL
gboolean dzl_dock_revealer_get_reveal_child (DzlDockRevealer *self);
DZL_AVAILABLE_IN_ALL
gint dzl_dock_revealer_get_position (DzlDockRevealer *self);
DZL_AVAILABLE_IN_ALL
void dzl_dock_revealer_set_position (DzlDockRevealer *self,
gint position);
DZL_AVAILABLE_IN_ALL
gboolean dzl_dock_revealer_get_position_set (DzlDockRevealer *self);
DZL_AVAILABLE_IN_ALL
void dzl_dock_revealer_set_position_set (DzlDockRevealer *self,
gboolean position_set);
DZL_AVAILABLE_IN_ALL
guint dzl_dock_revealer_get_transition_duration (DzlDockRevealer *self);
DZL_AVAILABLE_IN_ALL
void dzl_dock_revealer_set_transition_duration (DzlDockRevealer *self,
guint transition_duration);
DZL_AVAILABLE_IN_ALL
gboolean dzl_dock_revealer_is_animating (DzlDockRevealer *self);
G_END_DECLS
#endif /* DZL_DOCK_REVEALER_H */
|
gpl-3.0
|
gsmlg/oneblog
|
app/assets/javascript/app/role.js
|
207
|
define(['backbone'], function(Backbone){
var Role = Backbone.Model.extend({
idAttribute: 'UID',
url: '/api/role'
});
var role = new Role();
role.fetch();
return role;
});
|
gpl-3.0
|
marcboudreau/ilo
|
dxt/fshtool.h
|
850
|
/************************************************************************
FSH decompressor/compressor
Copyright 2016 Marc Boudreau
Based on code released by Denis Auroux under the GNU GPL.
auroux@math.polytechnique.fr
http://www.math.polytechnique.fr/cmat/auroux/nfs/
http://auroux.free.fr/nfs/
This is free software. It is distributed under the terms of the
GNU General Public License.
Distributing this software without its source code is illegal.
*************************************************************************/
void unpack_dxt(unsigned char mask, unsigned short col1, unsigned short col2,
unsigned char *target);
int score_dxt(unsigned long *px, int nstep, unsigned long col1,
unsigned long col2, unsigned long *pack);
void pack_dxt(unsigned long *px, unsigned char *dest);
|
gpl-3.0
|
mnr/DatabaseClinic-SQLite
|
Ch05/README.md
|
1980
|
# CRUD Operations
This challenge will demonstrate how to perform [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) operations on a range of databases.
There are several tasks to perform. We are provided with the text of Shakespeare’s [A Midsummer Night's Dream](http://shakespeare.mit.edu/midsummer/full.html), plus a list of characters in the play. Using those two datasets, the instructors will have to accomplish the following tasks. The first 3 tasks will execute concurrently (if possible/practical).
* For each line in the Shakespeare text, **CREATE** a corresponding record in the database. Each record will include the name of the character speaking, the (absolute) line number of the phrase and the phrase itself, trimmed of any leading or following spaces
* For each record in the database, search for character names, convert them to UPPERCASE, then **UPDATE** the record in the database
* For each record in the database, **DELETE** any lines that start with “ENTER” or “EXIT” or “ACT” or “SCENE”
* When all other tasks are complete, **READ** each line and print it out to console. This task is not concurrent.
* During execution, the instructor will store performance data and then create a table showing the average time for each operation:
| Operation | Average Execution Time (Milliseconds) |
|---|---|
| CREATE | (average time for each line of task 1) |
| READ | (average time for each line of task 4) |
| UPDATE | (average time for each line of task 2) |
| DELETE | (average time for each line of task 3) |
# Exercise Files
For this chapter, the files will be provided in the Exercise Files:
A_Midsummer_Nights_Dream.txt for the play’s text
characters.txt for the character list.
# MNR Notes
This problem wasn't all that difficult. I've broken my solution into four python programs that store performance data back into the database for use by the timing report.
I've also provided an "R" version of the solution.
|
gpl-3.0
|
RannyeriDev/Solfege
|
solfege/exercises/solmisation.py
|
16440
|
# GNU Solfege - free ear training software
# Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2011,
# 2013 Tom Cato Amundsen
# Copyright (C) 2013 Jan Baumgart (Folkwang Universitaet der Kuenste)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import division
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Gdk
from solfege import abstract
from solfege import abstract_solmisation_addon
from solfege import gu
from solfege import lessonfile
from solfege import mpd
from solfege.const import solmisation_syllables, solmisation_notenames
class Teacher(abstract.Teacher, abstract_solmisation_addon.SolmisationAddOnClass):
OK = 0
ERR_PICKY = 1
ERR_NO_ELEMS = 2
def __init__(self, exname):
abstract.Teacher.__init__(self, exname)
self.lessonfileclass = lessonfile.HeaderLessonfile
def play_question(self):
if self.q_status == self.QSTATUS_NO:
return
self.play(self.get_music_string())
def guess_answer(self, a):
assert self.q_status in [self.QSTATUS_NEW, self.QSTATUS_WRONG]
v = []
for idx in range(len(self.m_question)):
v.append(self.m_question[idx] == a[idx])
if not [x for x in v if x == 0]:
self.q_status = self.QSTATUS_SOLVED
self.maybe_auto_new_question()
return 1
else:
self.q_status = self.QSTATUS_WRONG
class RhythmViewer(Gtk.Frame):
def __init__(self, parent):
Gtk.Frame.__init__(self)
self.set_shadow_type(Gtk.ShadowType.IN)
self.g_parent = parent
self.g_box = Gtk.HBox()
self.g_box.show()
self.g_box.set_spacing(gu.PAD_SMALL)
self.g_box.set_border_width(gu.PAD)
self.add(self.g_box)
self.m_data = []
# the number of rhythm elements the viewer is supposed to show
self.m_num_notes = 0
self.g_face = None
self.__timeout = None
def set_num_notes(self, i):
self.m_num_notes = i
def clear(self):
for child in self.g_box.get_children():
child.destroy()
self.m_data = []
def create_holders(self):
"""
create those |__| that represents one beat
"""
if self.__timeout:
GObject.source_remove(self.__timeout)
self.clear()
for x in range(self.m_num_notes):
self.g_box.pack_start(gu.create_png_image('holder'), False, False, 0)
self.m_data = []
def clear_wrong_part(self):
"""When the user have answered the question, this method is used
to clear all but the first correct elements."""
# this assert is always true because if there is no rhythm element,
# then there is a rhythm holder ( |__| )
assert self.m_num_notes == len(self.g_parent.m_t.m_question)
self.g_face.destroy()
self.g_face = None
for n in range(self.m_num_notes):
if self.m_data[n] != self.g_parent.m_t.m_question[n]:
break
for x in range(n, len(self.g_box.get_children())):
self.g_box.get_children()[n].destroy()
self.m_data = self.m_data[:n]
for x in range(n, self.m_num_notes):
self.g_box.pack_start(gu.create_png_image('holder'), False, False, 0)
def add_rhythm_element(self, i):
assert len(self.m_data) <= self.m_num_notes
if len(self.g_box.get_children()) >= self.m_num_notes:
self.g_box.get_children()[self.m_num_notes-1].destroy()
vbox = Gtk.VBox()
vbox.show()
# im = gu.create_rhythm_image(const.RHYTHMS[i])
im = self.g_parent.solbutton(i, False)
vbox.pack_start(im, True, True, 0)
vbox.pack_start(gu.create_png_image('rhythm-wrong'), False, False, 0)
vbox.get_children()[-1].hide()
self.g_box.pack_start(vbox, False, False, 0)
self.g_box.reorder_child(vbox, len(self.m_data))
self.m_data.append(i)
def backspace(self):
if len(self.m_data) > 0:
if self.g_face:
self.g_box.get_children()[-2].destroy()
self.g_face.destroy()
self.g_face = None
self.g_box.get_children()[len(self.m_data)-1].destroy()
self.g_box.pack_start(gu.create_png_image('holder'), False, False, 0)
del self.m_data[-1]
def mark_wrong(self, idx):
"""
Mark the rhythm elements that was wrong by putting the content of
graphics/rhythm-wrong.png (normally a red line) under the element.
"""
self.g_box.get_children()[idx].get_children()[1].show()
def len(self):
"return the number of rhythm elements currently viewed"
return len(self.m_data)
def sad_face(self):
l = gu.HarmonicProgressionLabel(_("Wrong"))
l.show()
self.g_box.pack_start(l, False, False, 0)
self.g_face = Gtk.EventBox()
self.g_face.connect('button_press_event', self.on_sadface_event)
self.g_face.show()
im = Gtk.Image()
im.set_from_stock('solfege-sadface', Gtk.IconSize.LARGE_TOOLBAR)
im.show()
self.g_face.add(im)
self.g_box.pack_start(self.g_face, False, False, 0)
def happy_face(self):
l = gu.HarmonicProgressionLabel(_("Correct"))
l.show()
self.g_box.pack_start(l, False, False, 0)
self.g_face = Gtk.EventBox()
self.g_face.connect('button_press_event', self.on_happyface_event)
self.g_face.show()
im = Gtk.Image()
im.set_from_stock('solfege-happyface', Gtk.IconSize.LARGE_TOOLBAR)
im.show()
self.g_face.add(im)
self.g_box.pack_start(self.g_face, False, False, 0)
def on_happyface_event(self, obj, event):
if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:
self.g_parent.new_question()
def on_sadface_event(self, obj, event):
if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:
self.clear_wrong_part()
def flash(self, s):
self.clear()
l = Gtk.Label(label=s)
l.set_name("Feedback")
l.set_alignment(0.0, 0.5)
l.show()
self.g_box.pack_start(l, True, True, 0)
self.g_box.set_size_request(
max(l.size_request().width + gu.PAD * 2, self.g_box.size_request().width),
max(l.size_request().height + gu.PAD * 2, self.g_box.size_request().height))
self.__timeout = GObject.timeout_add(2000, self.unflash)
def unflash(self, *v):
self.__timeout = None
self.clear()
class Gui(abstract.Gui, abstract_solmisation_addon.SolmisationAddOnGuiClass):
lesson_heading = _("Solmisation Diktat")
def __init__(self, teacher):
abstract.Gui.__init__(self, teacher)
self.m_key_bindings = {'backspace_ak': self.on_backspace}
self.g_answer_box = Gtk.VBox()
self.answer_buttons = []
self.m_answer_buttons = {}
#-------
hbox = gu.bHBox(self.practise_box)
b = Gtk.Button(_("Play"))
b.show()
b.connect('clicked', self.play_users_answer)
hbox.pack_start(b, False, True, 0)
self.practise_box.pack_start(Gtk.HBox(), False, False,
padding=gu.PAD_SMALL)
self.g_rhythm_viewer = RhythmViewer(self)
self.g_rhythm_viewer.create_holders()
hbox.pack_start(self.g_rhythm_viewer, True, True, 0)
self.practise_box.pack_start(self.g_answer_box, False, False, 0)
# action area
self.std_buttons_add(
('new', self.new_question),
('repeat', self.repeat_question),
#('play_answer', self.play_users_answer),
('give_up', self.give_up),
('backspace', self.on_backspace))
self.practise_box.show_all()
##############
# config_box #
##############
self.add_select_elements_gui()
#--------
self.config_box.pack_start(Gtk.HBox(), False, False,
padding=gu.PAD_SMALL)
self.add_select_num_notes_gui()
#-----
self.config_box.pack_start(Gtk.HBox(), False, False,
padding=gu.PAD_SMALL)
#------
hbox = gu.bHBox(self.config_box, False)
hbox.set_spacing(gu.PAD_SMALL)
hbox.pack_start(Gtk.Label(_("Beats per minute:")), False, False, 0)
spin = gu.nSpinButton(self.m_exname, 'bpm',
Gtk.Adjustment(60, 20, 240, 1, 10))
hbox.pack_start(spin, False, False, 0)
hbox = gu.bHBox(self.config_box, False)
hbox.set_spacing(gu.PAD_SMALL)
hbox.pack_start(gu.nCheckButton(self.m_exname,
"show_first_note",
_("Show the first tone")), False, False, 0)
hbox.pack_start(gu.nCheckButton(self.m_exname,
"play_cadence",
_("Play cadence")), False, False, 0)
self._add_auto_new_question_gui(self.config_box)
self.config_box.show_all()
def solbutton(self, i, connect):
if i > len(solmisation_syllables) or i < 0:
btn = Gtk.Button()
else:
btn = Gtk.Button(solmisation_syllables[i])
btn.show()
if connect:
btn.connect('clicked', self.guess_element, i)
return btn
def select_element_cb(self, button, element_num):
super(Gui, self).select_element_cb(button, element_num)
self.m_answer_buttons[element_num].set_sensitive(button.get_active())
#self.update_answer_buttons()
def on_backspace(self, widget=None):
if self.m_t.q_status == self.QSTATUS_SOLVED:
return
self.g_rhythm_viewer.backspace()
if not self.g_rhythm_viewer.m_data:
self.g_backspace.set_sensitive(False)
def play_users_answer(self, widget):
if self.g_rhythm_viewer.m_data:
melody = ""
p = mpd.MusicalPitch()
for k in self.g_rhythm_viewer.m_data:
melody += " " + mpd.transpose_notename(solmisation_notenames[k], self.m_t.m_transp) + "4"
self.m_t.play(r"\staff{ \time 1000000/4 %s }" % melody)
def guess_element(self, sender, i):
if self.m_t.q_status == self.QSTATUS_NO:
self.g_rhythm_viewer.flash(_("Click 'New' to begin."))
return
if self.m_t.q_status == self.QSTATUS_SOLVED:
return
if self.g_rhythm_viewer.len() == len(self.m_t.m_question):
self.g_rhythm_viewer.clear_wrong_part()
self.g_backspace.set_sensitive(True)
self.g_rhythm_viewer.add_rhythm_element(i)
if self.g_rhythm_viewer.len() == len(self.m_t.m_question):
if self.m_t.guess_answer(self.g_rhythm_viewer.m_data):
self.g_rhythm_viewer.happy_face()
self.std_buttons_answer_correct()
else:
v = []
for idx in range(len(self.m_t.m_question)):
v.append(self.m_t.m_question[idx] == self.g_rhythm_viewer.m_data[idx])
for x in range(len(v)):
if not v[x]:
self.g_rhythm_viewer.mark_wrong(x)
self.g_rhythm_viewer.sad_face()
self.std_buttons_answer_wrong()
def new_question(self, widget=None):
g = self.m_t.new_question()
if g == self.m_t.OK:
self.g_first_rhythm_button.grab_focus()
self.g_rhythm_viewer.set_num_notes(self.get_int('num_notes'))
self.g_rhythm_viewer.create_holders()
self.std_buttons_new_question()
if self.m_t.get_bool('show_first_note'):
self.g_rhythm_viewer.add_rhythm_element(self.m_t.m_question[0])
try:
self.m_t.play_question()
except Exception, e:
if not self.standard_exception_handler(e, self.on_end_practise):
raise
return
elif g == self.m_t.ERR_PICKY:
self.g_rhythm_viewer.flash(_("You have to solve this question first."))
else:
assert g == self.m_t.ERR_NO_ELEMS
self.g_repeat.set_sensitive(False)
self.g_rhythm_viewer.flash(_("You have to configure this exercise properly"))
def repeat_question(self, *w):
self.m_t.play_question()
self.g_first_rhythm_button.grab_focus()
def update_answer_buttons(self):
"""
(Re)create the buttons needed to answer the questions.
We recreate the buttons for each lesson file because the
header may specify a different set of rhythm elements to use.
"""
for but in self.answer_buttons:
but.destroy()
self.answer_buttons = []
self.g_first_rhythm_button = None
gs = Gtk.SizeGroup(Gtk.SizeGroupMode.HORIZONTAL)
for i, v in enumerate((
[1, 4, -1, 8, 11, -1, 15, 18, 21, -1, 25, 28, -1, 32],
[0, 3, 6, 7, 10, 13, 14, 17, 20, 23, 24, 27, 30, 31, 34],
[2, 5, -1, 9, 12, -1, 16, 19, 22, -1, 26, 29, -1, 33])):
hbox = Gtk.HBox(True, 0)
for k in v:
b = self.solbutton(k, True)
gs.add_widget(b)
b.set_sensitive(False)
for n in self.m_t.m_P.header.solmisation_elements:
if k == n:
b.set_sensitive(True)
if not self.g_first_rhythm_button:
self.g_first_rhythm_button = b
hbox.pack_start(b, True, True, 0)
self.answer_buttons.append(b)
if k != -1:
self.m_answer_buttons[k] = b
spacing = Gtk.Alignment()
if i in (0, 2):
spacing.set_property('left-padding', 16)
spacing.set_property('right-padding', 16)
spacing.add(hbox)
self.g_answer_box.pack_start(spacing, True, True, 0)
spacing.show_all()
def on_start_practise(self):
# FIXME for now, we run in custom_mode all the time, so we don't
# have to add lots of lesson files. We can change this later.
#self.m_t.m_custom_mode = self.get_bool('gui/expert_mode')
self.m_t.m_custom_mode = True
super(Gui, self).on_start_practise()
if not self.m_t.m_P.header.solmisation_elements:
self.m_t.m_P.header.solmisation_elements = self.m_t.elements[:]
self.update_answer_buttons()
self.std_buttons_start_practise()
if self.m_t.m_custom_mode:
self.update_select_elements_buttons()
self.g_element_frame.show()
else:
self.g_element_frame.hide()
self.m_t.set_default_header_values()
if 'show_first_note' in self.m_t.m_P.header:
self.m_t.set_bool('show_first_note', self.m_t.m_P.header.show_first_note)
if 'play_cadence' in self.m_t.m_P.header:
self.m_t.set_bool('play_cadence', self.m_t.m_P.header.play_cadence)
self.g_rhythm_viewer.flash(_("Click 'New' to begin."))
def on_end_practise(self):
self.m_t.end_practise()
self.std_buttons_end_practise()
self.g_rhythm_viewer.create_holders()
def give_up(self, widget=None):
if self.m_t.q_status == self.QSTATUS_NO:
return
self.g_rhythm_viewer.clear()
for i in self.m_t.m_question:
self.g_rhythm_viewer.add_rhythm_element(i)
self.m_t.q_status = self.QSTATUS_SOLVED
self.std_buttons_give_up()
|
gpl-3.0
|
CCAFS/MARLO
|
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/CustomParameter.java
|
1703
|
package org.cgiar.ccafs.marlo.data.model;
// Generated May 17, 2017 3:36:29 PM by Hibernate Tools 4.3.1.Final
/**
* CustomParameter generated by hbm2java
*/
public class CustomParameter extends MarloAuditableEntity implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 9127311887995427567L;
private GlobalUnit crp;
private Parameter parameter;
private String value;
public CustomParameter() {
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
CustomParameter other = (CustomParameter) obj;
if (this.getId() == null) {
if (other.getId() != null) {
return false;
}
} else if (!this.getId().equals(other.getId())) {
return false;
}
return true;
}
public GlobalUnit getCrp() {
return crp;
}
public Parameter getParameter() {
return parameter;
}
public Long getParameterId() {
return this.getParameter().getId();
}
public String getValue() {
return value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.getId() == null) ? 0 : this.getId().hashCode());
return result;
}
public void setCrp(GlobalUnit crp) {
this.crp = crp;
}
public void setParameter(Parameter parameter) {
this.parameter = parameter;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "CustomParameter [id=" + this.getId() + ", crp=" + crp + ", parameter=" + parameter + ", value=" + value
+ "]";
}
}
|
gpl-3.0
|
ILiebhardt/darktable
|
RELEASE_NOTES.md
|
17600
|
We're proud to announce the new feature release of darktable, 3.0.0!
The github release is here: [https://github.com/darktable-org/darktable/releases/tag/release-3.0.0](https://github.com/darktable-org/darktable/releases/tag/release-3.0.0).
As always, please don't use the autogenerated tarball provided by
github, but only our tar.xz. the checksums are:
```
$ sha256sum darktable-3.0.0.tar.xz
??? darktable-3.0.0.tar.xz
$ sha256sum darktable-3.0.0.dmg
??? darktable-3.0.0.dmg
$ sha256sum darktable-3.0.0.exe
??? darktable-3.0.0.exe
```
When updating from the currently stable 2.6.x series, please bear in
mind that your edits will be preserved during this process, but the new
library and configuration will not be usable with 2.6.x any more, so
making a backup is strongly advised.
#### Important note: to make sure that darktable can keep on supporting the raw file format for your camera, *please* read [this post](https://discuss.pixls.us/t/raw-samples-wanted/5420?u=lebedevri) on how/what raw samples you can contribute to ensure that we have the *full* raw sample set for your camera under CC0 license!
- Almost 3 thousand commits to darktable+rawspeed since 2.6
- 553 pull requests handled
- 66 issues closed
- Updated user manual is coming soon™
## The Big Ones
- A full rework of the GUI. The whole GUI is now fully
controlled by [GTK+ CSS rules](https://developer.gnome.org/gtk3/stable/chap-css-overview.html). There is
no more size, color, position in Gtk C code, which makes the whole GUI themable. This version comes
with several themes:
- darktable : the default theme
- darktable-icons : the default theme with icons
- darktable-elegant-darker : more condensed fonts
best experience with Roboto font installed
- darktable-icons-darker : as elegant, with module icons
best experience with Roboto font installed
- darktable-elegant-dark : lighter version
- darktable-elegant-grey : even lighter version
- darktable-icons-dark : lighter version. with module icons
- darktable-icons-grey : even lighter version, with module icons
New shortcuts have been introduced to quickly collapse borders, sidebars, histogram and
navigation modules, allowing a new borderless editing experience.
Note that the new GUI requires Gtk+ 3.22 or higher to work properly.
- It's now possible to associate dynamic key shortcuts to sliders, then
use them with the mouse wheel or arrow keys to move the value up and down.
For example, associating the <kbd>E</kbd> key to the exposure slider, you can press
it and scroll to increase the exposure without having to open the module.
You get fast heads-up access to all your favorite settings, as if you
were using a dedicated multimedia console.
- The color picker on the 'tone curve', 'color zones' and 'fill light' modules,
as well as the parametric mask controls, now allows you to select an
area when enabled by using <kbd>Ctrl+click</kbd> on the button.
- Added undo/redo support in lighttable for tags, color labels, ratings,
metadata, deleted history stack, pasted history stack and applied
styles.
IMPORTANT:
The 'preview' and 'preview with focus detection' actions
(previously <kbd>Z</kbd> and <kbd>Ctrl+Z</kbd> respectively) are now assigned to
<kbd>W</kbd> and <kbd>Ctrl+W</kbd> in order to follow the convention of
using <kbd>Ctrl+Z</kbd> for the "undo" function (<kbd>Ctrl+Y</kbd> for redo).
- A new timeline view has been introduced in the lighttable.
- A new 'culling' mode has been added to the lightable view. It
displays a fixed number of consecutive images starting from the first
selected, and allows you to pan & zoom them. The number of displayed images
can be set by the user, and they can be navigated with the mouse wheel
and keyboard.
- A quite extensive rewrite of the lighttable view (including the filmstrip in darkroom view)
has been made to greatly improve the overall performance. The lighttable is now
usable on 4K and 5K monitors.
- Added support for the new 'raster mask', a copy of a parametric mask
which is stable during the whole pixel-pipe.
- The processing order of the pixel-pipe can now be changed by using
<kbd>Ctrl+Shift+drag</kbd> on the module headers to arrange them relative
to each other. It is VERY IMPORTANT to understand that this feature is NOT
for creating a more convenient GUI layout, but for changing the actual
processing of the image. DO NOT USE THIS FEATURE unless you understand the
reason behind the default ordering, and have a specific reason for changing it.
The default order is still the correct order for most purposes. Also note that
styles will always apply the default ordering; creating a style based on modules
which have had their order changed will NOT recreate this changed order when
applied, and therefore may not give the expected result.
- The history stack will now always show mandatory modules which were previously
hidden. They are always active as necessary for processing images, and are not
removed by compressing history or by selecting one as a stating point for editing.
These seven modules (some are RAW-only) have a specific icon to identify them easily:
- raw black/white point
- white balance
- highlight reconstruction
- demosaic
- input color profile
- output color profile
- gamma
- The 'color zones' module now shows a histogram based on the chosen ‘select
by’ channel, and if the color picker is in 'select area' mode, the range within
the selected area will also be shown. By default, the spline adjustment is
now similar to the curve controls, allowing you to add and delete nodes, but
these nodes can still be moved with the old-style size control by selecting
the 'edit by area' checkbox. There is also a new 'strong' processing option,
and a new color picker which creates a curve based on selected image area.
- A new module 'filmic RGB' which, like the previous 'filmic', is designed
to replace 'base curve', 'shadows and highlights' and other global tone-mapping modules.
This new version replaces the one introduced in 2.6.2; it should be easier to use,
and it will reduce color casts. The old 'filmic' module is now deprecated and
is only available on images where it was already used for editing.
- A new module 'tone equalizer' is designed to merge the features of 'zone system',
'shadows and highlights', and (local) 'tone mapping' modules in a scene-referred
RGB space. It brings an easy and safe way to remap tones locally, performing a quick
zone-based dodging and burning using Ansel Adam's zone system logic.
The module provides an interface similar to audio graphic equalizers,
with 9 bands (available as fixed sliders or nodes on a spline view),
allowing you to selectively push or pull the exposure for each band in the
range from blacks to specular highlights. It also features an interactive
cursor that allows to push or pull the exposure gains directly from
the image preview by simply hovering over an area and scrolling. It uses a guided filter
internally to refine the dodging and burning mask, which preserves local contrast
without producing halos along edges.
## New Features And Changes
- A new module for handling 3D RGB Lut transformations (PNG Hald-CLUT and
Cube files are supported).
- Many improvements to the 'denoise (profiled)' module. The degree of shadow
denoising can be controlled, including the correction of color casts
(mainly improves high-ISO images). "Auto" modes which infer some parameters
from the profile are available, allowing users to create presets
which are adaptive to various ISO values. The default values of the sliders
are also adapted dynamically on module activation, giving a good trade-off
between noise smoothing and detail preservation. The non-local means mode
has 2 new options: one to coarse-grain denoising, and one to control the
amount of fine detail to preserve. The controls now have soft boundaries,
which means that users can use the keyboard to enter values outside the
range of the sliders if they need to.
- Along with selecting the 'soft proof' color profile, users can now select an
additional profile for the color space of the histogram, color picker and
overexposed checker. When gamut or softproof checks are active the histogram
and color picker use the softproof profile, otherwise they use the new
histogram profile (which is always used for overexposure checking).
- A new setting for 'working profile' has been added to the input color profile
module. This color space will be used by RGB modules between the input and
output color profile modules.
- A new color picker has been added to the parametric masking controls which
adjusts the range sliders based on the selected area from the image. Click the
picker button to adjust the input image slider, <kbd>Ctrl+click</kbd> the
button to adjust the output image slider.
- The 'picasa' target storage in the export module has been completely rewritten
to support the new Google Photo API, and renamed 'google photos'. It is again
possible to create albums directly from the export module.
- A new single-line image information display can be positioned at the top (left, right,
or center) or bottom (center) of the darkroom view to replace the information previously
overlaid on the histogram. The specific information shown can be configured in preferences.
- The 'tagging' module is faster, and can now display hierarchical tags in a
tree view. Tags can now be designated as 'private' (not exported by default),
'synonym' (to help search engines), and 'category' (not exported, for organizing
the tag library). The metadata exported with images can now be configured in the
'export selected' module, allowing you to choose which main types are exported,
as well as define values for specific tags based on formulas.
- Many code optimizations for CPU and SSE paths. The tone equalizer module
introduces a new optimization paradigm (GCC target clones), aimed toward users
of pre-built Linux packages. The image-processing code will be cloned for several
CPU generations (SSE2, SSE3, SSE4, AVX, AVX2) at compilation time, and the best-suited
version of the code will be chosen by the system at run time. This experiment is
to be generalized to other modules if proven successful, and will allow users of pre-built
packages to get the same performance as if the program was specifically compiled for their
computer. It needs GCC 9 compiler and does not yet work on Windows
due to the lack of support of target clones on the OS side.
- A new preference to expand/collapse a darkroom module when it is
activated/deactivated.
- The 'collect images' module has a new single-click option featuring range selection
for date-time and numeric values.
- The orientation of drawn masks using the 'gradient' shape is now clearly displayed
with an arrow.
- The 'graduated density' module has better accuracy when computing the
rotation to avoid sporadic flipping of the gradient.
- Make sure the OpenCL kernel code is recompiled when the driver
version is updated.
- Add color pickers for 'split toning', 'graduated density' and 'watermark' modules.
- The color picker positions are kept during editing within a module.
- The map view can zoom on the images of the selected collection.
- The slideshow will now start at the selected images if any, and supports
changing the delay between images. It will also now be more responsive when
manually moving backward and forward through the images.
- A new 'basic adjustments' module has been added. It allows to adjust
the black level, exposure, highlight compression, contrast, middle grey,
brightness and saturation. It also has an auto feature based on Rawtherapee's
auto levels that can work on the entire image or a user selected area.
- A new 'rgb curve' module has been added. It has modes for linked and
independent RGB channels. The curves and histogram can be displayed using
the working profile or can be scaled to be 50% grey. A secondary color
picker will add 4 nodes to the curve based on the area selected in the
image: min, average, middle, and max.
- A new 'rgb levels' module has been added. It has linked and
independent channels, preserve colors option and is native RGB.
- A new search box has been added to the module groups in the darkroom
view, with configuration options to show only the module groups, only
the search box, or both. Modules are searched for by (localized) name,
and when displaying only the search box, the active modules are shown
when the box is empty. A shortcut can be set for focusing the box.
- A preview window has been added to the darkroom that displays the edited image
on a separate window.
- A new option 'skip' is added to the 'on conflict' setting on the export module
which skips the exporting to existing destination files.
- Allow to switch between clone/heal and blur/color modes in 'retouch' module
after creating a shape using <kbd>Ctrl+click</kbd> on corresponding mode icon.
- An accels window (<kbd>H</kbd>) has been added to summarize all
available shortcuts and mouse actions available in the current
context.
- A zoom & pan feature has been added to lighttable full preview.
- The base-curve module is now using luminance color preservation by
default. This can give slightly less saturated pictures compared to
the previous version where no color preservation was made. But it
will generally avoid color shift.
## Bug fixes
- The color picker support has been fixed by a complete rewrite. It
should now give correct values in all cases.
- Fix overexposed display.
- Do not disable SSL for storage modules.
- A long standing bug on mask distort in Liquify module has been
fixed. This was visible when a liquify mask was used together with
the perspective correction module activated.
- A bug on mask distort from crop & rotate when using flip and
some angle has been fixed.
- Fix manual crop in perspective correction module when not in default
orientation.
- The modification of date/time is now stored into the XMP. This
ensures that removing the picture and reloading will keep the changes.
- Fix orientation to support all cases as exposed in these examples:
https://github.com/recurser/exif-orientation-examples
- Store the panel states for each lighttable mode.
- Fix crop&rotate and orientation in the lightroom importer.
- Fix ProPhoto RGB profile.
- Fix exif lens metadata parsing containing comma.
## Lua
- The displayed image in darkroom view can now be changed.
- GUI panel visibility can now be queried and changed.
- Lighttable view toolbox (rating filter, rating comparator, sort
field, and sort direction) can now be changed.
- Lighttable layout and zoom level can now be changed.
- All images containing a specific tag can be searched and returned.
## Changed Dependencies
- CMake 3.10 is now required.
- OpenMP 4.0 is now required (optional dependency).
## RawSpeed changes
### Changed Dependencies
- CMake 3.10 is now required.
- Pugixml 1.8 is now required.
- OpenMP 4.0 is now required (optional dependency).
- POSIX threads are no longer required.
- zlib 1.2.11 is now required (optional dependency).
### Changes
- Threading was migrated to OpenMP from POSIX threads.
- Phase One IIQ decompressor fixes (quadrant scaling, bad column).
- Large-scale code cleanup, hardening is ongoing still.
- A CMake infrastructure was added to allow integration of RawSpeed into LLVM LNT / Test-Suite.
- Widespread performance tuning, most affected decompressors:
* Sony ARW2
* Panasonic V5
* Phase One
* Nikon
* Pentax
* Canon
* Samsung V1 (compression = '32772')
* Samsung V2 (compression = '32773')
- Continuation of collaboration with LLVM Compiler Infrastructure Project.
## Camera support, compared to 2.6.0
### Base Support
- Epson R-D1s
- Epson R-D1x
- Fujifilm FinePix F770EXR
- Fujifilm FinePix S7000
- Fujifilm GFX 50R (compressed)
- Fujifilm X-A10
- Fujifilm X-T30 (compressed)
- Fujifilm XF10
- Kodak DCS Pro 14N
- Kodak EasyShare Z981
- Kodak EasyShare Z990
- Leica C (Typ 112) (4:3)
- Leica CL (dng)
- Leica Q (Typ 116) (dng)
- Leica Q2 (dng)
- Leica SL (Typ 601) (dng)
- Leica V-LUX (Typ 114) (3:2, 4:3, 16:9, 1:1)
- Nikon Z 6 (14bit-uncompressed, 12bit-uncompressed)
- Nikon Z 7 (14bit-uncompressed)
- Olympus E-M1X
- Olympus E-M5 Mark III
- Olympus TG-6
- Panasonic DC-G90 (4:3)
- Panasonic DC-G91 (4:3)
- Panasonic DC-G95 (4:3)
- Panasonic DC-G99 (4:3)
- Panasonic DC-ZS200 (3:2)
- Panasonic DMC-TX1 (3:2)
- Phase One P30
- Sony DSC-RX0M2
- Sony DSC-RX100M6
- Sony DSC-RX100M7
- Sony ILCE-6400
- Sony ILCE-6600
- Sony ILCE-7RM4
### White Balance Presets
- Leica Q2
- Nikon D500
- Nikon Z 7
- Olympus E-M5 Mark III
- Panasonic DC-LX100M2
- Sony ILCE-6400
### Noise Profiles
- Leica Q2
- Nikon D3
- Nikon D3500
- Nikon Z 6
- Nikon Z 7
- Olympus E-PL8
- Olympus E-PL9
- Panasonic DC-LX100M2
- Sony DSC-RX100M5A
- Sony ILCE-6400
- Sony SLT-A35
## Translations
- Afrikaans
- Albanian
- Chinese
- Czech
- Dutch
- European Spanish
- Finnish
- French
- Galician
- German
- Hebrew
- Hungarian
- Italian
- Japanese
- Nepal
- Norwegian Bokmål
- Polish
- Portuguese
- Romanian
- Russian
- Slovenian
- Thai
|
gpl-3.0
|
cmjatai/cmj
|
cmj/sigad/migrations/0034_auto_20180215_0953.py
|
1088
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-02-15 11:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sigad', '0033_auto_20180207_1028'),
]
operations = [
migrations.AddField(
model_name='documento',
name='capa',
field=models.BooleanField(choices=[(True, 'Sim'), (False, 'Não')], default=False, help_text='Só um objeto pode ser capa de sua classe. Caso haja outro já selecionado, ele será desconsiderado.', verbose_name='Capa de sua Classe'),
),
migrations.AlterField(
model_name='classe',
name='template_classe',
field=models.IntegerField(choices=[(1, 'Listagem em Linha'), (2, 'Galeria Albuns'), (3, 'Página dos Parlamentares'), (4, 'Página individual de Parlamentar'), (5, 'Banco de Imagens'), (6, 'Galeria de Áudios'), (7, 'Galeria de Vídeos'), (99, 'Documento Específico')], default=1, verbose_name='Template para a Classe'),
),
]
|
gpl-3.0
|
tysonliddell/OpenRA
|
OpenRA.Mods.Common/Traits/World/GameSaveViewportManager.cs
|
2338
|
#region Copyright & License Information
/*
* Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.Linq;
using OpenRA.Graphics;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
{
public class GameSaveViewportManagerInfo : ITraitInfo
{
public object Create(ActorInitializer init) { return new GameSaveViewportManager(); }
}
public class GameSaveViewportManager : IWorldLoaded, IGameSaveTraitData
{
WorldRenderer worldRenderer;
void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) { worldRenderer = wr; }
List<MiniYamlNode> IGameSaveTraitData.IssueTraitData(Actor self)
{
// HACK: Store the viewport state for the skirmish observer on the first bot's trait
// TODO: This won't make sense for MP saves
var localPlayer = worldRenderer.World.LocalPlayer;
if ((localPlayer != null && localPlayer.PlayerActor != self) ||
(localPlayer == null && self.Owner != self.World.Players.FirstOrDefault(p => p.IsBot)))
return null;
var nodes = new List<MiniYamlNode>()
{
new MiniYamlNode("Viewport", FieldSaver.FormatValue(worldRenderer.Viewport.CenterPosition))
};
var renderPlayer = worldRenderer.World.RenderPlayer;
if (localPlayer == null && renderPlayer != null)
nodes.Add(new MiniYamlNode("RenderPlayer", FieldSaver.FormatValue(renderPlayer.PlayerActor.ActorID)));
return nodes;
}
void IGameSaveTraitData.ResolveTraitData(Actor self, List<MiniYamlNode> data)
{
var viewportNode = data.FirstOrDefault(n => n.Key == "Viewport");
if (viewportNode != null)
worldRenderer.Viewport.Center(FieldLoader.GetValue<WPos>("Viewport", viewportNode.Value.Value));
var renderPlayerNode = data.FirstOrDefault(n => n.Key == "RenderPlayer");
if (renderPlayerNode != null)
{
var renderPlayerActorID = FieldLoader.GetValue<uint>("RenderPlayer", renderPlayerNode.Value.Value);
worldRenderer.World.RenderPlayer = worldRenderer.World.GetActorById(renderPlayerActorID).Owner;
}
}
}
}
|
gpl-3.0
|
sasadangelo/MrSnake
|
app/src/main/java/org/androidforfun/mrsnake/model/Snake.java
|
7705
|
/*
* Copyright (C) 2016 Salvatore D'Angelo
* This file is part of Mr Snake project.
* This file derive from the Mr Nom project developed by Mario Zechner for the Beginning Android
* Games book (chapter 6).
*
* Mr Snake is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Mr Snake 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.
*/
package org.androidforfun.mrsnake.model;
import java.util.ArrayList;
import java.util.List;
/*
* This class represents the snake. A snake is composed by several pieces described by the class
* SnakeBody. In particular the first piece is the head represented by SnakeHead class and the last
* piece is the tail represented by SnakeTail class.
*
* @author Salvatore D'Angelo
*/
public class Snake {
// the list of pieces of the snake
private List<SnakeBody> parts = new ArrayList<>();
// the direction of the snake. Possible values are: UP, DOWN, LEFT and RIGHT.
private Direction direction;
// when the head of the snake turn this variable contains the direction of the neck. Its value
// depends on if the snake turned clockwise or anticlockwise. In the former case the possible
// values are: UP_RIGHT, RIGHT_DOWN, DOWN_LEFT, LEFT_UP. In the latter case the possible values
// are: UP_LEFT, LEFT_DOWN, DOWN_RIGHT, RIGHT_UP.
private Direction neckDirection;
public Snake() {
reset();
}
/*
* The snake is turned clockwise. The new direction and neck direction depends on the old
* direction.
* UP -> LEFT - UP_LEFT
* LEFT -> DOWN - LEFT_DOWN
* DOWN -> RIGHT - DOWN_RIGHT
* RIGHT -> UP - RIGHT_UP
*/
public void turnAntiClockwise() {
switch (direction) {
case UP:
neckDirection=Direction.UP_LEFT;
direction=Direction.LEFT;
break;
case LEFT:
neckDirection=Direction.LEFT_DOWN;
direction=Direction.DOWN;
break;
case DOWN:
neckDirection=Direction.DOWN_RIGHT;
direction=Direction.RIGHT;
break;
case RIGHT:
neckDirection=Direction.RIGHT_UP;
direction=Direction.UP;
break;
}
}
/*
* The snake is turned anticlockwise. The new direction and neck direction depends on the old
* direction.
* UP -> RIGHT - UP_RIGHT
* RIGHT -> DOWN - RIGHT_DOWN
* DOWN -> LEFT - DOWN_LEFT
* LEFT -> UP - LEFT_UP
*/
public void turnClockwise() {
switch (direction) {
case UP:
neckDirection=Direction.UP_RIGHT;
direction=Direction.RIGHT;
break;
case RIGHT:
neckDirection=Direction.RIGHT_DOWN;
direction=Direction.DOWN;
break;
case DOWN:
neckDirection=Direction.DOWN_LEFT;
direction=Direction.LEFT;
break;
case LEFT:
neckDirection=Direction.LEFT_UP;
direction=Direction.UP;
break;
}
}
/*
* When the snake eat a fruti its size must be increased by 1 piece. This piece is added in the
* middle so the tail should shift by a position. The direction of this shift depends on the
* current direction of the tail
*/
public void eat() {
// add a new piece to the snake
SnakeTail tail = (SnakeTail) parts.get(parts.size()-1);
parts.add(parts.size()-1, new SnakeBody(tail.getX(), tail.getY(), tail.direction));
// shift the tail by 1 position with a direction that depends on its current position.
switch (tail.direction) {
case UP:
tail.moveDown();
break;
case DOWN:
tail.moveUp();
break;
case LEFT:
tail.moveRight();
break;
case RIGHT:
tail.moveLeft();
break;
}
}
/*
* Advance the snake on the grid by a position that depends on the current snake direction.
*/
public void advance() {
int last = parts.size() - 1;
SnakeHead head = (SnakeHead) parts.get(0);
SnakeBody neck = parts.get(1);
SnakeTail tail = (SnakeTail) parts.get(last);
// move all the snake pieces but head, one step forward
for(int i = last; i > 0; i--) {
SnakeBody before = parts.get(i-1);
SnakeBody part = parts.get(i);
part.setX(before.getX());
part.setY(before.getY());
part.direction=before.direction;
}
// move the head towards the snake direction.
head.direction=direction;
switch (direction) {
case UP:
head.moveUp();
break;
case LEFT:
head.moveLeft();
break;
case DOWN:
head.moveDown();
break;
case RIGHT:
head.moveRight();
break;
}
// determine the neck direction
switch (neckDirection) {
case UP_RIGHT:
case LEFT_UP:
case DOWN_LEFT:
case RIGHT_DOWN:
case LEFT_DOWN:
case UP_LEFT:
case DOWN_RIGHT:
case RIGHT_UP:
neck.direction=neckDirection;
neckDirection=Direction.UP;
break;
}
// determine the tail direction
switch (tail.direction) {
case DOWN_LEFT:
case UP_LEFT:
tail.direction=Direction.LEFT;
break;
case LEFT_UP:
case RIGHT_UP:
tail.direction=Direction.UP;
break;
case RIGHT_DOWN:
case LEFT_DOWN:
tail.direction=Direction.DOWN;
break;
case UP_RIGHT:
case DOWN_RIGHT:
tail.direction=Direction.RIGHT;
break;
}
}
/*
* Initializes the snake with a head, a tail and 2 pieces in the middle.
* Direction is UP.
*/
public void reset() {
direction = Direction.UP;
neckDirection = Direction.UP;
parts.clear();
parts.add(new SnakeHead(5, 6, Direction.UP));
parts.add(new SnakeBody(5, 7, Direction.UP));
parts.add(new SnakeBody(5, 8, Direction.UP));
parts.add(new SnakeTail(5, 9, Direction.UP));
}
/*
* Check if snake eat itself.
*/
public boolean checkBitten() {
int len = parts.size();
SnakeBody head = parts.get(0);
for(int i = 1; i < len; i++) {
SnakeBody part = parts.get(i);
if (head.collide(part))
return true;
}
return false;
}
public SnakeHead getSnakeHead() {
return (SnakeHead) parts.get(0);
}
public SnakeBody getSnakeBody(int i) {
return parts.get(i);
}
public int getLength() {
return parts.size();
}
}
|
gpl-3.0
|
DigitalCookiesGroup/SWEDesigner
|
Front-End/node_modules/@uirouter/core/lib/transition/interface.js
|
852
|
"use strict";
var TransitionHookPhase;
(function (TransitionHookPhase) {
TransitionHookPhase[TransitionHookPhase["CREATE"] = 0] = "CREATE";
TransitionHookPhase[TransitionHookPhase["BEFORE"] = 1] = "BEFORE";
TransitionHookPhase[TransitionHookPhase["RUN"] = 2] = "RUN";
TransitionHookPhase[TransitionHookPhase["SUCCESS"] = 3] = "SUCCESS";
TransitionHookPhase[TransitionHookPhase["ERROR"] = 4] = "ERROR";
})(TransitionHookPhase = exports.TransitionHookPhase || (exports.TransitionHookPhase = {}));
var TransitionHookScope;
(function (TransitionHookScope) {
TransitionHookScope[TransitionHookScope["TRANSITION"] = 0] = "TRANSITION";
TransitionHookScope[TransitionHookScope["STATE"] = 1] = "STATE";
})(TransitionHookScope = exports.TransitionHookScope || (exports.TransitionHookScope = {}));
//# sourceMappingURL=interface.js.map
|
gpl-3.0
|
lucasjkr/opencommerce
|
system/library/squareup/exception.php
|
2480
|
<?php
namespace Squareup;
class Exception extends \Exception {
const ERR_CODE_ACCESS_TOKEN_REVOKED = 'ACCESS_TOKEN_REVOKED';
const ERR_CODE_ACCESS_TOKEN_EXPIRED = 'ACCESS_TOKEN_EXPIRED';
private $config;
private $log;
private $language;
private $errors;
private $isCurlError;
private $overrideFields = array(
'billing_address.country',
'shipping_address.country',
'email_address',
'phone_number'
);
public function __construct($registry, $errors, $is_curl_error = false) {
$this->errors = $errors;
$this->isCurlError = $is_curl_error;
$this->config = $registry->get('config');
$this->log = $registry->get('log');
$this->language = $registry->get('language');
$message = $this->concatErrors();
if ($this->config->get('config_error_log')) {
$this->log->write($message);
}
parent::__construct($message);
}
public function isCurlError() {
return $this->isCurlError;
}
public function isAccessTokenRevoked() {
return $this->errorCodeExists(self::ERR_CODE_ACCESS_TOKEN_REVOKED);
}
public function isAccessTokenExpired() {
return $this->errorCodeExists(self::ERR_CODE_ACCESS_TOKEN_EXPIRED);
}
protected function errorCodeExists($code) {
if (is_array($this->errors)) {
foreach ($this->errors as $error) {
if ($error['code'] == $code) {
return true;
}
}
}
return false;
}
protected function overrideError($field) {
return $this->language->get('squareup_override_error_' . $field);
}
protected function parseError($error) {
if (!empty($error['field']) && in_array($error['field'], $this->overrideFields)) {
return $this->overrideError($error['field']);
}
$message = $error['detail'];
if (!empty($error['field'])) {
$message .= sprintf($this->language->get('squareup_error_field'), $error['field']);
}
return $message;
}
protected function concatErrors() {
$messages = [];
if (is_array($this->errors)) {
foreach ($this->errors as $error) {
$messages[] = $this->parseError($error);
}
} else {
$messages[] = $this->errors;
}
return implode(' ', $messages);
}
}
|
gpl-3.0
|
ithaca/visu
|
VisuServeur/visu/src/com/lyon2/utils/UserAccountHelpers.java
|
3804
|
/**
* Copyright Université Lyon 1 / Université Lyon 2 (2009,2010)
*
* <ithaca@liris.cnrs.fr>
*
* This file is part of Visu.
*
* This software is a computer program whose purpose is to provide an
* enriched videoconference application.
*
* Visu is a free software subjected to a double license.
* You can redistribute it and/or modify since you respect the terms of either
* (at least one of the both license) :
* - the GNU Lesser General Public License as published by the Free Software Foundation;
* either version 3 of the License, or any later version.
* - the CeCILL-C as published by CeCILL; either version 2 of the License, or any later version.
*
* -- GNU LGPL license
*
* Visu is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Visu is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Visu. If not, see <http://www.gnu.org/licenses/>.
*
* -- CeCILL-C license
*
* This software is governed by the CeCILL-C license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-C
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-C license and that you accept its terms.
*
* -- End of licenses
*/
package com.lyon2.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class UserAccountHelpers
{
public static String key (int nb)
{
Random rand = new Random();
String password = new String();
String dico = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
int size = dico.length();
for(int i = 0; i < nb ; ++i)
{
password += dico.charAt( rand.nextInt(size) );
}
return password;
}
public static String md5(String str)
{
String hash = new String();
try
{
String s="test";
MessageDigest m=MessageDigest.getInstance("MD5");
m.update(s.getBytes(),0,s.length());
hash = new BigInteger( 1,m.digest()).toString(16);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return hash;
}
}
|
gpl-3.0
|
1313ou/TreebolicLib
|
treebolicGlue/src/main/java/treebolic/glue/component/Utils.java
|
5780
|
/*
* Copyright (c) 2019. Bernard Bou <1313ou@gmail.com>
*/
package treebolic.glue.component;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.TypedValue;
import android.view.Display;
import android.view.WindowManager;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.graphics.drawable.DrawableCompat;
/**
* Utilities
*
* @author Bernard Bou
*/
@SuppressWarnings("WeakerAccess")
public class Utils
{
@NonNull
static public int[] fetchColors(@NonNull final Context context, @NonNull int... attrs)
{
final TypedValue typedValue = new TypedValue();
final TypedArray array = context.obtainStyledAttributes(typedValue.data, attrs);
final int[] colors = new int[attrs.length];
for (int i = 0; i < attrs.length; i++)
{
colors[i] = array.getColor(i, 0);
}
array.recycle();
return colors;
}
/*
* Get color from theme
*
* @param context context
* @param styleId style id (ex: R.style.MyTheme)
* @param colorAttrIds attr ids (ex: R.attr.editTextColor)
* @return colors
*/
/*
@SuppressWarnings("WeakerAccess")
@NonNull
static public int[] fetchColorsFromStyle(@NonNull final Context context, @NonNull int styleId, @NonNull int... colorAttrIds)
{
final TypedArray array = context.obtainStyledAttributes(styleId, colorAttrIds);
final int[] colors = new int[colorAttrIds.length];
for (int i = 0; i < colorAttrIds.length; i++)
{
colors[i] = array.getColor(i, 0);
}
array.recycle();
return colors;
}
*/
@NonNull
static public Integer[] fetchColorsNullable(@NonNull final Context context, @NonNull @SuppressWarnings("SameParameterValue") int... attrs)
{
final TypedValue typedValue = new TypedValue();
final TypedArray array = context.obtainStyledAttributes(typedValue.data, attrs);
final Integer[] colors = new Integer[attrs.length];
for (int i = 0; i < attrs.length; i++)
{
colors[i] = array.hasValue(i) ? array.getColor(i, 0) : null;
}
array.recycle();
return colors;
}
/*
static public int fetchColor(final Context context, int attr)
{
final TypedValue typedValue = new TypedValue();
final Resources.Theme theme = context.getTheme();
theme.resolveAttribute(attr, typedValue, true);
return typedValue.data;
}
*/
/*
static public Integer fetchColorNullable(final Context context, int attr)
{
final TypedValue typedValue = new TypedValue();
final Resources.Theme theme = context.getTheme();
theme.resolveAttribute(attr, typedValue, true);
return typedValue.type == TypedValue.TYPE_NULL ? null : typedValue.data;
}
*/
static public int getColor(@NonNull final Context context, @ColorRes @SuppressWarnings("SameParameterValue") int resId)
{
return ContextCompat.getColor(context, resId);
}
/**
* Get drawable
*
* @param context context
* @param resId drawable id
* @return drawable
*/
static public Drawable getDrawable(@NonNull final Context context, @DrawableRes int resId)
{
return ResourcesCompat.getDrawable(context.getResources(), resId, context.getTheme());
}
/**
* Get drawables
*
* @param context context
* @param resIds drawable ids
* @return drawables
*/
@NonNull
static public Drawable[] getDrawables(@NonNull final Context context, @NonNull @SuppressWarnings("SameParameterValue") int... resIds)
{
final Resources resources = context.getResources();
final Resources.Theme theme = context.getTheme();
Drawable[] drawables = new Drawable[resIds.length];
for (int i = 0; i < resIds.length; i++)
{
drawables[i] = ResourcesCompat.getDrawable(resources, resIds[i], theme);
}
return drawables;
}
static public void tint(@NonNull final Drawable drawable, @ColorInt int iconTint)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
drawable.setTint(iconTint);
}
else
{
DrawableCompat.setTint(DrawableCompat.wrap(drawable), iconTint);
}
}
static public int screenWidth(@NonNull final Context context)
{
final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
assert wm != null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
{
final Rect bounds = wm.getCurrentWindowMetrics().getBounds();
return bounds.width();
}
else
{
final Display display = wm.getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
// int height = size.y;
return size.x;
}
}
static public Point screenSize(@NonNull final Context context)
{
final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
assert wm != null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
{
final Rect bounds = wm.getCurrentWindowMetrics().getBounds();
return new Point(bounds.width(),bounds.height());
}
else
{
final Display display = wm.getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
return size;
}
}
public static String join(@NonNull final CharSequence delim, @Nullable final CharSequence[] strs)
{
if (strs == null)
{
return "";
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (CharSequence str : strs)
{
if (str == null || str.length() == 0)
{
continue;
}
if (first)
{
first = false;
}
else
{
sb.append(delim);
}
sb.append(str);
}
return sb.toString();
}
}
|
gpl-3.0
|
alfrenovsky/Digesto
|
db/migrate/20110908115724_create_permissions.rb
|
240
|
class CreatePermissions < ActiveRecord::Migration
def self.up
create_table :permissions do |t|
t.integer :role_id
t.integer :user_id
t.timestamps
end
end
def self.down
drop_table :permissions
end
end
|
gpl-3.0
|
gerddie/mia
|
src/2dsegment-local-cmeans.cc
|
17671
|
/* -*- mia-c++ -*-
*
* This file is part of MIA - a toolbox for medical image analysis
* Copyright (c) Leipzig, Madrid 1999-2017 Gert Wollny
*
* MIA is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MIA; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <mia/core/histogram.hh>
#include <mia/core/cmdlineparser.hh>
#include <mia/core/cmeans.hh>
#include <mia/2d.hh>
#include <memory>
#include <vector>
#include <numeric>
using namespace mia;
using namespace std;
typedef vector<C2DFImage> C2DFImageVec;
const SProgramDescription g_description = {
{pdi_group, "Analysis, filtering, combining, and segmentation of 2D images"},
{pdi_short, "Run a c-means segmentation of a 2D image."},
{
pdi_description, "This program runs the segmentation of a 2D image by applying "
"a localized c-means approach that helps to overcome intensity inhomogeneities "
"in the image. The approach evaluates a global c-means clustering, and then "
"separates the image into overlapping regions where more c-means iterations "
"are run only including the locally present classes, i.e. the classes that "
"relatively contain more pixels than a given threshold. This program implements "
"a 2D prototype of the algorithm described in: "
"[Dunmore CJ, Wollny G, Skinner MM. (2018) MIA-Clustering: a novel method "
"for segmentation of paleontological material. PeerJ 6:e4374.](https://doi.org/10.7717/peerj.4374)"
},
{
pdi_example_descr, "Run the segmentation on image test.png using three classes, "
"local regions of 40 pixels (grid width 20 pixels), and a class ignore threshold of 0.01."
},
{pdi_example_code, "-i test.png -o label.png -n 3 -g 20 -t 0.01"}
};
class FRunHistogram : public TFilter<void>
{
public:
template <typename T>
void operator()(const T2DImage<T>& image);
CSparseHistogram::Compressed get_histogram() const;
private:
CSparseHistogram m_sparse_histogram;
};
class FLocalCMeans: public TFilter<void>
{
public:
typedef map<int, CMeans::DVector> Probmap;
FLocalCMeans(float epsilon, const vector<double>& global_class_centers,
const C2DBounds& start, const C2DBounds& end,
const Probmap& global_probmap,
float rel_cluster_threshold,
const map<int, unsigned>& segmap,
vector<C2DFDatafield>& prob_buffer);
template <typename T>
void operator()(const T2DImage<T>& image);
private:
const float m_epsilon;
const vector<double>& m_global_class_centers;
const C2DBounds m_start;
const C2DBounds m_end;
const Probmap& m_global_probmap;
const float m_rel_cluster_threshold;
const map<int, unsigned>& m_segmap;
vector<C2DFDatafield>& m_prob_buffer;
size_t m_count;
};
class FCrispSeg: public TFilter<P2DImage>
{
public:
FCrispSeg(const map<int, unsigned>& segmap):
m_segmap(segmap)
{
}
template <typename T>
P2DImage operator()(const T2DImage<T>& image) const
{
P2DImage out_image = make_shared<C2DUBImage>(image.get_size());
C2DUBImage *help = static_cast<C2DUBImage *>(out_image.get());
transform(image.begin(), image.end(), help->begin(),
[this](T x) {
return m_segmap.at(x);
});
return out_image;
}
private:
const map<int, unsigned>& m_segmap;
};
int do_main(int argc, char *argv[])
{
string in_filename;
string out_filename;
string out_filename2;
string cls_filename;
string debug_filename;
int blocksize = 15;
double rel_cluster_threshold = 0.02;
float cmeans_epsilon = 0.0001;
CMeans::PInitializer class_center_initializer;
const auto& image2dio = C2DImageIOPluginHandler::instance();
CCmdOptionList opts(g_description);
opts.set_group("File-IO");
opts.add(make_opt( in_filename, "in-file", 'i', "image to be segmented",
CCmdOptionFlags::required_input, &image2dio ));
opts.add(make_opt( out_filename, "out-file", 'o', "class label image based on "
"merging local labels", CCmdOptionFlags::output, &image2dio ));
opts.add(make_opt( out_filename2, "out-global-crisp", 'G', "class label image based on "
"global segmentation", CCmdOptionFlags::output, &image2dio ));
opts.add(make_opt( cls_filename, "class-prob", 'C', "class probability image file, filetype "
"must support floating point multi-frame images", CCmdOptionFlags::output, &image2dio ));
opts.set_group("Parameters");
opts.add(make_opt( blocksize, EParameterBounds::bf_min_closed, {3},
"grid-spacing", 'g', "Spacing of the grid used to modulate "
"the intensity inhomogeneities"));
opts.add(make_opt( class_center_initializer, "kmeans:nc=3",
"cmeans", 'c', "c-means initializer"));
opts.add(make_opt( cmeans_epsilon, EParameterBounds::bf_min_open,
{0.0}, "c-means-epsilon", 'e', "c-means breaking condition for update tolerance"));
opts.add(make_opt( rel_cluster_threshold, EParameterBounds::bf_min_closed | EParameterBounds::bf_max_open,
{0.0, 1.0}, "relative-cluster-threshold", 't', "threshhold to ignore classes when initializing"
" the local cmeans from the global one."));
if (opts.parse(argc, argv) != CCmdOptionList::hr_no)
return EXIT_SUCCESS;
if (out_filename.empty() && out_filename2.empty()) {
throw invalid_argument("You must specify at least one output file");
}
auto in_image = load_image2d(in_filename);
FRunHistogram global_histogram;
mia::accumulate(global_histogram, *in_image);
CMeans globale_cmeans(cmeans_epsilon, class_center_initializer);
auto gh = global_histogram.get_histogram();
CMeans::DVector global_class_centers;
auto global_sparse_probmap = globale_cmeans.run(gh, global_class_centers, false);
cvinfo() << "Histogram range: [" << gh[0].first << ", " << gh[gh.size() - 1].first << "]\n";
cvinfo() << "Global class centers: " << global_class_centers << "\n";
cvinfo() << "Probmap size = " << global_sparse_probmap.size()
<< " weight number " << global_sparse_probmap[0].second.size() << "\n";
auto n_classes = global_class_centers.size();
// need the normalized class centers
map<int, unsigned> segmap;
for_each(global_sparse_probmap.begin(), global_sparse_probmap.end(),
[&segmap](const CMeans::SparseProbmap::value_type & x) {
int c = 0;
float max_prob = 0.0f;
for (unsigned i = 0; i < x.second.size(); ++i) {
auto f = x.second[i];
if (f > max_prob) {
max_prob = f;
c = i;
};
}
segmap[x.first] = c;
});
FLocalCMeans::Probmap global_probmap;
for (auto k : global_sparse_probmap) {
global_probmap[k.first] = k.second;
};
if (!out_filename2.empty()) {
FCrispSeg cs(segmap);
auto crisp_global_seg = mia::filter(cs, *in_image);
if (!save_image (out_filename2, crisp_global_seg)) {
cverr() << "Unable to save to '" << out_filename2 << "'\n";
}
}
int nx = (in_image->get_size().x + blocksize - 1) / blocksize;
int ny = (in_image->get_size().y + blocksize - 1) / blocksize;
int start_x = (nx * blocksize - in_image->get_size().x) / 2;
int start_y = (ny * blocksize - in_image->get_size().y) / 2;
vector<C2DFDatafield> prob_buffer(global_class_centers.size());
for (unsigned i = 0; i < global_class_centers.size(); ++i)
prob_buffer[i] = C2DFDatafield(in_image->get_size());
for (int iy_base = start_y; iy_base < (int)in_image->get_size().y; iy_base += blocksize) {
unsigned iy = iy_base < 0 ? 0 : iy_base;
unsigned iy_end = iy_base + 2 * blocksize;
if (iy_end > in_image->get_size().y)
iy_end = in_image->get_size().y;
for (int ix_base = start_x; ix_base < (int)in_image->get_size().x; ix_base += blocksize) {
unsigned ix = ix_base < 0 ? 0 : ix_base;
unsigned ix_end = ix_base + 2 * blocksize;
if (ix_end > in_image->get_size().x)
ix_end = in_image->get_size().x;
FLocalCMeans lcm(cmeans_epsilon, global_class_centers,
C2DBounds(ix, iy), C2DBounds(ix_end, iy_end),
global_probmap,
rel_cluster_threshold,
segmap,
prob_buffer);
mia::accumulate(lcm, *in_image);
}
}
// save the prob images ?
// normalize probability images
C2DFImage sum(prob_buffer[0]);
for (unsigned c = 1; c < n_classes; ++c) {
transform(sum.begin(), sum.end(), prob_buffer[c].begin(), sum.begin(),
[](float x, float y) {
return x + y;
});
}
for (unsigned c = 0; c < n_classes; ++c) {
transform(sum.begin(), sum.end(), prob_buffer[c].begin(), prob_buffer[c].begin(),
[](float s, float p) {
return p / s;
});
}
if (!cls_filename.empty()) {
C2DImageIOPluginHandler::Instance::Data classes;
for (unsigned c = 0; c < n_classes; ++c)
classes.push_back(make_shared<C2DFImage>(prob_buffer[c]));
if (!C2DImageIOPluginHandler::instance().save(cls_filename, classes))
cverr() << "Error writing class images to '" << cls_filename << "'\n";
}
// now for each pixel we have a probability sume that should take inhomogeinities
// into account
C2DUBImage out_image(in_image->get_size(), *in_image);
fill(out_image.begin(), out_image.end(), 0);
for (unsigned c = 1; c < n_classes; ++c) {
auto iout = out_image.begin();
auto eout = out_image.end();
auto itest = prob_buffer[0].begin();
auto iprob = prob_buffer[c].begin();
while ( iout != eout ) {
if (*itest < *iprob) {
*itest = *iprob;
*iout = c;
}
++iout;
++itest;
++iprob;
}
}
return save_image(out_filename, out_image) ? EXIT_SUCCESS : EXIT_FAILURE;
}
template <typename T>
void FRunHistogram::operator()(const T2DImage<T>& image)
{
m_sparse_histogram(image.begin(), image.end());
}
CSparseHistogram::Compressed FRunHistogram::get_histogram() const
{
return m_sparse_histogram.get_compressed_histogram();
}
FLocalCMeans::FLocalCMeans(float epsilon, const vector<double>& global_class_centers,
const C2DBounds& start, const C2DBounds& end,
const Probmap& global_probmap,
float rel_cluster_threshold,
const map<int, unsigned>& segmap,
vector<C2DFDatafield>& prob_buffer):
m_epsilon(epsilon),
m_global_class_centers(global_class_centers),
m_start(start),
m_end(end),
m_global_probmap(global_probmap),
m_rel_cluster_threshold(rel_cluster_threshold),
m_segmap(segmap),
m_prob_buffer(prob_buffer),
m_count((m_end - m_start).product())
{
}
template <typename T>
void FLocalCMeans::operator()(const T2DImage<T>& image)
{
cvmsg() << "Start subrange [" << m_start << "]-[" << m_end << "]\n";
// obtain the histogram for the current patch
CSparseHistogram histogram;
histogram(image.begin_range(m_start, m_end),
image.end_range(m_start, m_end));
auto ch = histogram.get_compressed_histogram();
// calculate the class avaliability in the patch
vector<double> partition(m_global_class_centers.size());
for (auto idx : ch) {
const double n = idx.second;
auto v = m_global_probmap.at(idx.first);
transform(partition.begin(), partition.end(), v.begin(),
partition.begin(), [n](double p, double value) {
return p + n * value;
});
}
auto part_thresh = std::accumulate(partition.begin(), partition.end(), 0.0) * m_rel_cluster_threshold;
cvinfo() << "Partition = " << partition << "\n";
// select the classes that should be used further on
vector<double> retained_class_centers;
vector<unsigned> used_classed;
for (unsigned i = 0; i < partition.size(); ++i) {
if (partition[i] >= part_thresh) {
retained_class_centers.push_back(m_global_class_centers[i]);
used_classed.push_back(i);
}
}
// prepare linear interpolation summing
auto center = C2DFVector((m_end + m_start)) / 2.0f;
auto max_distance = C2DFVector((m_end - m_start)) / 2.0f;
if (retained_class_centers.size() > 1) {
ostringstream cci_descr;
cci_descr << "predefined:cc=[" << retained_class_centers << "]";
cvinfo() << "Initializing local cmeans with '" << cci_descr.str()
<< " for retained classes " << used_classed << "'\n";
auto cci = CMeansInitializerPluginHandler::instance().produce(cci_descr.str());
// remove data that was globally assigned to now unused class
CSparseHistogram::Compressed cleaned_histogram;
cleaned_histogram.reserve(ch.size());
// copy used intensities
for (auto c : used_classed) {
for (auto ich : ch) {
if ( m_segmap.at(ich.first) == c) {
cleaned_histogram.push_back(ich);
}
}
}
// evluate the local c-means classification
CMeans local_cmeans(m_epsilon, cci);
auto local_map = local_cmeans.run(cleaned_histogram, retained_class_centers);
// create a lookup map intensity -> probability vector
map<unsigned short, CMeans::DVector> mapper;
for (auto i : local_map) {
mapper[i.first] = i.second;
}
// now add the new probabilities to the global maps.
auto ii = image.begin_range(m_start, m_end);
auto ie = image.end_range(m_start, m_end);
while (ii != ie) {
auto probs = mapper.find(*ii);
auto delta = (C2DFVector(ii.pos()) - center) / max_distance;
float lin_scale = (1.0 - std::fabs(delta.x)) * (1.0 - std::fabs(delta.y));
if (probs != mapper.end()) {
for (unsigned c = 0; c < used_classed.size(); ++c) {
m_prob_buffer[used_classed[c]](ii.pos()) += lin_scale * probs->second[c];
}
} else { // not in local map: retain global probabilities
auto v = m_global_probmap.at(*ii);
for (unsigned c = 0; c < v.size(); ++c) {
m_prob_buffer[c](ii.pos()) += lin_scale * v[c];
}
}
++ii;
}
} else { // only one class retained, add 1.0 to probabilities, linearly smoothed
cvdebug() << "Only one class used:" << used_classed[0] << "\n";
auto ii = m_prob_buffer[used_classed[0]].begin_range(m_start, m_end);
auto ie = m_prob_buffer[used_classed[0]].end_range(m_start, m_end);
while (ii != ie) {
auto delta = (C2DFVector(ii.pos()) - center) / max_distance;
*ii += (1.0 - std::fabs(delta.x)) * (1.0 - std::fabs(delta.y)); ;
++ii;
}
}
cvmsg() << "Done subrange [" << m_start << "]-[" << m_end << "]\n";
}
#include <mia/internal/main.hh>
MIA_MAIN(do_main);
|
gpl-3.0
|
oeru/techblog
|
drupal8/modules/at_tools/at_theme_generator/starterkits/starterkit/layout/plugin-layout-flex/css/threecol-2-8-2.css
|
2319
|
.atl__lr {
margin: 0 -0.625em;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
}
.atl__lc {
-webkit-flex: 0 0 auto;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
padding: 0 0.625em;
width: 100%;
}
.bp--at-core-simple-tablet-isolate .atl--threecol-2-8-2.l-ac--1-2 > .atl__cw > .atl__lc:first-child,
.bp--at-core-simple-wide .atl--threecol-2-8-2.l-ac--1-2 > .atl__cw > .atl__lc:first-child {
width: 83.33333%;
}
.bp--at-core-simple-tablet-isolate .atl--threecol-2-8-2.l-ac--1-2 > .atl__cw > .atl__lc:last-child,
.bp--at-core-simple-wide .atl--threecol-2-8-2.l-ac--1-2 > .atl__cw > .atl__lc:last-child {
width: 16.66667%;
}
.bp--at-core-simple-tablet-isolate .atl--threecol-2-8-2.l-ac--1-3 > .atl__cw > .atl__lc:first-child,
.bp--at-core-simple-wide .atl--threecol-2-8-2.l-ac--1-3 > .atl__cw > .atl__lc:first-child {
width: 83.33333%;
}
.bp--at-core-simple-tablet-isolate .atl--threecol-2-8-2.l-ac--1-3 > .atl__cw > .atl__lc:last-child,
.bp--at-core-simple-wide .atl--threecol-2-8-2.l-ac--1-3 > .atl__cw > .atl__lc:last-child {
width: 16.66667%;
}
.bp--at-core-simple-tablet-isolate .atl--threecol-2-8-2.l-ac--2-3 > .atl__cw > .atl__lc,
.bp--at-core-simple-wide .atl--threecol-2-8-2.l-ac--2-3 > .atl__cw > .atl__lc {
width: 50%;
}
.bp--at-core-simple-tablet-isolate .atl--threecol-2-8-2.l-arc--3 > .atl__cw > .atl__lc:nth-child(2), .bp--at-core-simple-tablet-isolate .atl--threecol-2-8-2.l-arc--3 > .atl__cw > .atl__lc:last-child {
width: 50%;
}
.bp--at-core-simple-wide .atl--threecol-2-8-2.l-arc--3 > .atl__cw > .atl__lc:first-child {
width: 66.66667%;
-webkit-order: 2;
-ms-flex-order: 2;
order: 2;
}
.bp--at-core-simple-wide .atl--threecol-2-8-2.l-arc--3 > .atl__cw > .atl__lc:nth-child(2) {
width: 16.66667%;
-webkit-order: 1;
-ms-flex-order: 1;
order: 1;
}
.bp--at-core-simple-wide .atl--threecol-2-8-2.l-arc--3 > .atl__cw > .atl__lc:last-child {
width: 16.66667%;
-webkit-order: 3;
-ms-flex-order: 3;
order: 3;
}
|
gpl-3.0
|
ritazh/xplat
|
tests/acceptance/notification-test.js
|
1845
|
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from 'azureexplorer/tests/helpers/start-app';
module('Integration | Notifications', {
afterEach: function() {
Ember.run(this.application, 'destroy');
this.store = null;
}
});
test('Notifications show up for batch download', function (assert) {
this.application = startApp({}, assert);
this.store = this.application.__container__.lookup('store:main');
Ember.run(() => {
this.store.findAll('account').then(accounts => {
accounts.content.forEach(account => {
account.record.deleteRecord();
account.record.save();
});
});
});
andThen(() => {
Ember.run(() => {
let newAccount = this.store.createRecord('account', {
name: 'Testaccount',
key: 'n+ufPpP3UwY+REvC3/zqBmHt2hCDdI06tQI5HFN7XnpUR5VEKMI+8kk/ez7QLQ3Cmojt/c1Ktaug3nK8FC8AeA==',
active: true
});
newAccount.save();
});
visit('/');
});
andThen(function () {
visit('/explorer').then(function () {
// replace file input as text box to avoid native dialog displaying
Ember.$('#nwSaveDirectory').attr('type', 'text');
Ember.$('#nwSaveInput').attr('type', 'text');
// select all blobs
return click('#selectAllCheckbox');
})
.then(function () {
return click('.fa-download');
})
.then(function () {
return triggerEvent('#nwSaveDirectory', 'change');
})
.then(function () {
return click('.handle');
})
.then(function () {
assert.equal(find('.mdi-action-done').length, 4);
});
});
});
|
gpl-3.0
|
psy0rz/ledanim
|
web/repo/xmas/sparkle.js
|
390
|
// sparkly effect for xmas stuff
// a blue icey glow with occasional sparkles
// sparkles
led.led_rnd(0, led.leds);
led.color(255, 255, 255);
led.fade_mode(2);
led.fade_speed(20);
led.draw();
//blue glow
led.repeat_begin_rnd(0,100);
led.led_rnd(0, led.leds);
led.color_rnd(0, 0, 0, 0, 100, 250);
led.fade_mode(1);
led.fade_speed(1);
led.draw();
led.delay(0);
led.repeat_end();
|
gpl-3.0
|
Rise-Vision/rise-vision-app-launcher
|
web/partials/schedules/share-schedule-popover.html
|
6419
|
<div id="shareSchedulePopover" ng-controller="SharedSchedulePopoverController" class="share-schedule-popover">
<div class="row">
<div class="col-xs-12">
<button type="button" class="close" ng-click="dismiss()" aria-hidden="true">
<streamline-icon name="close" width="10" height="10"></streamline-icon>
</button>
<span class="text-sm font-weight-bold" ng-show="currentTab === 'link'">Share</span>
<a class="text-sm font-weight-bold u_float-left" href="#" ng-click="currentTab = 'link'" ng-show="currentTab !== 'link'">← Go Back</a>
<div>
<span class="text-sm font-weight-bold aligner" ng-show="currentTab === 'chromeExtension'">Chrome Extension</span>
<span class="text-sm font-weight-bold aligner" ng-show="currentTab === 'embedCode'">Embed</span>
</div>
</div>
</div>
<div ng-show="currentTab === 'link'" class="row u_margin-sm-top">
<div class="col-xs-12">
<div class="u_scroll-x text-center sideways-panels scrollbox pb-4">
<div id="extensionButton" class="panel panel-default u_remove-bottom u_clickable" ng-click="currentTab = 'chromeExtension'">
<div class="panel-body">
<div class="row pt-2">
<div class="col-xs-12">
<img src="../images/shared-schedule/google-chrome.svg" height="32">
</div>
</div>
<div class="row pt-4">
<div class="col-xs-12">
<a class="text-sm font-weight-bold" href="#">Chrome Extension</a>
</div>
</div>
</div>
</div>
<div id="embedButton" class="panel panel-default u_remove-bottom u_clickable" ng-click="currentTab = 'embedCode'">
<div class="panel-body">
<div class="row pt-2">
<div class="col-xs-12">
<img src="../images/shared-schedule/embed-icon.svg" height="32">
</div>
</div>
<div class="row pt-4">
<div class="col-xs-12">
<a class="text-sm font-weight-bold" href="#">Embed</a>
</div>
</div>
</div>
</div>
<div class="panel panel-default u_remove-bottom u_clickable" ng-click="shareOnSocial('classroom')">
<div class="panel-body">
<div class="row pt-2">
<div class="col-xs-12">
<img src="../images/shared-schedule/google-classroom.svg" height="32">
</div>
</div>
<div class="row pt-4">
<div class="col-xs-12">
<a class="text-sm font-weight-bold" href="#">Google Classroom</a>
</div>
</div>
</div>
</div>
<div id="twitterShareButton" class="panel panel-default u_remove-bottom u_clickable" ng-click="shareOnSocial('twitter')">
<div class="panel-body">
<div class="row pt-2">
<div class="col-xs-12">
<img src="../images/shared-schedule/twitter.svg" height="32">
</div>
</div>
<div class="row pt-4">
<div class="col-xs-12">
<a class="text-sm font-weight-bold" href="#">Twitter</a>
</div>
</div>
</div>
</div>
<div class="panel panel-default u_remove-bottom u_clickable" ng-click="shareOnSocial('linkedin')">
<div class="panel-body">
<div class="row pt-2">
<div class="col-xs-12">
<img src="../images/shared-schedule/linkedin.svg" height="32">
</div>
</div>
<div class="row pt-4">
<div class="col-xs-12">
<a class="text-sm font-weight-bold" href="#">LinkedIn</a>
</div>
</div>
</div>
</div>
<div class="panel panel-default u_remove-bottom u_clickable" ng-click="shareOnSocial('facebook')">
<div class="panel-body">
<div class="row pt-2">
<div class="col-xs-12">
<img src="../images/shared-schedule/facebook.svg" height="32">
</div>
</div>
<div class="row pt-4">
<div class="col-xs-12">
<a class="text-sm font-weight-bold" href="#">Facebook</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div ng-show="currentTab === 'link'" class="row u_margin-sm-top">
<div class="col-xs-12 aligner">
<input class="form-control copy-text-box w-100" type="text" readonly="readonly" value="{{getLink()}}" ng-focus="onTextFocus($event)" focus-me="currentTab === 'link'"/>
<button id="copyUrlButton" class="btn btn-primary ml-2" ng-click="copyToClipboard(getLink())" aria-label="Copy">Copy</button>
</div>
</div>
<div ng-show="currentTab === 'embedCode'" class="row u_margin-sm-top">
<div class="col-xs-12">
<span class="text-sm font-weight-bold">Embed Code:</span>
<br>
<textarea class="form-control copy-text-box u_margin-sm-top w-100 resize-vertical" rows="10" readonly="readonly" ng-focus="onTextFocus($event)" focus-me="currentTab === 'embedCode'">{{getEmbedCode()}}</textarea>
<button id="copyEmbedCodeButton" class="btn btn-primary u_remove-left u_margin-sm-top w-100" ng-click="copyToClipboard(getEmbedCode())" aria-label="Copy">Copy</button>
</div>
</div>
<div ng-show="currentTab === 'chromeExtension'" class="row u_margin-sm-top">
<div class="col-xs-12">
<span class="text-sm font-weight-bold">Invite Message:</span>
<br>
<textarea class="form-control copy-text-box u_margin-sm-top w-100 resize-vertical" rows="10" readonly="readonly" ng-focus="onTextFocus($event)" focus-me="currentTab === 'chromeExtension'">{{getInviteMessage()}}</textarea>
<button id="copyInviteMessageButton" class="btn btn-primary u_remove-left u_margin-sm-top w-100" ng-click="copyToClipboard(getInviteMessage())" aria-label="Copy">Copy</button>
<a id="chromeExtensionLink" class="btn btn-default u_remove-left u_margin-sm-top w-100" href="https://chrome.google.com/webstore/detail/rise-vision-anywhere/dkoohkdagjpgjheoaaegomjhdccfbcle" target="_blank" aria-label="Install Chrome Extension" ng-click="trackScheduleShared()">Install Chrome Extension</a>
</div>
</div>
</div>
|
gpl-3.0
|
xiaosuo/voipconf
|
lib/ini.php
|
2462
|
<?php
/**
* Ini manipulation
*/
class Ini {
var $m_ini;
function Ini() {
$this->m_ini = Array();
}
function load($fn) {
$this->m_ini = Array();
$fh = fopen($fn, "r");
if (!$fh)
return false;
$section = "";
while (($line = fgets($fh)) !== false) {
$line = trim($line);
// ignore blank lines
if (strlen($line) == 0)
continue;
if (substr($line, 0, 1) == "[") {
if (substr($line, -1) != "]") {
fclose($fh);
return false;
}
$section = substr($line, 1, -1);
continue;
}
list($name, $value) = explode("=", $line, 2);
$name = trim($name);
// TODO: comma separated values?
$value = trim($value);
if (!$this->add($section, $name, $value)) {
fclose($fh);
return false;
}
}
fclose($fh);
return true;
}
function validate($section, $name) {
return $section != "" && $name != "";
}
function get($section, $name) {
if (!$this->validate($section, $name))
return false;
return $this->m_ini[$section][$name];
}
function set($section, $name, $value) {
if (!$this->validate($section, $name))
return false;
$this->m_ini[$section][$name] = $value;
return true;
}
function add($section, $name, $value) {
if (!$this->validate($section, $name))
return false;
if (isset($this->m_ini[$section][$name])) {
if (!is_array($this->m_ini[$section][$name])) {
$ovalue = $this->m_ini[$section][$name];
$this->m_ini[$section][$name] = array();
$this->m_ini[$section][$name][] = $ovalue;
}
$this->m_ini[$section][$name][] = $value;
} else {
$this->m_ini[$section][$name] = $value;
}
return true;
}
function dump($fn) {
$fh = fopen($fn, "w");
if (!$fh)
return false;
foreach (array_keys($this->m_ini) as $section) {
fwrite($fh, "[$section]\n");
foreach (array_keys($this->m_ini[$section]) as $name) {
if (is_array($this->m_ini[$section][$name])) {
foreach ($this->m_ini[$section][$name] as $value)
fwrite($fh, "$name=$value\n");
} else {
fwrite($fh, "$name=" . $this->m_ini[$section][$name] . "\n");
}
}
fwrite($fh, "\n");
}
fclose($fh);
}
function sections() {
return array_keys($this->m_ini);
}
function deleteSection($section) {
if ($section != "")
unset($this->m_ini[$section]);
}
}
/*
$ini = new Ini();
$ini->load("data/sip.conf");
var_dump($ini->get("general", "allow"));
var_dump($ini->get("general", "bindport"));
$ini->dump("sip.conf");
*/
?>
|
gpl-3.0
|
crisis-economics/CRISIS
|
CRISIS/src/eu/crisis_economics/abm/dashboard/Page_Model.java
|
7152
|
/*
* This file is part of CRISIS, an economics simulator.
*
* Copyright (C) 2015 AITIA International, Inc.
* Copyright (C) 2015 John Kieran Phillips
* Copyright (C) 2015 Ariel Y. Hoffman
*
* CRISIS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CRISIS 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 CRISIS. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.crisis_economics.abm.dashboard;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map.Entry;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import ai.aitia.meme.gui.Wizard;
import ai.aitia.meme.gui.Wizard.Button;
import ai.aitia.meme.gui.Wizard.IWizardPage;
import aurelienribon.ui.css.Style;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import eu.crisis_economics.utilities.Pair;
/**
* @author Tamás Máhr
*
*/
public class Page_Model implements IWizardPage, IIconsInHeader {
private static final String CSS_CLASS_COMMON_PANEL = ".commonPanel";
private static final int DECORATION_IMAGE_WIDTH = 600;
private static final String DECORATION_IMAGE = "Decisions.png";
private static final String TITLE = "Model";
private static final String INFO_TEXT = "Please select the model to run!";
private static final int STARTBUTTON_HEIGHT = 50;
private static final int STARTBUTTON_WIDTH = 350;
private Wizard wizard;
private Dashboard dashboard;
private Container container;
public Page_Model(Wizard wizard, final Dashboard dashboard) {
this.wizard = wizard;
this.dashboard = dashboard;
container = initContainer();
}
@Override
public String getInfoText(Wizard wizard) {
return wizard.getArrowsHeader(INFO_TEXT);
}
@Override
public Icon getIcon() {
return new ImageIcon(getClass().getResource("icons/bank.png"));
}
@Override
public Container getPanel() {
// ImageIcon buttonIcon = new ImageIcon(getClass().getResource("white-background-gold-button-hi.png"));
// buttonIcon = new ImageIcon(buttonIcon.getImage().getScaledInstance(STARTBUTTON_WIDTH, -STARTBUTTON_HEIGHT, java.awt.Image.SCALE_SMOOTH));
//
// int buttonHeight = buttonIcon.getIconHeight();
// int buttonWidth = buttonIcon.getIconWidth();
return container;
}
private Container initContainer() {
// BufferedImage image = null;
// try {
// image = ImageIO.read(getClass().getResource(DECORATION_IMAGE));
// } catch (IOException e) {
// throw new IllegalStateException(e);
// }
//
// ImageIcon imageIcon = new ImageIcon(image.getScaledInstance(DECORATION_IMAGE_WIDTH, -1, BufferedImage.SCALE_SMOOTH));
JLabel label = null;
label = new JLabel(new ImageIcon(new ImageIcon(getClass().getResource(DECORATION_IMAGE)).getImage().getScaledInstance(DECORATION_IMAGE_WIDTH, -1, Image.SCALE_SMOOTH)));
// label = new JLabel(imageIcon);
// label.setOpaque(true);
final DefaultFormBuilder
buttonFormBuilder = FormsUtils.build("p ~ p", "");
for (final Entry<String, Pair<String, Color>> record :
Dashboard.availableModels.entrySet()) {
final String
modelURI = record.getKey(),
modelName = record.getValue().getFirst();
final Color
buttonColor = record.getValue().getSecond();
JButton button = new JButton(
"<html><p align='center'>" + modelName + "</html>");
button.setPreferredSize(new Dimension(STARTBUTTON_WIDTH, STARTBUTTON_HEIGHT));
button.setBackground(buttonColor);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
IModelHandler modelHandler = null;
try {
modelHandler = dashboard.createModelHandler(modelURI);
} catch (ClassNotFoundException e) {
Logger log = Logger.getLogger(getClass());
log.error("Could not load the model class!", e);
}
try {
modelHandler.getRecorderAnnotationValue();
} catch (Exception e) {
ErrorDialog errorDialog = new ErrorDialog(wizard, "No recorder specified", "The model does not have '@RecorderSource' annotation");
errorDialog.show();
return;
}
dashboard.setTitle(modelName.substring(modelName.lastIndexOf('.') + 1));
wizard.gotoPage(1);
}
});
}
});
buttonFormBuilder.append(button);
}
final JButton loadButton = new JButton("<html><p align='center'>Load model configuration..." + "</html>");
loadButton.setPreferredSize(new Dimension(STARTBUTTON_WIDTH, STARTBUTTON_HEIGHT));
loadButton.setBackground(new Color(60, 193, 250));
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent _) {
dashboard.loadConfiguration();
}
});
buttonFormBuilder.append(loadButton);
JPanel buttonPanel = buttonFormBuilder.getPanel();
Style.registerCssClasses(buttonPanel, CSS_CLASS_COMMON_PANEL);
JPanel panel = FormsUtils.build("p ~ f:p:g",
"01 f:p:g",
label, buttonPanel, CellConstraints.CENTER).getPanel();
// panel.setBackground(Color.WHITE);
Style.registerCssClasses(panel, CSS_CLASS_COMMON_PANEL);
final JScrollPane pageScrollPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pageScrollPane.setBorder(null);
pageScrollPane.setViewportBorder(null);
pageScrollPane.setViewportView(panel);
return pageScrollPane;
}
@Override
public boolean isEnabled(Button button) {
switch (button){
case BACK:
return false;
case NEXT:
return false;
case CANCEL: // this is the charts page
return true;
case FINISH:
return false;
case CUSTOM:
return false;
}
return false;
}
@Override
public boolean onButtonPress(Button button) {
return true;
}
@Override
public void onPageChange(boolean show) {
if (show){
dashboard.getSaveConfigMenuItem().setEnabled(false);
dashboard.setTitle(null);
} else {
IModelHandler modelHandler = dashboard.getModelHandler();
if (modelHandler != null){
dashboard.setTitle(modelHandler.getModelClassSimpleName());
}
}
}
@Override
public String getTitle() {
return TITLE;
}
}
|
gpl-3.0
|
rdumitru/lum-scan-matching
|
3rdparty/3dtk-1.2/3rdparty/hogman/aislib/graph_viewer/primitives.h
|
8435
|
// HOG-Man - Hierarchical Optimization for Pose Graphs on Manifolds
// Copyright (C) 2010 G. Grisetti, R. Kümmerle, C. Stachniss
//
// This file is part of HOG-Man.
//
// HOG-Man is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// HOG-Man 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 HOG-Man. If not, see <http://www.gnu.org/licenses/>.
#ifndef PRIMITIVES_H
#define PRIMITIVES_H
/** @addtogroup viewer libviewer **/
// @{
/** \file primitives.h
* \brief draw primitives with OpenGL
*/
#include <qgl.h>
#include <cmath>
/**
* Quadratic used in several drawing functions
*/
extern GLUquadricObj* g_quadratic;
/**
* Call this function before using any of the draw functions
*/
void initPrimitives();
/**
* draw a box that is centered in the current coordinate frame
* @param l length of the box (x dimension)
* @param w width of the box (y dimension)
* @param h height of the box (z dimension)
*/
inline void drawBox(GLfloat l, GLfloat w, GLfloat h)
{
GLfloat sx = l*0.5f;
GLfloat sy = w*0.5f;
GLfloat sz = h*0.5f;
glBegin(GL_QUADS);
// bottom
glNormal3f( 0.0f, 0.0f,-1.0f);
glVertex3f(-sx, -sy, -sz);
glVertex3f(-sx, sy, -sz);
glVertex3f(sx, sy, -sz);
glVertex3f(sx, -sy, -sz);
// top
glNormal3f( 0.0f, 0.0f,1.0f);
glVertex3f(-sx, -sy, sz);
glVertex3f(-sx, sy, sz);
glVertex3f(sx, sy, sz);
glVertex3f(sx, -sy, sz);
// back
glNormal3f(-1.0f, 0.0f, 0.0f);
glVertex3f(-sx, -sy, -sz);
glVertex3f(-sx, sy, -sz);
glVertex3f(-sx, sy, sz);
glVertex3f(-sx, -sy, sz);
// front
glNormal3f( 1.0f, 0.0f, 0.0f);
glVertex3f(sx, -sy, -sz);
glVertex3f(sx, sy, -sz);
glVertex3f(sx, sy, sz);
glVertex3f(sx, -sy, sz);
// left
glNormal3f( 0.0f, -1.0f, 0.0f);
glVertex3f(-sx, -sy, -sz);
glVertex3f(sx, -sy, -sz);
glVertex3f(sx, -sy, sz);
glVertex3f(-sx, -sy, sz);
//right
glNormal3f( 0.0f, 1.0f, 0.0f);
glVertex3f(-sx, sy, -sz);
glVertex3f(sx, sy, -sz);
glVertex3f(sx, sy, sz);
glVertex3f(-sx, sy, sz);
glEnd();
}
/**
* draw a plane in x-y dimension with a height of zero
* @param l length in x
* @param w width in y
*/
inline void drawPlane(GLfloat l, GLfloat w)
{
GLfloat sx = l*0.5f;
GLfloat sy = w*0.5f;
glBegin(GL_QUADS);
glNormal3f( 0.0f, 0.0f, 1.0f);
glVertex3f(-sx, -sy, 0.f);
glVertex3f(-sx, sy, 0.f);
glVertex3f(sx, sy, 0.f);
glVertex3f(sx, -sy, 0.f);
glEnd();
}
/**
* draw a sphere whose center is in the origin of the current coordinate frame
* @param radius the radius of the sphere
*/
inline void drawSphere(GLfloat radius)
{
gluSphere(g_quadratic, radius, 32, 32);
}
/**
* draw a ellipsoid whose center is in the origin of the current coordinate frame
* @param r1 radius along x axis
* @param r2 radius along y axis
* @param r3 radius along z axis
*/
inline void drawEllipsoid(GLfloat r1, GLfloat r2, GLfloat r3)
{
GLboolean hasNormalization = glIsEnabled(GL_NORMALIZE);
if (!hasNormalization)
glEnable(GL_NORMALIZE);
glPushMatrix();
glScalef(r1, r2, r3);
gluSphere(g_quadratic, 1.0, 32, 32);
glPopMatrix();
if (!hasNormalization)
glDisable(GL_NORMALIZE);
}
/**
* draw a cone
*/
inline void drawCone(GLfloat radius, GLfloat height)
{
glPushMatrix();
glRotatef(-90.f, 1.f, 0.f, 0.f);
glTranslatef(0, 0, - height/2.0);
gluCylinder(g_quadratic, radius, 0.f, height, 32, 1);
gluDisk(g_quadratic, 0, radius, 32, 1);
glPopMatrix();
}
/**
* draw a (closed) cylinder
* @param radius the radius of the cylinder
* @param height the height of the cylinder
*/
inline void drawCylinder(GLfloat radius, GLfloat height)
{
glPushMatrix();
glRotatef(-90, 1.f, 0.f, 0.f);
glTranslatef(0, 0, + height/2.0);
gluDisk(g_quadratic, 0, radius, 32, 1);
glTranslatef(0, 0, - height);
gluCylinder(g_quadratic, radius, radius, height, 32, 1);
glRotatef(180, 1.f, 0.f, 0.f);
gluDisk(g_quadratic, 0, radius, 32, 1);
glPopMatrix();
}
/**
* draw a pyramid
*/
inline void drawPyramid(GLfloat length, GLfloat height)
{
glPushMatrix();
glTranslatef(0, 0, - height/2.0);
glRotatef(45, 0.f, 0.f, 1.f);
gluCylinder(g_quadratic, length, 0.f, height, 32, 1);
gluDisk(g_quadratic, 0, length, 32, 1);
glPopMatrix();
}
/**
* draw a range ring
* @param range the range (radius) of the partial ring
* @param fov Field Of View of the range sensor
* @param range_width specify how thick the ring should be drawn
*/
inline void drawRangeRing(GLfloat range, GLfloat fov, GLfloat range_width = 0.05)
{
glPushMatrix();
glRotatef((fov/2.0f) - 90, 0.f, 0.f, 1.f);
gluPartialDisk(g_quadratic, range, range + range_width, 32, 1, 0.f, fov);
glPopMatrix();
}
/**
* draw a slice of a cylinder (approximated with slices_per_circle triangles for the complete circle)
* @param radius the radius of the cylinder
* @param height the height of the cylinder
* @param fov the "fov" of the slice (om degree)
* @param slices_per_circle the number of triangle used to approximate the fulle circle
*/
inline void drawSlice(GLfloat radius, GLfloat height, GLfloat fov, int slices_per_circle = 32)
{
double fov_rad = fov/180.*M_PI; // convert to rad
int num_slices = int(slices_per_circle * (fov_rad / (2*M_PI))) + 1;
double angle_step = fov_rad / num_slices;
double angle_step_half = angle_step * 0.5;
GLfloat height_half = height * 0.5f;
GLfloat lower_z = -height_half;
GLfloat upper_z = height_half;
GLfloat last_x = std::cos(-fov_rad * 0.5) * radius;
GLfloat last_y = std::sin(-fov_rad * 0.5) * radius;
glPushMatrix();
glBegin(GL_TRIANGLES);
glNormal3f(std::sin(-fov_rad * 0.5), -std::cos(-fov_rad * 0.5), -0.f);
glVertex3f(0.f, 0.f, upper_z);
glVertex3f(0.f, 0.f, lower_z);
glVertex3f(last_x, last_y, upper_z);
glVertex3f(last_x, last_y, upper_z);
glVertex3f(last_x, last_y, lower_z);
glVertex3f(0.f, 0.f, lower_z);
double start_angle = -0.5*fov_rad + angle_step;
double angle = start_angle;
for (int i = 0; i < num_slices; ++i) {
GLfloat x = std::cos(angle) * radius;
GLfloat y = std::sin(angle) * radius;
GLfloat front_normal_x = std::cos(angle + angle_step_half);
GLfloat front_normal_y = std::sin(angle + angle_step_half);
// lower triangle
glNormal3f(0.f, 0.f, -1.f);
glVertex3f(0.f, 0.f, lower_z);
glVertex3f(x, y, lower_z);
glVertex3f(last_x, last_y, lower_z);
// upper
glNormal3f(0.f, 0.f, 1.f);
glVertex3f(0.f, 0.f, upper_z);
glVertex3f(x, y, upper_z);
glVertex3f(last_x, last_y, upper_z);
//front rectangle (we use two triangles)
glNormal3f(front_normal_x, front_normal_y, 0.f);
glVertex3f(last_x, last_y, upper_z);
glVertex3f(last_x, last_y, lower_z);
glVertex3f(x, y, upper_z);
glVertex3f(x, y, upper_z);
glVertex3f(x, y, lower_z);
glVertex3f(last_x, last_y, lower_z);
last_x = x;
last_y = y;
angle += angle_step;
}
glNormal3f(-std::sin(fov_rad * 0.5), std::cos(fov_rad * 0.5), -0.f);
glVertex3f(0.f, 0.f, upper_z);
glVertex3f(0.f, 0.f, lower_z);
glVertex3f(last_x, last_y, upper_z);
glVertex3f(last_x, last_y, upper_z);
glVertex3f(last_x, last_y, lower_z);
glVertex3f(0.f, 0.f, lower_z);
glEnd();
glPopMatrix();
}
/**
* draws a box used to represent a 6d pose
*/
void drawPoseBox();
/**
* Draws a 3D arrow along the positive Z axis.
*/
void drawArrow(float length=1.0f, float radius=-1.0f, int nbSubdivisions=12);
/**
* draw a 2D arrow along the x axis with the given len
*/
void drawArrow2D(float len, float head_width, float head_len);
/**
* Draws an XYZ axis, with a given len (default is 1.0).
*
* The axis position and orientation matches the current modelView matrix state: three arrows (red,
* green and blue) of length \p length are drawn along the positive X, Y and Z directions.
*/
void drawAxis(float length = 1.f);
/**
* Draws a grid in the XY plane, centered on (0,0,0) (defined in the current coordinate system).
*/
void drawGrid(float size=1.0f, int nbSubdivisions=10);
// @}
#endif
|
gpl-3.0
|
mda747/dtu_elec2_prog2_semester_project
|
Serial/src/SQL/CustomerDAO.java
|
529
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package SQL;
import java.util.ArrayList;
/**
*
* @author adam279
*/
public interface CustomerDAO {
public Customer getCustomer(int id);
public ArrayList<Customer> getCustomers();
public void addCustomer(Customer customer);
public void deleteCustomer(int id);
public void updateCustomer(Customer customer);
}
|
gpl-3.0
|
Evil-Spirit/AnandamideEditor
|
src/AnandamideWorkspaceTree.cpp
|
29220
|
//------------------------------------------------------------------------------
//
// This file is part of AnandamideEditor
//
// copyright: (c) 2010 - 2016
// authors: Alexey Egorov (FadeToBlack aka EvilSpirit)
// Zakhar Shelkovnikov
// Georgiy Kostarev
//
// mailto: anandamide@mail.ru
// anandamide.script@gmail.com
//
// AnandamideEditor is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// AnandamideEditor 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 AnandamideEditor. If not, see <http://www.gnu.org/licenses/>.
//
//------------------------------------------------------------------------------
#include "AnandamideWorkspaceTree.h"
#include "MainWindow.h"
#include "Anandamide.h"
#include "AnandamideLibrary.h"
#include "AnandamideViewport.h"
#include "XmlSettings.h"
#include "AnandamideViewport.h"
#include "AnandamideLibraryWidget.h"
#include <QFileInfo>
#include <QDir>
//------------------------------------------------------------------------------
//
// TreeItemWorkspace
//
//------------------------------------------------------------------------------
void TreeItemWorkspace::setChanged(bool changed)
{
changeFlag = changed;
QString text = "Default workspace";
if(fileName != QString()) {
text = QFileInfo(fileName).baseName();
}
if(changeFlag)
text.append('*');
setText(text.toLocal8Bit().constData());
}
TreeItemWorkspace::TreeItemWorkspace(QTreeWidget *parent, MainWindow *main_window) : TreeItemBase(parent, main_window) {
setIcon(0, QIcon(":/icons/folder2.png"));
setExpanded(true);
setChanged(false);
}
bool TreeItemWorkspace::addScriptItem(Anandamide::Script *script, const QString& fileName, int tabIndex, EditorWidgetsCollection *collection) {
if(getScriptWorkspaceIndex(script) >= 0) return false;
clearSelection();
TreeItemDepProject* project = new TreeItemDepProject(script, fileName, tabIndex, this);
project->setCollection(collection);
project->setSelected(true);
setChanged(true);
return true;
}
bool TreeItemWorkspace::removeScriptItem(Anandamide::Script *script)
{
int idx = getScriptWorkspaceIndex(script);
if(idx < 0) return false;
QTreeWidgetItem* child = this->child(idx);
TreeItemDepProject* project = dynamic_cast<TreeItemDepProject*>(child);
if(project) {
QList<int> tabs = project->getChildsTabs();
qSort(tabs);
while(tabs.size())
main_window->on_tabWidgetViewports_tabCloseRequested(tabs.takeLast());
}
this->removeChild(child);
delete child;
setChanged(true);
return true;
}
bool TreeItemWorkspace::removeScriptProjectByIndex(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
if(proj->getTabIndex() == tabIndex) {
QTreeWidgetItem* child = this->child(i);
this->removeChild(child);
delete child;
setChanged(true);
return true;
}
}
return false;
}
int TreeItemWorkspace::getScriptWorkspaceIndex(Anandamide::Script *script)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
if(proj->getScript() == script /*|| Anandamide::Str(proj->script->getName()) == Anandamide::Str(script->getName())*/)
return i;
}
return -1;
}
bool TreeItemWorkspace::updateProject(Anandamide::Script *script)
{
// int idx = getScriptWorkspaceIndex(script);
// if(idx < 0) return false;
// TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(idx));
// if(proj == NULL) return false;
// proj->updateChildren();
// return true;
bool res = false;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
if(proj->updateProject(script)) res = true;
}
return res;
}
TreeItemDepProject *TreeItemWorkspace::getScriptProject(Anandamide::Script *script)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
TreeItemDepProject* res = proj->getScriptProject(script);
if(res != NULL) return res;
}
return NULL;
}
TreeItemDepProject *TreeItemWorkspace::getTabIndexProject(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
TreeItemDepProject* res = proj->getTabIndexProject(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
TreeItemDepProject *TreeItemWorkspace::getProjectByFilename(const QString &filename)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* proj = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(proj == NULL) continue;
if(filename == proj->info.fileName)
return proj;
}
return NULL;
}
void TreeItemWorkspace::updateChildren()
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemBase* item = dynamic_cast<TreeItemBase*>(this->child(i));
if(item == NULL) continue;
item->updateChildren();
}
}
EditorWidgetsCollection *TreeItemWorkspace::getCollection(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
EditorWidgetsCollection* res = child->getCollection(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
Anandamide::Script *TreeItemWorkspace::getScript(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
Anandamide::Script* res = child->getScript(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
void TreeItemWorkspace::selectByTabIndex(int tabIndex)
{
clearSelection();
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(child->selectByTabIndex(tabIndex)) return;
}
}
void TreeItemWorkspace::tabMoved(int from, int to)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->tabMoved(from, to);
}
}
void TreeItemWorkspace::resetTabIndex(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->resetTabIndex(tabIndex);
}
}
QString TreeItemWorkspace::getFileName(int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
QString res = child->getFileName(tabIndex);
if(res != QString()) return res;
}
return QString();
}
bool TreeItemWorkspace::setFileName(const QString &filename, int tabIndex)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(child->setFileName(filename, tabIndex)) return true;
}
return false;
}
void TreeItemWorkspace::setShiftOnWheel(bool shift)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->setShiftOnWheel(shift);
}
}
void TreeItemWorkspace::clearSelection()
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->setSelected(false);
}
}
bool TreeItemWorkspace::saveWorkspace()
{
if(fileName == QString()) return false;
return saveWorkspace(fileName);
}
bool TreeItemWorkspace::saveWorkspace(const QString &filename)
{
if(filename == QString()) return false;
CXml_Settings sets;
sets.beginGroup("WorkSpace");
sets.beginGroup("Scripts");
int cntr = 0;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
sets.beginGroup(QString("Script_%1").arg(cntr));
sets.setValue("filename", QFileInfo(filename).absoluteDir().relativeFilePath(child->info.fileName));
sets.endGroup();
child->setSelected(false);
cntr++;
}
sets.endGroup();
sets.setValue("ScriptsCount", cntr);
sets.endGroup();
QFile file( filename );
if ( !file.open(QIODevice::WriteOnly) )
return false;
sets.saveToIO(&file);
file.close();
fileName = filename;
setChanged(false);
return true;
}
bool TreeItemWorkspace::loadWorkspace(const QString &filename)
{
QFile file( filename );
if ( !file.open(QIODevice::ReadOnly) )
return false;
CXml_Settings sets;
if(!sets.loadFromIO(&file)) {
file.close();
return false;
}
file.close();
main_window->closeAllTabs(true, -1);
this->clearChildren();
sets.beginGroup("WorkSpace");
int n = sets.value("ScriptsCount").toInt();
sets.beginGroup("Scripts");
for(int i = 0; i < n; ++i) {
sets.beginGroup(QString("Script_%1").arg(i));
QString fn = sets.value("filename").toString();
sets.endGroup();
if(fn != QString()) {
fn = QFileInfo(filename).absoluteDir().absoluteFilePath(fn);
Anandamide::Script* scr = main_window->createScript();
EditorWidgetsCollection* coll = new EditorWidgetsCollection(main_window);
main_window->currentCollection = coll;
coll->createCollection(main_window);
coll->viewport->shiftFlag = main_window->getShiftFlag();
main_window->setMessangerView(coll);
scr->load(fn.toLocal8Bit().constData());
if(scr->getLogicsCount() <= 0) {
scr->destroy();
continue;
}
// main_window->createTestLibraryForScript(scr);
addScriptItem(scr, fn, -1, coll);
}
}
sets.endGroup();
sets.endGroup();
fileName = filename;
setChanged(false);
selectByTabIndex(-1);
return true;
}
bool TreeItemWorkspace::isWorkspaceChanged()
{
return changeFlag;
}
QTreeWidgetItem *TreeItemWorkspace::getLibraryItem(const QString &libraryName)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
QTreeWidgetItem* item = child->getLibraryItem(libraryName, main_window->currentCollection);
if(item != NULL) return item;
}
return NULL;
}
void TreeItemWorkspace::onStopExecuting()
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->onStopExecuting();
}
}
//------------------------------------------------------------------------------
//
// TreeItemDepProject
//
//------------------------------------------------------------------------------
void TreeItemDepProject::clearCache()
{
while(cache.size())
delete cache.takeFirst();
}
int TreeItemDepProject::getCacheIndex(Anandamide::Script *script)
{
for(int i = 0; i < cache.size(); ++i)
if(cache[i]->script == script)
return i;
return -1;
}
void TreeItemDepProject::saveToCache()
{
clearCache();
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->saveToCache();
cache.append(new DepProjectInfo());
cache.last()->script = child->info.script;
cache.last()->fileName = child->info.fileName;
cache.last()->tabIndex = child->info.tabIndex;
foreach (DepProjectInfo* cc, child->cache) {
cache.last()->childInfo.append(new DepProjectInfo(cc));
}
cache.last()->collection = child->getCollection();
cache.last()->selected = child->info.selected;
}
}
QList<int> TreeItemDepProject::restoreFromCache()
{
QSet<int> unused;
QList<int> tabIndexes;
for(int i = 0; i < cache.size(); ++i)
unused.insert(i);
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
int idx = getCacheIndex(child->info.script);
if(idx < 0) continue;
unused.remove(idx);
child->info.fileName = cache[idx]->fileName;
child->info.tabIndex = cache[idx]->tabIndex;
child->clearCache();
foreach (DepProjectInfo* cc, cache[idx]->childInfo) {
child->cache.append(new DepProjectInfo(cc));
}
child->setCollection(cache[idx]->collection);
child->setSelected(cache[idx]->selected);
child->restoreFromCache();
}
QList<int> unusedList = unused.toList();
foreach (int i, unusedList) {
if(cache[i]->tabIndex >= 0)
tabIndexes.append(cache[i]->tabIndex);
tabIndexes.append( cache[i]->getChildsTabs() );
}
clearCache();
return tabIndexes;
}
TreeItemDepProject::TreeItemDepProject(Anandamide::Script *script, const QString& fileName, int tabIndex, TreeItemBase *parent) : TreeItemBase(parent) {
info.script = script;
info.fileName = fileName;
info.tabIndex = tabIndex;
setIcon(0, QIcon(isTopLevelProject() ? ":/icons/blocks.png" : ":/icons/library.png"));
setExpanded(true);
updateChildren();
}
TreeItemDepProject::~TreeItemDepProject()
{
clearCache();
}
bool TreeItemDepProject::isTopLevelProject()
{
TreeItemDepProject* prg = dynamic_cast<TreeItemDepProject*>(this->parent());
return prg == NULL;
}
void TreeItemDepProject::updateChildren() {
if(Anandamide::Str(info.script->getName()) == Anandamide::Str())
setText("Unnamed Script");
else
setText(info.script->getName());
saveToCache();
clearChildren();
for(int i = 0; i < info.script->getLibraries()->getLibrariesCount(); ++i) {
Anandamide::ScriptLibrary* script_lib = dynamic_cast<Anandamide::ScriptLibrary*>(const_cast<Anandamide::Library*>(info.script->getLibraries()->getLibrary(i)));
if(script_lib == NULL) continue;
if(isScriptUsed(script_lib->getScript())) continue;
/*TreeItemDepProject *item = */new TreeItemDepProject(script_lib->getScript(), QString::fromLocal8Bit(script_lib->getFileName()), -1, this);
}
QList<int> tabIndexes = restoreFromCache();
qSort(tabIndexes);
while(tabIndexes.size()) {
main_window->on_tabWidgetViewports_tabCloseRequested(tabIndexes.takeLast());
}
}
bool TreeItemDepProject::isScriptUsed(Anandamide::Script *script) {
if(info.script == script/* || Anandamide::Str(info.script->getName()) == Anandamide::Str(script->getName())*/)
return true;
TreeItemDepProject* parent = dynamic_cast<TreeItemDepProject*>(this->parent());
if(parent == NULL) return false;
return parent->isScriptUsed(script);
}
Anandamide::Script *TreeItemDepProject::getScript() {return info.script;}
Anandamide::Script *TreeItemDepProject::getScript(int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0)
return info.script;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
Anandamide::Script* res = child->getScript(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
int TreeItemDepProject::getScriptIndex(Anandamide::Script *script)
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(script = child->getScript()) return i;
}
return -1;
}
bool TreeItemDepProject::updateProject(Anandamide::Script *script)
{
bool res = false;
if(script == info.script) {
res = true;
updateChildren();
}
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(child->updateProject(script)) res = true;
}
return res;
}
EditorWidgetsCollection *TreeItemDepProject::getCollection() {return info.collection;}
EditorWidgetsCollection *TreeItemDepProject::getCollection(int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0)
return info.collection;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
EditorWidgetsCollection* res = child->getCollection(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
void TreeItemDepProject::setCollection(EditorWidgetsCollection *collection)
{
info.collection = collection;
}
int TreeItemDepProject::getTabIndex()
{
return info.tabIndex;
}
void TreeItemDepProject::setTabIndex(int tabIndex)
{
info.tabIndex = tabIndex;
}
void TreeItemDepProject::tabMoved(int from, int to)
{
if(info.tabIndex == from)
info.tabIndex = to;
else if(info.tabIndex == to)
info.tabIndex = from;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->tabMoved(from, to);
}
}
void TreeItemDepProject::resetTabIndex(int tabIndex)
{
if(tabIndex >= 0) {
if(info.tabIndex == tabIndex)
info.tabIndex = -1;
else if(info.tabIndex > tabIndex)
info.tabIndex--;
}
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->resetTabIndex(tabIndex);
}
}
void TreeItemDepProject::setShiftOnWheel(bool shift)
{
if(info.collection != NULL)
if(info.collection->isCreated())
info.collection->viewport->shiftFlag = shift;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->setShiftOnWheel(shift);
}
}
void TreeItemDepProject::setSelected(bool selected)
{
info.selected = selected;
QFont f;
if(selected)
f.setBold(true);
this->setFont(0, f);
this->setBackground(0, selected ? QBrush(QColor(230, 193, 193)) : QBrush());
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->setSelected(false);
}
}
bool TreeItemDepProject::selectByTabIndex(int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0) {
setSelected(true);
return true;
}
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(child->selectByTabIndex(tabIndex)) return true;
}
return false;
}
void TreeItemDepProject::createNewTab()
{
if(info.collection == NULL)
info.collection = new EditorWidgetsCollection(main_window);
main_window->currentCollection = info.collection;
if(!info.collection->isCreated())
info.collection->createCollection(main_window);
info.tabIndex = main_window->getTabsCount();
main_window->addCollection(info.collection, info.script->getName(), isTopLevelProject());
Anandamide::Logic *logic = info.script->getLogic(0);
info.collection->editor->setLogic(logic);
info.collection->editor->reset();
info.collection->project_tree->clear();
TreeItemScript *script_item = new TreeItemScript(info.collection->project_tree, main_window, info.script);
info.collection->project_tree->addTopLevelItem(script_item);
script_item->setExpanded(true);
info.collection->library_widget->invalidate();
info.collection->viewport->repaint();
}
QString TreeItemDepProject::getFileName(int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0)
return info.fileName;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
QString res = child->getFileName(tabIndex);
if(res != QString()) return res;
}
return QString();
}
bool TreeItemDepProject::setFileName(const QString &filename, int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0) {
info.fileName = filename;
return true;
}
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(child->setFileName(filename, tabIndex)) return true;
}
return false;
}
QList<int> TreeItemDepProject::getChildsTabs() {
QList<int> res;
if(info.tabIndex >= 0)
res << info.tabIndex;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
res << child->getChildsTabs();
}
return res;
}
QTreeWidgetItem *TreeItemDepProject::getLibraryItem(const QString &libraryName, EditorWidgetsCollection *collection)
{
if(info.collection == collection) {
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
if(QString::fromLocal8Bit( child->info.script->getName() ) == libraryName) return child;
}
}
else {
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
QTreeWidgetItem* item = child->getLibraryItem(libraryName, collection);
if(item != NULL) return item;
}
}
return NULL;
}
TreeItemDepProject *TreeItemDepProject::getChildByName(const QString &name)
{
return dynamic_cast<TreeItemDepProject*>(this->getChildByText(name));
}
void TreeItemDepProject::onStopExecuting()
{
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
child->onStopExecuting();
}
}
TreeItemDepProject *TreeItemDepProject::getScriptProject(Anandamide::Script *script)
{
if(info.script == script)
return this;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
TreeItemDepProject* res = child->getScriptProject(script);
if(res != NULL) return res;
}
return NULL;
}
TreeItemDepProject *TreeItemDepProject::getTabIndexProject(int tabIndex)
{
if(info.tabIndex == tabIndex && tabIndex >= 0)
return this;
for(int i = 0; i < this->childCount(); ++i) {
TreeItemDepProject* child = dynamic_cast<TreeItemDepProject*>(this->child(i));
if(child == NULL) continue;
TreeItemDepProject* res = child->getTabIndexProject(tabIndex);
if(res != NULL) return res;
}
return NULL;
}
//------------------------------------------------------------------------------
//
// AnandamideWorkspaceTree
//
//------------------------------------------------------------------------------
AnandamideWorkspaceTree::AnandamideWorkspaceTree(QWidget *parent) :
QTreeWidget(parent)
{
root = new TreeItemWorkspace(this, main_window);
connect(this,
SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)),
SLOT(onItemDoubleClicked(QTreeWidgetItem*, int)));
}
bool AnandamideWorkspaceTree::addScriptProject(Anandamide::Script *script, const QString &fileName, int tabIndex, EditorWidgetsCollection *collection)
{
return root->addScriptItem(script, fileName, tabIndex, collection);
}
bool AnandamideWorkspaceTree::removeScriptProject(Anandamide::Script *script)
{
return root->removeScriptItem(script);
}
bool AnandamideWorkspaceTree::removeScriptProjectByIndex(int tabIndex)
{
return root->removeScriptProjectByIndex(tabIndex);
}
bool AnandamideWorkspaceTree::isScriptProject(Anandamide::Script *script)
{
return root->getScriptWorkspaceIndex(script) >= 0;
}
bool AnandamideWorkspaceTree::setScriptProject(const QString &fileName)
{
TreeItemDepProject* project = root->getProjectByFilename(fileName);
if(project == NULL) return false;
onItemDoubleClicked(project, 0);
return true;
}
bool AnandamideWorkspaceTree::updateProject(Anandamide::Script *script)
{
return root->updateProject(script);
}
void AnandamideWorkspaceTree::update()
{
root->updateChildren();
}
EditorWidgetsCollection *AnandamideWorkspaceTree::getCollection(int tabIndex)
{
return root->getCollection(tabIndex);
}
Anandamide::Script *AnandamideWorkspaceTree::getScript(int tabIndex)
{
return root->getScript(tabIndex);
}
QString AnandamideWorkspaceTree::getFileName(int tabIndex)
{
return root->getFileName(tabIndex);
}
bool AnandamideWorkspaceTree::setFileName(const QString &filename, int tabIndex)
{
return root->setFileName(filename, tabIndex);
}
void AnandamideWorkspaceTree::newWorkspace()
{
main_window->closeAllTabs(true, -1);
delete root;
root = new TreeItemWorkspace(this, main_window);
}
bool AnandamideWorkspaceTree::saveWorkspace()
{
return root->saveWorkspace();
}
bool AnandamideWorkspaceTree::saveWorkspace(const QString &filename)
{
return root->saveWorkspace(filename);
}
bool AnandamideWorkspaceTree::loadWorkspace(const QString &filename)
{
main_window->setCursorShape(Qt::WaitCursor);
bool res = root->loadWorkspace(filename);
main_window->setCursorShape(Qt::ArrowCursor);
return res;
}
bool AnandamideWorkspaceTree::isWorkspaceChanged()
{
return root->isWorkspaceChanged();
}
void AnandamideWorkspaceTree::clearChanges()
{
root->setChanged(false);
}
bool AnandamideWorkspaceTree::openLibrary(const QString &libraryName)
{
QTreeWidgetItem* item = root->getLibraryItem(libraryName);
if(item == NULL) return false;
onItemDoubleClicked(item, 0);
return true;
}
void AnandamideWorkspaceTree::onStopExecuting()
{
root->clearSelection();
root->onStopExecuting();
}
void AnandamideWorkspaceTree::setCurrentScript(QStringList &logicLibList)
{/*
if(logicLibList.takeLast() != QString()) return;
while(logicLibList.size() && project != NULL) {
project = project->getChildByName(logicLibList.takeLast());
}
onItemDoubleClicked(project, 0);
*/
}
void AnandamideWorkspaceTree::openScriptView(Anandamide::Script *script)
{
TreeItemDepProject* project = root->getScriptProject(script);
if(project == NULL) return;
if(project->getTabIndex() >= 0) {
main_window->setTabIndex(project->getTabIndex());
}
else {
project->createNewTab();
}
}
bool AnandamideWorkspaceTree::isProjectRunning(int tabIndex)
{
if(tabIndex < 0) return false;
TreeItemDepProject* project = root->getTabIndexProject(tabIndex);
while(project != NULL) {
project = dynamic_cast<TreeItemDepProject*>(project->parent());
}
return false;
}
void AnandamideWorkspaceTree::selectByTabIndex(int tabIndex)
{
root->selectByTabIndex(tabIndex);
}
void AnandamideWorkspaceTree::tabMoved(int from, int to)
{
root->tabMoved(from, to);
}
void AnandamideWorkspaceTree::resetTabIndex(int tabIndex)
{
root->resetTabIndex(tabIndex);
}
void AnandamideWorkspaceTree::setShiftOnWheel(bool shift)
{
root->setShiftOnWheel(shift);
}
void AnandamideWorkspaceTree::onItemDoubleClicked(QTreeWidgetItem *tree_item, int column)
{
Q_UNUSED(column);
TreeItemDepProject* project = dynamic_cast<TreeItemDepProject*>(tree_item);
if(project == NULL) return;
root->clearSelection();
project->setSelected(true);
if(project->getTabIndex() >= 0) {
main_window->setTabIndex(project->getTabIndex());
}
else {
project->createNewTab();
}
}
TreeItemDepProject::DepProjectInfo::DepProjectInfo() {
collection = NULL;
selected = false;
}
TreeItemDepProject::DepProjectInfo::DepProjectInfo(TreeItemDepProject::DepProjectInfo *other) {
script = other->script;
fileName = other->fileName;
tabIndex = other->tabIndex;
collection = other->collection;
selected = other->selected;
childCopy(other);
}
void TreeItemDepProject::DepProjectInfo::clear() {
while(childInfo.size()) {
delete childInfo.takeFirst();
}
}
void TreeItemDepProject::DepProjectInfo::childCopy(TreeItemDepProject::DepProjectInfo *other) {
clear();
foreach (DepProjectInfo* cc, other->childInfo) {
childInfo.append(new DepProjectInfo(cc));
}
}
QList<int> TreeItemDepProject::DepProjectInfo::getChildsTabs() {
QList<int> res;
foreach (DepProjectInfo* ci, childInfo) {
if(ci->tabIndex >= 0)
res.append(ci->tabIndex);
res.append( ci->getChildsTabs() );
}
return res;
}
|
gpl-3.0
|
Slaedr/amovemesh
|
src/unused/extra_code.hpp
|
10133
|
/** Unused, mostly useless, code. */
/// Computes circumcentre and circumradius of a [tetrahedron](@ref Tet).
/** NOTE: The tetrahedron's jacobian (2*volume) should be stored in [elem.D](&ref D) beforehand.
* The center and radius of the circumsphere are calculated as follows. The circumcenter is
* \f[ \mathbf{O} = \frac{|\mathbf{a}^2(\mathbf{b}\times \mathbf{c}) + \mathbf{b}^2(\mathbf{c}\times \mathbf{a}) + \mathbf{c}^2(\mathbf{a}\times \mathbf{b})|}{12 V} \f]
* and the radius \f$ R = |\mathbf{O}|\f$.
*/
void Delaunay3d::compute_circumsphere2(Tet& elem)
{
vector<double> a(ndim), b(ndim), c(ndim), n1(ndim), n2(ndim), n3(ndim), fin(ndim);
for(int idim = 0; idim < ndim; idim++)
{
a[idim] = nodes[elem.p[0]][idim]-nodes[elem.p[3]][idim];
b[idim] = nodes[elem.p[1]][idim]-nodes[elem.p[3]][idim];
c[idim] = nodes[elem.p[2]][idim]-nodes[elem.p[3]][idim];
}
cross_product3(n1,b,c);
cross_product3(n2,c,a);
cross_product3(n3,a,b);
for(int idim = 0; idim < ndim; idim++)
{
fin[idim] = dot(a,a)*n1[idim] + dot(b,b)*n2[idim] + dot(c,c)*n3[idim];
fin[idim] /= 2.0*elem.D;
elem.centre[idim] = fin[idim];
}
elem.radius = l2norm(fin);
cout << "Circumsphere data: centre " << elem.centre[0] << "," << elem.centre[1] << "," << elem.centre[2] << ", radius " << elem.radius << ", elem jacobian " << elem.D << endl;
}
/// Computes circumcentre and circumradius of a [tetrahedron](@ref Tet).
/** NOTE: The tetrahedron's jacobian (6*volume) should be stored in [elem.D](@ref elem::D) beforehand.
* Reference: [Weisstein, Eric W. "Circumsphere." From MathWorld--A Wolfram Web Resource.](@ref http://mathworld.wolfram.com/Circumsphere.html)
* \note Probably wrong!
*/
void Delaunay3d::compute_circumsphere3(Tet& elem)
{
Matrix<double> dx(nnode,nnode), dy(nnode,nnode), dz(nnode,nnode), cc(nnode,nnode);
double a = elem.D, c, d_x, d_y, d_z;
#if DEBUGW==1
if(fabs(a) < ZERO_TOL) cout << "Delaunay3d: compute_circumcircle(): ! Jacobian of the element is zero!!" << endl;
#endif
dx(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2];
dx(0,1) = nodes[elem.p[0]][1]; dx(0,2) = nodes[elem.p[0]][2]; dx(0,3) = 1;
dx(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2];
dx(1,1) = nodes[elem.p[1]][1]; dx(1,2) = nodes[elem.p[1]][2]; dx(1,3) = 1;
dx(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2];
dx(2,1) = nodes[elem.p[2]][1]; dx(2,2) = nodes[elem.p[2]][2]; dx(2,3) = 1;
dx(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2];
dx(3,1) = nodes[elem.p[3]][1]; dx(3,2) = nodes[elem.p[3]][2]; dx(3,3) = 1;
dy(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2];
dy(0,1) = nodes[elem.p[0]][0]; dy(0,2) = nodes[elem.p[0]][2]; dy(0,3) = 1;
dy(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2];
dy(1,1) = nodes[elem.p[1]][0]; dy(1,2) = nodes[elem.p[1]][2]; dy(1,3) = 1;
dy(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2];
dy(2,1) = nodes[elem.p[2]][0]; dy(2,2) = nodes[elem.p[2]][2]; dy(2,3) = 1;
dy(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2];
dy(3,1) = nodes[elem.p[3]][0]; dy(3,2) = nodes[elem.p[3]][2]; dy(3,3) = 1;
dz(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2];
dz(0,1) = nodes[elem.p[0]][0]; dz(0,2) = nodes[elem.p[0]][1]; dz(0,3) = 1;
dz(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2];
dz(1,1) = nodes[elem.p[1]][0]; dz(1,2) = nodes[elem.p[1]][1]; dz(1,3) = 1;
dz(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2];
dz(2,1) = nodes[elem.p[2]][0]; dz(2,2) = nodes[elem.p[2]][1]; dz(2,3) = 1;
dz(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2];
dz(3,1) = nodes[elem.p[3]][0]; dz(3,2) = nodes[elem.p[3]][1]; dz(3,3) = 1;
cc(0,0) = nodes[elem.p[0]][0]*nodes[elem.p[0]][0] + nodes[elem.p[0]][1]*nodes[elem.p[0]][1] + nodes[elem.p[0]][2]*nodes[elem.p[0]][2];
cc(0,1) = nodes[elem.p[0]][0]; cc(0,2) = nodes[elem.p[0]][1]; cc(0,3) = nodes[elem.p[0]][2];
cc(1,0) = nodes[elem.p[1]][0]*nodes[elem.p[1]][0] + nodes[elem.p[1]][1]*nodes[elem.p[1]][1] + nodes[elem.p[1]][2]*nodes[elem.p[1]][2];
cc(1,1) = nodes[elem.p[1]][0]; cc(1,2) = nodes[elem.p[1]][1]; cc(1,3) = nodes[elem.p[1]][2];
cc(2,0) = nodes[elem.p[2]][0]*nodes[elem.p[2]][0] + nodes[elem.p[2]][1]*nodes[elem.p[2]][1] + nodes[elem.p[2]][2]*nodes[elem.p[2]][2];
cc(2,1) = nodes[elem.p[2]][0]; cc(2,2) = nodes[elem.p[2]][1]; cc(2,3) = nodes[elem.p[2]][2];
cc(3,0) = nodes[elem.p[3]][0]*nodes[elem.p[3]][0] + nodes[elem.p[3]][1]*nodes[elem.p[3]][1] + nodes[elem.p[3]][2]*nodes[elem.p[3]][2];
cc(3,1) = nodes[elem.p[3]][0]; cc(3,2) = nodes[elem.p[3]][1]; cc(3,3) = nodes[elem.p[3]][2];
d_x = determinant(dx);
d_y = determinant(dy);
d_z = determinant(dz);
c = determinant(cc);
elem.centre[0] = d_x/a*0.5;
elem.centre[1] = d_y/a*0.5;
elem.centre[2] = d_z/a*0.5;
elem.radius = sqrt(d_x*d_x + d_y*d_y + d_z*d_z - 4.0*a*c)/2*fabs(a);
cout << "Circumcircle data: centre " << elem.centre[0] << "," << elem.centre[1] << "," << elem.centre[2] << ", radius " << elem.radius << ", elem jacobian " << a << endl;
}
/// Calculates the jacobian of the tetrahedron formed by point r and a face of tetrahedron ielem.
/** The face is selected by i between 0 and 3. Face i is the face opposite to local node i of the tetrahedron.
*/
double Delaunay3d::det4(int ielem, int i, const vector<double>& r) const
{
#if DEBUGW==1
if(i > 3) {
std::cout << "Delaunay3D: det4(): ! Second argument is greater than 3!" << std::endl;
return 0;
}
#endif
Tet elem = elems[ielem];
double ret = 0;
switch(i)
{
case(0):
ret = r[0] * ( nodes[elem.p[1]][1]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) + nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] );
ret -= r[1] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] );
ret += r[2] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) -nodes[elem.p[1]][1]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] );
ret -= nodes[elem.p[1]][0]*( nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] ) -nodes[elem.p[1]][1]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] ) +nodes[elem.p[1]][2]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] );
break;
case(1):
ret = nodes[elem.p[0]][0] * ( r[1]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -r[2]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) + nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] );
ret -= nodes[elem.p[0]][1] * (r[0]*(nodes[elem.p[2]][2]-nodes[elem.p[3]][2]) -r[2]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] );
ret += nodes[elem.p[0]][2] * (r[0]*(nodes[elem.p[2]][1]-nodes[elem.p[3]][1]) -r[1]*(nodes[elem.p[2]][0]-nodes[elem.p[3]][0]) + nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] );
ret -= r[0]*( nodes[elem.p[2]][1]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][1] ) -r[1]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][2] - nodes[elem.p[2]][2]*nodes[elem.p[3]][0] ) +r[2]*( nodes[elem.p[2]][0]*nodes[elem.p[3]][1] - nodes[elem.p[2]][1]*nodes[elem.p[3]][0] );
break;
case(2):
ret = nodes[elem.p[0]][0] * ( nodes[elem.p[1]][1]*(r[2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(r[1]-nodes[elem.p[3]][1]) + r[1]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][1] );
ret -= nodes[elem.p[0]][1] * (nodes[elem.p[1]][0]*(r[2]-nodes[elem.p[3]][2]) -nodes[elem.p[1]][2]*(r[0]-nodes[elem.p[3]][0]) + r[0]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][0] );
ret += nodes[elem.p[0]][2] * (nodes[elem.p[1]][0]*(r[1]-nodes[elem.p[3]][1]) -nodes[elem.p[1]][1]*(r[0]-nodes[elem.p[3]][0]) + r[0]*nodes[elem.p[3]][1] - r[1]*nodes[elem.p[3]][0] );
ret -= nodes[elem.p[1]][0]*( r[1]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][1] ) -nodes[elem.p[1]][1]*( r[0]*nodes[elem.p[3]][2] - r[2]*nodes[elem.p[3]][0] ) +nodes[elem.p[1]][2]*( r[0]*nodes[elem.p[3]][1] - r[1]*nodes[elem.p[3]][0] );
break;
case(3):
ret = nodes[elem.p[0]][0] * ( nodes[elem.p[1]][1]*(nodes[elem.p[2]][2]-r[2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][1]-r[1]) + nodes[elem.p[2]][1]*r[2] - nodes[elem.p[2]][2]*r[1] );
ret -= nodes[elem.p[0]][1] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][2]-r[2]) -nodes[elem.p[1]][2]*(nodes[elem.p[2]][0]-r[0]) + nodes[elem.p[2]][0]*r[2] - nodes[elem.p[2]][2]*r[0] );
ret += nodes[elem.p[0]][2] * (nodes[elem.p[1]][0]*(nodes[elem.p[2]][1]-r[1]) -nodes[elem.p[1]][1]*(nodes[elem.p[2]][0]-r[0]) + nodes[elem.p[2]][0]*r[1] - nodes[elem.p[2]][1]*r[0] );
ret -= nodes[elem.p[1]][0] *( nodes[elem.p[2]][1]*r[2] - nodes[elem.p[2]][2]*r[1] ) -nodes[elem.p[1]][1]*( nodes[elem.p[2]][0]*r[2] - nodes[elem.p[2]][2]*r[0] ) + nodes[elem.p[1]][2]*( nodes[elem.p[2]][0]*r[1] - nodes[elem.p[2]][1]*r[0] );
break;
default:
cout << "Delaunay3D: det4(): ! Invalid argument i! Should be between 0 and 3 inclusive." << endl;
ret = -1;
}
return ret;
}
|
gpl-3.0
|
AKSW/AutoSPARQL
|
algorithm-tbsl/src/main/java/org/aksw/autosparql/tbsl/algorithm/util/IndexResultItemComparator.java
|
1260
|
//package org.aksw.autosparql.tbsl.algorithm.util;
//
//import java.util.Comparator;
//import java.util.HashMap;
//import java.util.Map;
//
//import org.dllearner.common.index.IndexResultItem;
//
//public class IndexResultItemComparator implements Comparator<IndexResultItem>{
// private String s;
// private Map<String, Double> cache;
//
// public IndexResultItemComparator(String s) {
// this.s = s;
// cache = new HashMap<String, Double>();
// }
//
// @Override
// public int compare(IndexResultItem item1, IndexResultItem item2) {
//
// double sim1 = 0;
// if(cache.containsKey(item1.getLabel())){
// sim1 = cache.get(item1.getLabel());
// } else {
// sim1 = Similarity.getSimilarity(s, item1.getLabel());
// cache.put(item1.getLabel(), sim1);
// }
// double sim2 = 0;
// if(cache.containsKey(item2.getLabel())){
// sim2 = cache.get(item2.getLabel());
// } else {
// sim2 = Similarity.getSimilarity(s, item2.getLabel());
// cache.put(item2.getLabel(), sim2);
// }
//
// if(sim1 < sim2){
// return 1;
// } else if(sim1 > sim2){
// return -1;
// } else {
// int val = item1.getLabel().compareTo(item2.getLabel());
// if(val == 0){
// return item1.getUri().compareTo(item2.getUri());
// }
// return val;
// }
// }
//}
|
gpl-3.0
|
dleuenbe/project2
|
server/hardware/beaglebone-ports.ts
|
8864
|
import {Logger, getLogger} from '../utils/logger';
import fs = require('fs');
import {Observable} from 'rxjs/Observable';
import {Subscriber} from 'rxjs/Subscriber';
import {Direction, AbstractAIN, AbstractGPIO, AbstractLED} from './abstract-ports';
export class GPIO extends AbstractGPIO {
public static readonly VALID_IDS: number[] = [2, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 20, 26, 27, 44, 45, 46, 47, 48, 49, 60, 61, 65, 66, 69, 115];
private static readonly logger: Logger = getLogger('GPIO');
private static readonly ROOT = '/sys/class/gpio/';
private static readonly UNEXPORT = GPIO.ROOT + 'unexport';
private static readonly EXPORT = GPIO.ROOT + 'export';
private static readonly BASE_NAME = 'gpio';
private outputObs: Observable<boolean> = null;
private intervalId: any = null;
private prevValue: number = 48; // ascii 0
constructor(protected id: number, private direction: Direction) {
super(id);
if (GPIO.VALID_IDS.filter(vid => vid != id).length === 0) {
throw new Error(`GPIO id ${id} is not valid!`);
}
let portName: string = this.getName();
// activate port if not yet done
if (!fs.existsSync(portName)) {
let cmd: string = `${GPIO.EXPORT}`;
fs.writeFileSync(cmd, id);
GPIO.logger.debug(`enable port id ${id}`);
}
// set port direction
let cmd = `${portName}/direction`;
fs.writeFileSync(cmd, this.directionVerb());
GPIO.logger.debug(`port ${id} direction ${this.directionVerb()}`);
// if output then set mode to edge
if (this.direction === Direction.INPUT) {
cmd = `${portName}/edge`;
fs.writeFileSync(cmd, 'none');
GPIO.logger.debug(`port ${id} edge on both`);
} else {
this.setState(false);
}
}
getName(): string {
return `${GPIO.ROOT}${GPIO.BASE_NAME}${this.id}`;
}
directionVerb(): string {
switch (this.direction) {
case Direction.INPUT:
return 'in';
case Direction.OUTPUT:
return 'out';
default:
return null;
}
}
setState(on: boolean): void {
if (this.direction === Direction.OUTPUT) {
let cmd: string = `${this.getName()}/value`;
let state: number = on ? 0 : 1; // on = 0, off = 1, i.e. inverted
GPIO.logger.debug(`setState ${cmd} to ${state}`);
if (fs.existsSync(cmd)) {
fs.writeFileSync(cmd, state);
GPIO.logger.debug('done');
} else {
GPIO.logger.error(`setState failed: ${cmd} does not exit`);
}
} else {
GPIO.logger.error(`setState ${this.getName()} not allowed for input pin`);
}
}
watch(): Observable<boolean> {
if (this.direction === Direction.INPUT) {
if (this.outputObs === null) {
this.outputObs = Observable.create((subscriber: Subscriber<boolean>) => {
let cmd: string = `${this.getName()}/value`;
GPIO.logger.debug(`watch ${cmd}`);
if (fs.existsSync(cmd)) {
this.read(subscriber, cmd);
} else {
subscriber.error(`watch failed: ${cmd} does not exist`);
subscriber.complete();
}
});
}
return this.outputObs;
} else {
GPIO.logger.error(`watch ${this.getName()} not allowed for output pin`);
}
}
private read(subscriber: Subscriber<boolean>, cmd: string, value?: boolean): void {
this.intervalId = setInterval(() => {
let data: Buffer = fs.readFileSync(cmd);
if (data) {
let val: number = data.readUInt8(0); // ascii value of 0 = 48, of 1 = 49
if (val !== this.prevValue) {
GPIO.logger.debug(`${this.getName()} input is ${val !== 48}`);
subscriber.next(val !== 48);
this.prevValue = val;
}
} else {
let errStr: string = `read ${cmd} failed with no data`;
GPIO.logger.error(errStr);
subscriber.error(errStr);
subscriber.complete();
clearInterval(this.intervalId);
}
}, 100);
}
reset(): void {
GPIO.logger.debug(`reset ${this.getName()} --> ${GPIO.UNEXPORT} for gpio${this.id}`);
if (fs.existsSync(this.getName())) {
if (this.intervalId !== null) {
clearInterval(this.intervalId);
}
fs.writeFileSync(GPIO.UNEXPORT, this.id);
GPIO.logger.debug('done');
} else {
GPIO.logger.error(`Reset failed: ${this.getName()} does not exit`);
}
}
toString(): string {
let portName: string = `${this.getName()}`;
if (fs.existsSync(portName)) {
let direction = fs.readFileSync(`${portName}}/direction`);
let edge = fs.readFileSync(`${portName}}/edge`);
let str = `${portName}: direction ${direction} [${this.directionVerb()}]`;
if (this.direction === Direction.OUTPUT) {
str += `, edge on ${edge} [none]`;
}
return str;
} else {
return `Unexpected: ${portName} does not exist!`;
}
}
}
export class AIN extends AbstractAIN {
public static readonly VALID_IDS: number[] = [0, 1, 2, 3, 4, 5, 6];
public static readonly MAX_VALUE: number = 4096;
private static readonly logger: Logger = getLogger('AIN');
private static readonly ROOT = '/sys/bus/iio/devices/iio:device0/';
private static readonly BASE_NAME = 'in_voltage';
private static readonly POST_FIX = '_raw';
private outputObs: Observable<number> = null;
private intervalId: any = null;
private doPoll: boolean = true;
constructor(protected id: number) {
super(id);
if (AIN.VALID_IDS.filter(vid => vid != id).length === 0) {
throw new Error(`AIN id ${id} is not valid!`);
}
}
getName(): string {
return `${AIN.ROOT}${AIN.BASE_NAME}${this.id}${AIN.POST_FIX}`;
}
poll(intervalSeconds: number): Observable<number> {
if (this.outputObs === null) {
this.outputObs = Observable.create((subscriber: Subscriber<number>) => {
AIN.logger.debug(`poll ${this.getName()} every ${intervalSeconds} second(s)`);
if (fs.existsSync(this.getName())) {
this.readInitialValue(subscriber);
this.doPoll = true;
this.intervalId = setInterval(() => {
if (this.doPoll) {
this.subscribeReadValue(subscriber);
} else {
subscriber.complete();
}
}, intervalSeconds * 1000);
} else {
subscriber.error(`poll failed: ${this.getName()} does not exist`);
subscriber.complete();
}
});
}
return this.outputObs;
}
private readInitialValue(subscriber: Subscriber<number>) {
this.subscribeReadValue(subscriber);
}
private subscribeReadValue(subscriber: Subscriber<number>) {
fs.readFile(this.getName(), (err, data) => {
if (err) {
subscriber.error(`read ${this.getName()} failed with ${err}`);
} else {
let val: number = Number(data.toString());
AIN.logger.debug(`${this.getName()}: value ${val}`);
subscriber.next(val);
}
});
}
stopPolling(): void {
AIN.logger.debug(`stopPolling ${this.getName()}`);
clearInterval(this.intervalId);
this.doPoll = false;
}
}
export class LED extends AbstractLED {
public static readonly VALID_IDS: number[] = [0, 1, 2, 3];
private static readonly logger: Logger = getLogger('SimulatedGPIO');
private static readonly ROOT = '/sys/class/leds/';
private static readonly BASE_NAME = 'beaglebone:green:usr';
constructor(protected id: number) {
super(id);
if (LED.VALID_IDS.filter(vid => vid != id).length === 0) {
throw new Error(`LED id ${id} is not valid!`);
}
this.setState(0);
}
getName(): string {
return `${LED.ROOT}${LED.BASE_NAME}${this.id}`;
}
setState(state: number): void {
let cmd: string = `${this.getName()}/brightness`;
LED.logger.debug(`setState ${cmd} to ${state}`);
if (fs.existsSync(cmd)) {
fs.writeFileSync(cmd, state);
} else {
LED.logger.error(`setState ${state} failed: ${cmd} does not exist`);
}
}
blink(delayOn: number, delayOff: number): void {
let cmdTimer: string = `${this.getName()}/trigger`;
let cmdOn: string = `${this.getName()}/delay_on`;
let cmdOff: string = `${this.getName()}/delay_off`;
LED.logger.debug(`blink ${cmdTimer} with ${delayOn}-${delayOff}`);
if (fs.existsSync(cmdTimer)) {
fs.writeFileSync(cmdTimer, 'timer');
fs.writeFileSync(cmdOn, delayOn);
fs.writeFileSync(cmdOff, delayOff);
} else {
LED.logger.error(`blink ${delayOn}-${delayOff} failed: ${cmdTimer} does not exist`);
}
}
heartbeat(): void {
let cmd: string = `${this.getName()}/trigger`;
let value: string = 'heartbeat';
LED.logger.debug(`heartbeat ${cmd} to ${value}`);
if (fs.existsSync(cmd)) {
fs.writeFileSync(cmd, value);
} else {
LED.logger.error(`heatbeat ${value} failed: ${cmd} does not exist`);
}
}
}
|
gpl-3.0
|
ronaflx/opensource-tutorial
|
protobuf/closure-test.cc
|
2640
|
//============================================================================
// Name : closure-test.cc
// Author : ronaflx
// Version : 1.0
// Copyright : GNU GPL
// Description :
//============================================================================
#include <iostream>
using namespace std;
#include <google/protobuf/stubs/common.h>
#include <gtest/gtest.h>
#include "person.pb.h"
using google::protobuf::NewCallback;
using google::protobuf::Closure;
class ClosureTestFixture : public ::testing::Test {
protected:
string name;
string email;
int id;
vector<string> phonenumber;
void SetUp() {
name = "ronaflx";
id = 195936;
email = "900831flx@gmail.com";
phonenumber.push_back("18945918324");
phonenumber.push_back("13354599597");
}
};
// all call function should use void as return value
void PrintInfo() {
EXPECT_TRUE(true);
return;
}
// callback function can only call once
// it will delete it self after call.
TEST_F(ClosureTestFixture, SimpleCallBack) {
Closure* closure = NewCallback(&PrintInfo);
closure->Run();
// DO NOT call it again.
// closure->Run();
EXPECT_EQ(name, "ronaflx");
EXPECT_EQ(email, "900831flx@gmail.com");
// DO NOT delete it again.
// delete closure;
}
// for this kind callback funtion, we
// use pointer instead of reference.
void PrintInfo(string* name, string* email) {
*name = "flx.rona";
*email = "ronaflx@google.com";
}
// callback function can also have args.
// but protobuf only provide 5 args besides
// funcion itself.
TEST_F(ClosureTestFixture, ArguementCallBack) {
Closure* closure = NewCallback(&PrintInfo, &name, &email);
closure->Run();
EXPECT_EQ(name, "flx.rona");
EXPECT_EQ(email, "ronaflx@google.com");
}
// use const type pointer.
void ConstPrintInfo(const string* name, const string* email) {
EXPECT_EQ(*name, "ronaflx");
EXPECT_EQ(*email, "900831flx@gmail.com");
}
// for a non-const value, if we want to pass it
// to const type we use const_cast operator.
TEST_F(ClosureTestFixture, ConstArguement) {
Closure* closure = NewCallback(&ConstPrintInfo,
const_cast<const string*>(&name),
const_cast<const string*>(&email));
closure->Run();
EXPECT_EQ(name, "ronaflx");
EXPECT_EQ(email, "900831flx@gmail.com");
}
template<class T>
void SimpleFunction(T* instance) {
EXPECT_TRUE(true);
}
// fo template function, use function<type> as argument.
TEST_F(ClosureTestFixture, TemplateCallBack) {
Closure* closure = NewCallback(&SimpleFunction<string>, &name);
closure->Run();
EXPECT_EQ(name, "ronaflx");
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
gpl-3.0
|
livecodefraser/livecode
|
libfoundation/src/foundation-data.cpp
|
14664
|
/* Copyright (C) 2003-2013 Runtime Revolution Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include <foundation.h>
#include <foundation-auto.h>
#include "foundation-private.h"
////////////////////////////////////////////////////////////////////////////////
// This method ensures there is 'count' bytes of empty space starting at 'at'
// in 'r_data'. It returns false if allocation fails.
static bool __MCDataExpandAt(MCDataRef r_data, uindex_t at, uindex_t count);
// This method removes 'count' bytes from byte sequence starting at 'at'.
static void __MCDataShrinkAt(MCDataRef r_data, uindex_t at, uindex_t count);
// This method clamps the given range to the valid limits for the byte sequence.
static void __MCDataClampRange(MCDataRef r_data, MCRange& x_range);
static bool __MCDataMakeImmutable(__MCData *self);
////////////////////////////////////////////////////////////////////////////////
bool MCDataCreateWithBytes(const byte_t *p_bytes, uindex_t p_byte_count, MCDataRef& r_data)
{
bool t_success;
t_success = true;
__MCData *self;
self = nil;
if (t_success)
t_success = __MCValueCreate(kMCValueTypeCodeData, self);
if (t_success)
t_success = MCMemoryNewArray(p_byte_count, self -> bytes);
if (t_success)
{
MCMemoryCopy(self -> bytes, p_bytes, p_byte_count);
self -> byte_count = p_byte_count;
r_data = self;
}
else
{
if (self != nil)
MCMemoryDeleteArray(self -> bytes);
MCMemoryDelete(self);
}
return t_success;
}
bool MCDataCreateWithBytesAndRelease(byte_t *p_bytes, uindex_t p_byte_count, MCDataRef& r_data)
{
if (MCDataCreateWithBytes(p_bytes, p_byte_count, r_data))
{
MCMemoryDeallocate(p_bytes);
return true;
}
return false;
}
bool MCDataIsEmpty(MCDataRef p_data)
{
return p_data -> byte_count == 0;
}
uindex_t MCDataGetLength(MCDataRef p_data)
{
return p_data->byte_count;
}
const byte_t *MCDataGetBytePtr(MCDataRef p_data)
{
return p_data->bytes;
}
byte_t MCDataGetByteAtIndex(MCDataRef p_data, uindex_t p_index)
{
return p_data->bytes[p_index];
}
hash_t MCDataHash(MCDataRef p_data);
bool MCDataIsEqualTo(MCDataRef p_left, MCDataRef p_right)
{
if (p_left -> byte_count != p_right -> byte_count)
return false;
return MCMemoryCompare(p_left -> bytes, p_right -> bytes, p_left -> byte_count) == 0;
}
compare_t MCDataCompareTo(MCDataRef p_left, MCDataRef p_right);
// Mutable data methods
bool MCDataCreateMutable(uindex_t p_initial_capacity, MCDataRef& r_data)
{
bool t_success;
t_success = true;
__MCData *self;
self = nil;
if (t_success)
t_success = __MCValueCreate(kMCValueTypeCodeData, self);
if (t_success)
t_success = __MCDataExpandAt(self, 0, p_initial_capacity);
if (t_success)
{
self->flags |= kMCDataFlagIsMutable;
r_data = self;
}
return t_success;
}
bool MCDataCopy(MCDataRef p_data, MCDataRef& r_new_data)
{
if (!MCDataIsMutable(p_data))
{
MCValueRetain(p_data);
r_new_data = p_data;
return true;
}
return MCDataCreateWithBytes(p_data->bytes, p_data->byte_count, r_new_data);
}
bool MCDataCopyAndRelease(MCDataRef p_data, MCDataRef& r_new_data)
{
// If the MCData is immutable we just pass it through (as we are releasing it).
if (!MCDataIsMutable(p_data))
{
r_new_data = p_data;
return true;
}
// If the reference is 1, convert it to an immutable MCData
if (p_data->references == 1)
{
__MCDataMakeImmutable(p_data);
p_data->flags &= ~kMCDataFlagIsMutable;
r_new_data = p_data;
return true;
}
// Otherwise make a copy of the data and then release the original
bool t_success;
t_success = MCDataCreateWithBytes(p_data->bytes, p_data->byte_count, r_new_data);
MCValueRelease(p_data);
return t_success;
}
bool MCDataMutableCopy(MCDataRef p_data, MCDataRef& r_mutable_data)
{
MCDataRef t_mutable_data;
if (!MCDataCreateMutable(p_data->byte_count, t_mutable_data))
return false;
MCMemoryCopy(t_mutable_data->bytes, p_data->bytes, p_data->byte_count);
t_mutable_data->byte_count = p_data->byte_count;
r_mutable_data = t_mutable_data;
return true;
}
bool MCDataMutableCopyAndRelease(MCDataRef p_data, MCDataRef& r_mutable_data)
{
if (MCDataMutableCopy(p_data, r_mutable_data))
{
MCValueRelease(p_data);
return true;
}
return false;
}
bool MCDataCopyRange(MCDataRef self, MCRange p_range, MCDataRef& r_new_data)
{
__MCDataClampRange(self, p_range);
return MCDataCreateWithBytes(self -> bytes + p_range . offset, p_range . length, r_new_data);
}
bool MCDataCopyRangeAndRelease(MCDataRef self, MCRange p_range, MCDataRef& r_new_data)
{
if (MCDataCopyRange(self, p_range, r_new_data))
{
MCValueRelease(self);
return true;
}
return false;
}
bool MCDataIsMutable(const MCDataRef p_data)
{
return (p_data->flags & kMCDataFlagIsMutable) != 0;
}
bool MCDataAppend(MCDataRef r_data, MCDataRef p_suffix)
{
MCAssert(MCDataIsMutable(r_data));
if (r_data == p_suffix)
{
// Must copy first the suffix
MCDataRef t_suffix_copy;
if(!MCDataCopy(r_data, t_suffix_copy))
return false;
// Copy succeeded: can process recursively the appending, and then release the newly created suffix.
bool t_success = MCDataAppend(r_data, t_suffix_copy);
MCValueRelease(t_suffix_copy);
return t_success;
}
if (!__MCDataExpandAt(r_data, r_data->byte_count, p_suffix->byte_count))
return false;
MCMemoryCopy(r_data->bytes + r_data->byte_count - p_suffix->byte_count, p_suffix->bytes, p_suffix->byte_count);
return true;
}
bool MCDataAppendBytes(MCDataRef r_data, const byte_t *p_bytes, uindex_t p_byte_count)
{
MCAssert(MCDataIsMutable(r_data));
// Expand the capacity if necessary
if (!__MCDataExpandAt(r_data, r_data->byte_count, p_byte_count))
return false;
MCMemoryCopy(r_data->bytes + r_data->byte_count - p_byte_count, p_bytes, p_byte_count);
return true;
}
bool MCDataAppendByte(MCDataRef r_data, byte_t p_byte)
{
MCAssert(MCDataIsMutable(r_data));
return MCDataAppendBytes(r_data, &p_byte, 1);
}
bool MCDataPrepend(MCDataRef r_data, MCDataRef p_prefix)
{
MCAssert(MCDataIsMutable(r_data));
if (r_data == p_prefix)
{
// Must copy first the prefix
MCDataRef t_prefix_copy;
if(!MCDataCopy(r_data, t_prefix_copy))
return false;
// Copy succeeded: can process recursively the appending, and then release the newly created suffix.
bool t_success = MCDataPrepend(r_data, t_prefix_copy);
MCValueRelease(t_prefix_copy);
return t_success;
}
// Ensure there is room enough to copy the prefix
if (!__MCDataExpandAt(r_data, 0, p_prefix->byte_count))
return false;
MCMemoryCopy(r_data->bytes, p_prefix->bytes, p_prefix->byte_count);
return true;
}
bool MCDataPrependBytes(MCDataRef r_data, const byte_t *p_bytes, uindex_t p_byte_count)
{
MCAssert(MCDataIsMutable(r_data));
// Ensure there is room enough to copy the prefix
if (!__MCDataExpandAt(r_data, 0, p_byte_count))
return false;
MCMemoryCopy(r_data->bytes, p_bytes, p_byte_count);
return true;
}
bool MCDataPrependByte(MCDataRef r_data, byte_t p_byte)
{
return MCDataPrependBytes(r_data, &p_byte, 1);
}
bool MCDataInsert(MCDataRef r_data, uindex_t p_at, MCDataRef p_new_data)
{
MCAssert(MCDataIsMutable(r_data));
if (r_data == p_new_data)
{
// Must copy first the prefix
MCDataRef t_new_data_copy;
if(!MCDataCopy(r_data, t_new_data_copy))
return false;
// Copy succeeded: can process recursively the appending, and then release the newly created suffix.
bool t_success = MCDataPrepend(r_data, t_new_data_copy);
MCValueRelease(t_new_data_copy);
return t_success;
}
// Ensure there is room enough to copy the prefix
if (!__MCDataExpandAt(r_data, p_at, p_new_data->byte_count))
return false;
MCMemoryCopy(r_data->bytes, p_new_data->bytes, p_new_data->byte_count);
return true;
}
bool MCDataRemove(MCDataRef r_data, MCRange p_range)
{
MCAssert(MCDataIsMutable(r_data));
__MCDataClampRange(r_data, p_range);
// Copy down the bytes above
__MCDataShrinkAt(r_data, p_range.offset, p_range.length);
// We succeeded.
return true;
}
bool MCDataReplace(MCDataRef r_data, MCRange p_range, MCDataRef p_new_data)
{
MCAssert(MCDataIsMutable(r_data));
if (r_data == p_new_data)
{
MCDataRef t_new_data;
if (!MCDataCopy(p_new_data, t_new_data))
return false;
bool t_success = MCDataReplace(r_data, p_range, t_new_data);
MCValueRelease(t_new_data);
return t_success;
}
__MCDataClampRange(r_data, p_range);
// Work out the new size of the string.
uindex_t t_new_char_count;
t_new_char_count = r_data->byte_count - p_range.length + p_new_data->byte_count;
if (t_new_char_count > r_data->byte_count)
{
// Expand the string at the end of the range by the amount extra we
// need.
if (!__MCDataExpandAt(r_data, p_range.offset + p_range.length, t_new_char_count - r_data->byte_count))
return false;
}
else if (t_new_char_count < r_data->byte_count)
{
// Shrink the last part of the range by the amount less we need.
__MCDataShrinkAt(r_data, p_range.offset + (p_range.length - (r_data->byte_count - t_new_char_count)), (r_data->byte_count - t_new_char_count));
}
// Copy across the replacement chars.
MCMemoryCopy(r_data->bytes + p_range.offset, p_new_data->bytes, p_new_data->byte_count);
// We succeeded.
return true;
}
bool MCDataPad(MCDataRef p_data, byte_t p_byte, uindex_t p_count)
{
if (!__MCDataExpandAt(p_data, p_data -> byte_count, p_count))
return false;
memset(p_data -> bytes + p_data -> byte_count - p_count, p_byte, p_count);
return true;
}
compare_t MCDataCompareTo(MCDataRef p_left, MCDataRef p_right)
{
compare_t t_result;
t_result = memcmp(p_left -> bytes, p_right -> bytes, MCMin(p_left -> byte_count, p_right -> byte_count));
if (t_result != 0)
return t_result;
return p_left -> byte_count - p_right -> byte_count;
}
#if defined(__MAC__) || defined (__IOS__)
bool MCDataConvertToCFDataRef(MCDataRef p_data, CFDataRef& r_cfdata)
{
r_cfdata = CFDataCreate(nil, MCDataGetBytePtr(p_data), MCDataGetLength(p_data));
return r_cfdata != nil;
}
#endif
static void __MCDataClampRange(MCDataRef p_data, MCRange& x_range)
{
uindex_t t_left, t_right;
t_left = MCMin(x_range . offset, p_data -> byte_count);
t_right = MCMin(x_range . offset + MCMin(x_range . length, UINDEX_MAX - x_range . offset), p_data->byte_count);
x_range . offset = t_left;
x_range . length = t_right - t_left;
}
static void __MCDataShrinkAt(MCDataRef r_data, uindex_t p_at, uindex_t p_count)
{
// Shift the bytes above 'at' down to remove 'count'
MCMemoryMove(r_data->bytes + p_at, r_data->bytes + (p_at + p_count), r_data->byte_count - (p_at + p_count));
// Now adjust the length of the string.
r_data->byte_count -= p_count;
// TODO: Shrink the buffer if its too big.
}
static bool __MCDataExpandAt(MCDataRef r_data, uindex_t p_at, uindex_t p_count)
{
// Fetch the capacity.
uindex_t t_capacity;
t_capacity = r_data->capacity;
// The capacity field stores the total number of chars that could fit not
// including the implicit NUL, so if we fit, we can fast-track.
if (t_capacity != 0 && r_data->byte_count + p_count <= t_capacity)
{
// Shift up the bytes above
MCMemoryMove(r_data->bytes + p_at + p_count,r_data->bytes + p_at, r_data->byte_count - p_at);
// Increase the byte_count.
r_data->byte_count += p_count;
// We succeeded.
return true;
}
// If we get here then we need to reallocate first.
// Base capacity - current length + inserted length
uindex_t t_new_capacity;
t_new_capacity = r_data->byte_count + p_count;
// Capacity rounded up to a suitable boundary (at some point this should
// be a function of the string's size).
t_new_capacity = (t_new_capacity + 63) & ~63;
// Reallocate.
if (!MCMemoryReallocate(r_data->bytes, t_new_capacity, r_data->bytes))
return false;
// Shift up the bytes above
MCMemoryMove(r_data->bytes + p_at + p_count, r_data->bytes + p_at, r_data->byte_count - p_at);
// Increase the byte_count.
r_data->byte_count += p_count;
// Update the capacity
r_data -> capacity = t_new_capacity;
// We succeeded.
return true;
}
static bool __MCDataMakeImmutable(__MCData *self)
{
if (!MCMemoryResizeArray(self -> byte_count, self -> bytes, self -> byte_count))
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
MCDataRef kMCEmptyData;
bool __MCDataInitialize(void)
{
if (!MCDataCreateWithBytes(nil, 0, kMCEmptyData))
return false;
return true;
}
void __MCDataFinalize(void)
{
MCValueRelease(kMCEmptyData);
}
void __MCDataDestroy(__MCData *self)
{
if (self -> bytes != nil)
MCMemoryDeleteArray(self -> bytes);
}
bool __MCDataImmutableCopy(__MCData *self, bool p_release, __MCData *&r_immutable_value)
{
if (!p_release)
return MCDataCopy(self, r_immutable_value);
return MCDataCopyAndRelease(self, r_immutable_value);
}
bool __MCDataIsEqualTo(__MCData *self, __MCData *p_other_data)
{
return MCDataIsEqualTo(self, p_other_data);
}
hash_t __MCDataHash(__MCData *self)
{
return MCHashBytes(self -> bytes, self -> byte_count);
}
bool __MCDataCopyDescription(__MCData *self, MCStringRef &r_description)
{
return false;
}
|
gpl-3.0
|
maksvzw/zetcam
|
src/main/java/org/maksvzw/zetcam/core/audio/buffers/ByteSampleBuffer.java
|
3890
|
/*
* Copyright (C) 2015 Lenny Knockaert <lknockx@gmail.com>
*
* This file is part of ZetCam
*
* ZetCam is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ZetCam 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 org.maksvzw.zetcam.core.audio.buffers;
import com.xuggle.xuggler.IAudioSamples;
/**
*
* @author Lenny Knockaert
*/
public abstract class ByteSampleBuffer extends AudioSampleBuffer<Byte>
{
private final byte[] tempBuf;
private byte[] mixBuf;
protected ByteSampleBuffer(IAudioSamples samples)
{
super(samples);
this.tempBuf = new byte[1024];
}
@Override
protected final Byte getSample(IAudioSamples samples, int index)
{
samples.get(index, this.tempBuf, 0, 1);
return this.tempBuf[0];
}
@Override
protected final void putSample(IAudioSamples samples, int index, Byte sample)
{
this.tempBuf[0] = sample;
samples.put(this.tempBuf, 0, index, 1);
}
@Override
protected final void copySamples(IAudioSamples src, int srcIndex, IAudioSamples dst, int dstIndex, int length)
{
int tempLength;
while(length > 0) {
tempLength = Math.min(this.tempBuf.length, length);
src.get(srcIndex, this.tempBuf, 0, tempLength);
dst.put(this.tempBuf, 0, dstIndex, tempLength);
srcIndex += tempLength;
dstIndex += tempLength;
length -= tempLength;
}
}
@Override
protected final void mixSamples(IAudioSamples src, int srcIndex, IAudioSamples dst, int dstIndex, int length)
{
if (this.mixBuf == null)
this.mixBuf = new byte[this.tempBuf.length];
int tempLength;
while(length > 0) {
tempLength = Math.min(this.tempBuf.length, length);
src.get(srcIndex, this.tempBuf, 0, tempLength);
dst.get(srcIndex, this.mixBuf, 0, tempLength);
for(int i = 0; i < tempLength; i++)
this.mixBuf[i] = this.mixSample(this.tempBuf[i], this.mixBuf[i]);
dst.put(this.mixBuf, 0, dstIndex, tempLength);
srcIndex += tempLength;
dstIndex += tempLength;
length -= tempLength;
}
}
@Override
protected final void scaleSamples(IAudioSamples samples, int index, int length, double scale)
{
int tempLength;
while(length > 0) {
tempLength = Math.min(length, this.tempBuf.length);
samples.get(index, this.tempBuf, 0, tempLength);
for(int i = 0; i < tempLength; i++)
this.tempBuf[i] = this.scaleSample(this.tempBuf[i], scale);
samples.put(this.tempBuf, 0, index, tempLength);
length -= tempLength;
index += tempLength;
}
}
@Override
protected final void fillSamples(IAudioSamples samples, int index, int length, Byte sample)
{
int tempLength;
while(length > 0) {
tempLength = Math.min(length, this.tempBuf.length);
samples.get(index, this.tempBuf, 0, tempLength);
for(int i = 0; i < tempLength; i++)
this.tempBuf[i] = sample;
samples.put(this.tempBuf, 0, index, tempLength);
length -= tempLength;
index += tempLength;
}
}
}
|
gpl-3.0
|
Staartvin/Statz
|
src/me/staartvin/statz/datamanager/player/specification/EnteredBedsSpecification.java
|
551
|
package me.staartvin.statz.datamanager.player.specification;
import java.util.UUID;
public class EnteredBedsSpecification extends PlayerStatSpecification {
public EnteredBedsSpecification(UUID uuid, int value, String worldName) {
super();
this.putInData(Keys.UUID.toString(), uuid);
this.putInData(Keys.VALUE.toString(), value);
this.putInData(Keys.WORLD.toString(), worldName);
}
@Override
public boolean hasWorldSupport() {
return true;
}
public enum Keys {UUID, VALUE, WORLD}
}
|
gpl-3.0
|
builify/builify
|
src/javascript/components/canvas/click-toolbox/html-tagnames.js
|
512
|
export default {
div: 'Div',
aside: 'Aside',
main: 'Main',
h1: 'Heading',
h2: 'Heading',
h3: 'Heading',
h4: 'Heading',
h5: 'Heading',
h6: 'Heading',
p: 'Paragraph',
span: 'Span',
ul: 'Unordered List',
li: 'List Item',
img: 'Image',
strong: 'Strong Text',
em: 'Emphasised Text',
i: 'Icon',
a: 'Link',
input: 'Input',
blockquote: 'Quote',
figcaption: 'Caption',
button: 'Button',
header: 'Header',
footer: 'Footer'
};
|
gpl-3.0
|
LOA-SEAD/cuidando-bem
|
grunt/options/watch.js
|
1178
|
// watch
"use strict";
module.exports = {
options: {
livereload: false
},
// docs: {
// files: [
// "<%= pkg.source %>" + "/javascript/**/*.js"
// ],
// tasks: [
// "docs"
// ]
// },
js: {
files: [
"<%= pkg.source %>" + "/javascript/**/*.js"
],
tasks: [
// 'clean:js',
"newer:copy:js",
"newer:copy:libs"
]
},
html: {
files: [
"<%= pkg.source %>" + "/html/**/*.html"
],
tasks: [
// 'clean:html',
"newer:copy:html"
]
},
less: {
files: [
"<%= pkg.source %>" + "/css/**/*.less"
],
tasks: [
"less:dev",
"postcss:dev"
]
},
images: {
files: [
"<%= pkg.source %>" + "/images/**/*.{png,jpg,jpeg,gif}"
],
tasks: [
"newer:imagemin:dev"
]
},
livereload: {
options: {
livereload: true
},
files: [
"<%= pkg.development %>" + "/**/*"
]
}
};
|
gpl-3.0
|
heartvalve/OpenFlipper
|
Plugin-PropertyVis/OpenVolumeMesh/OVMPropertyVisualizerT.cc
|
18016
|
/*===========================================================================*\
* *
* OpenFlipper *
* Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen *
* www.openflipper.org *
* *
*--------------------------------------------------------------------------- *
* This file is part of OpenFlipper. *
* *
* OpenFlipper is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenFlipper is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU LesserGeneral Public *
* License along with OpenFlipper. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $LastChangedBy$ *
* $Date$ *
* *
\*===========================================================================*/
#ifdef ENABLE_OPENVOLUMEMESH_SUPPORT
#define OVM_PROPERTY_VISUALIZER_CC
#ifdef ENABLE_OPENVOLUMEMESH_POLYHEDRAL_SUPPORT
#include <ObjectTypes/PolyhedralMesh/PolyhedralMesh.hh>
#endif
#ifdef ENABLE_OPENVOLUMEMESH_HEXAHEDRAL_SUPPORT
#include <ObjectTypes/HexahedralMesh/HexahedralMesh.hh>
#endif
#include "OVMPropertyVisualizer.hh"
template <typename MeshT>
template <typename InnerType>
QString OVMPropertyVisualizer<MeshT>::getPropertyText_(unsigned int index)
{
if (PropertyVisualizer::propertyInfo.isCellProp())
{
OpenVolumeMesh::CellPropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_cell_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::CellHandle(index)]);
}
else if (PropertyVisualizer::propertyInfo.isFaceProp())
{
OpenVolumeMesh::FacePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_face_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::FaceHandle(index)]);
}
else if (PropertyVisualizer::propertyInfo.isHalffaceProp())
{
OpenVolumeMesh::HalfFacePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_halfface_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::HalfFaceHandle(index)]);
}
else if (PropertyVisualizer::propertyInfo.isEdgeProp())
{
OpenVolumeMesh::EdgePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_edge_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::EdgeHandle(index)]);
}
else if (PropertyVisualizer::propertyInfo.isHalfedgeProp())
{
OpenVolumeMesh::HalfEdgePropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_halfedge_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::HalfEdgeHandle(index)]);
}
else //if (propertyInfo.isVertexProp())
{
OpenVolumeMesh::VertexPropertyT<InnerType> prop = OVMPropertyVisualizer<MeshT>::mesh->template request_vertex_property<InnerType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
return PropertyVisualizer::toStr(prop[OpenVolumeMesh::VertexHandle(index)]);
}
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setPropertyFromText(unsigned int index, QString text)
{
if (propertyInfo.isCellProp())
setCellPropertyFromText(index, text);
else if (propertyInfo.isFaceProp())
setFacePropertyFromText(index, text);
else if (propertyInfo.isHalffaceProp())
setHalffacePropertyFromText(index, text);
else if (propertyInfo.isEdgeProp())
setEdgePropertyFromText(index, text);
else if (propertyInfo.isHalfedgeProp())
setHalfedgePropertyFromText(index, text);
else //if (propertyInfo.isVertexProp())
setVertexPropertyFromText(index, text);
}
template <typename MeshT>
int OVMPropertyVisualizer<MeshT>::getEntityCount()
{
if (propertyInfo.isCellProp())
return mesh->n_cells();
if (propertyInfo.isFaceProp())
return mesh->n_faces();
if (propertyInfo.isHalffaceProp())
return mesh->n_halffaces();
else if (propertyInfo.isEdgeProp())
return mesh->n_edges();
else if (propertyInfo.isHalfedgeProp())
return mesh->n_halfedges();
else //if (propertyInfo.isVertexProp())
return mesh->n_vertices();
}
template <typename MeshT>
QString OVMPropertyVisualizer<MeshT>::getHeader()
{
//Header: headerVersion, numberOfEntities, typeOfEntites, typeOfProperty, propertyName
QString header = QObject::tr("1"); //version
header.append(QObject::tr(", %1").arg(getEntityCount())); //number of entities
header.append(QObject::tr(", %1").arg(propertyInfo.entityType())); //type of entities
header.append(", ").append(propertyInfo.friendlyTypeName()); //type of property
header.append(", ").append(propertyInfo.propName().c_str()); // name of property
return header;
}
template <typename MeshT>
unsigned int OVMPropertyVisualizer<MeshT>::getClosestPrimitiveId(unsigned int _face, ACG::Vec3d& _hitPoint)
{
if (propertyInfo.isHalffaceProp())
return getClosestHalffaceId(_face, _hitPoint);
else// if (propertyInfo.isHalfedgeProp())
return getClosestHalfedgeId(_face, _hitPoint);
}
template <typename MeshT>
unsigned int OVMPropertyVisualizer<MeshT>::getClosestHalffaceId(unsigned int _face, ACG::Vec3d& _hitPoint)
{
ACG::Vec3d direction = PluginFunctions::viewingDirection();
OpenVolumeMesh::HalfFaceHandle hfh = mesh->halfface_handle(OpenVolumeMesh::FaceHandle(_face), 0);
OpenVolumeMesh::HalfFaceVertexIter hfv_it = mesh->hfv_iter(hfh);
ACG::Vec3d p1 = mesh->vertex(*(hfv_it+0));
ACG::Vec3d p2 = mesh->vertex(*(hfv_it+1));
ACG::Vec3d p3 = mesh->vertex(*(hfv_it+2));
ACG::Vec3d normal = (p2-p1)%(p3-p1);
if ((direction | normal) < 0)
return hfh.idx();
else
return mesh->halfface_handle(OpenVolumeMesh::FaceHandle(_face), 1).idx();
}
template <typename MeshT>
unsigned int OVMPropertyVisualizer<MeshT>::getClosestHalfedgeId(unsigned int _face, ACG::Vec3d& _hitPoint)
{
unsigned int halfface = getClosestHalffaceId(_face, _hitPoint);
OpenVolumeMesh::OpenVolumeMeshFace face = mesh->halfface(halfface);
const std::vector<OpenVolumeMesh::HalfEdgeHandle> & halfedges = face.halfedges();
double min_distance = DBL_MAX;
OpenVolumeMesh::HalfEdgeHandle closestHalfEdgeHandle;
for (std::vector<OpenVolumeMesh::HalfEdgeHandle>::const_iterator he_it = halfedges.begin(); he_it != halfedges.end(); ++he_it)
{
OpenVolumeMesh::OpenVolumeMeshEdge edge = OVMPropertyVisualizer<MeshT>::mesh->halfedge(*he_it);
ACG::Vec3d v1 = mesh->vertex(edge.from_vertex());
ACG::Vec3d v2 = mesh->vertex(edge.to_vertex());
ACG::Vec3d p = 0.5 * (v1+v2);
double distance = (p-_hitPoint).length();
if (distance < min_distance)
{
min_distance = distance;
closestHalfEdgeHandle = *he_it;
}
}
return closestHalfEdgeHandle.idx();
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualize(bool _setDrawMode)
{
if (propertyInfo.isCellProp())
visualizeCellProp(_setDrawMode);
else if (propertyInfo.isFaceProp())
visualizeFaceProp(_setDrawMode);
else if (propertyInfo.isHalffaceProp())
visualizeHalffaceProp(_setDrawMode);
else if (propertyInfo.isEdgeProp())
visualizeEdgeProp(_setDrawMode);
else if (propertyInfo.isHalfedgeProp())
visualizeHalfedgeProp(_setDrawMode);
else if (propertyInfo.isVertexProp())
visualizeVertexProp(_setDrawMode);
}
template <typename MeshT>
OpenMesh::Vec4f OVMPropertyVisualizer<MeshT>::convertColor(const QColor _color){
OpenMesh::Vec4f color;
color[0] = _color.redF();
color[1] = _color.greenF();
color[2] = _color.blueF();
color[3] = _color.alphaF();
return color;
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeFaceProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing FaceProp not implemented");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeEdgeProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing EdgeProp not implemented");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeHalfedgeProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing HalfedgeProp not implemented");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeVertexProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing VertexProp not implemented");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeCellProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing CellProp not implemented");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::visualizeHalffaceProp(bool /*_setDrawMode*/)
{
emit log(LOGERR, "Visualizing HalffaceProp not implemented");
}
template<typename MeshT>
template<typename PropType>
inline void OVMPropertyVisualizer<MeshT>::duplicateProperty_stage1() {
std::string newPropertyName;
for (int i = 1;; ++i) {
std::ostringstream oss;
oss << propertyInfo.propName() << " Copy " << i;
newPropertyName = oss.str();
if (propertyInfo.isCellProp())
{
if(!mesh->template cell_property_exists<PropType>(newPropertyName)) break;
}
else if (propertyInfo.isFaceProp())
{
if(!mesh->template face_property_exists<PropType>(newPropertyName)) break;
}
else if (propertyInfo.isHalffaceProp())
{
if(!mesh->template halfface_property_exists<PropType>(newPropertyName)) break;
}
else if (propertyInfo.isEdgeProp())
{
if(!mesh->template edge_property_exists<PropType>(newPropertyName)) break;
}
else if (propertyInfo.isHalfedgeProp())
{
if(!mesh->template halfedge_property_exists<PropType>(newPropertyName)) break;
}
else if (propertyInfo.isVertexProp())
{
if(!mesh->template vertex_property_exists<PropType>(newPropertyName)) break;
}
}
if (propertyInfo.isCellProp())
{
OpenVolumeMesh::CellPropertyT<PropType> prop = mesh->template request_cell_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::CellPropertyT<PropType> newProp = mesh->template request_cell_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->cells_begin(), mesh->cells_end(), CopyProperty<OpenVolumeMesh::CellPropertyT<PropType> >(newProp, prop, mesh));
}
else if (propertyInfo.isFaceProp())
{
OpenVolumeMesh::FacePropertyT<PropType> prop = mesh->template request_face_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::FacePropertyT<PropType> newProp = mesh->template request_face_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->faces_begin(), mesh->faces_end(), CopyProperty<OpenVolumeMesh::FacePropertyT<PropType> >(newProp, prop, mesh));
}
else if (propertyInfo.isHalffaceProp())
{
OpenVolumeMesh::HalfFacePropertyT<PropType> prop = mesh->template request_halfface_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::HalfFacePropertyT<PropType> newProp = mesh->template request_halfface_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->halffaces_begin(), mesh->halffaces_end(), CopyProperty<OpenVolumeMesh::HalfFacePropertyT<PropType> >(newProp, prop, mesh));
}
else if (propertyInfo.isEdgeProp())
{
OpenVolumeMesh::EdgePropertyT<PropType> prop = mesh->template request_edge_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::EdgePropertyT<PropType> newProp = mesh->template request_edge_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->edges_begin(), mesh->edges_end(), CopyProperty<OpenVolumeMesh::EdgePropertyT<PropType> >(newProp, prop, mesh));
}
else if (propertyInfo.isHalfedgeProp())
{
OpenVolumeMesh::HalfEdgePropertyT<PropType> prop = mesh->template request_halfedge_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::HalfEdgePropertyT<PropType> newProp = mesh->template request_halfedge_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->halfedges_begin(), mesh->halfedges_end(), CopyProperty<OpenVolumeMesh::HalfEdgePropertyT<PropType> >(newProp, prop, mesh));
}
else if (propertyInfo.isVertexProp())
{
OpenVolumeMesh::VertexPropertyT<PropType> prop = mesh->template request_vertex_property<PropType>(OVMPropertyVisualizer<MeshT>::propertyInfo.propName());
OpenVolumeMesh::VertexPropertyT<PropType> newProp = mesh->template request_vertex_property< PropType >(newPropertyName);
mesh->set_persistent(newProp, true);
std::for_each(mesh->vertices_begin(), mesh->vertices_end(), CopyProperty<OpenVolumeMesh::VertexPropertyT<PropType> >(newProp, prop, mesh));
}
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::clear()
{
VolumeMeshObject<MeshT>* object;
PluginFunctions::getObject(OVMPropertyVisualizer<MeshT>::mObjectID, object);
if (propertyInfo.isCellProp())
object->colors().clear_cell_colors();
else if (propertyInfo.isFaceProp())
object->colors().clear_face_colors();
else if (propertyInfo.isHalffaceProp())
object->colors().clear_halfface_colors();
else if (propertyInfo.isEdgeProp())
object->colors().clear_edge_colors();
else if (propertyInfo.isHalfedgeProp())
object->colors().clear_halfedge_colors();
else if (propertyInfo.isVertexProp())
object->colors().clear_vertex_colors();
object->setObjectDrawMode(drawModes.cellsFlatShaded);
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setCellPropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting CellProp not implemented for this property type");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setFacePropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting FaceProp not implemented for this property type");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setHalffacePropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting HalffaceProp not implemented for this property type");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setEdgePropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting EdgeProp not implemented for this property type");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setHalfedgePropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting HalfedgeProp not implemented for this property type");
}
template <typename MeshT>
void OVMPropertyVisualizer<MeshT>::setVertexPropertyFromText(unsigned int /*index*/, QString /*text*/)
{
emit log(LOGERR, "Setting VertexProp not implemented for this property type");
}
#endif /* ENABLE_OPENVOLUMEMESH_SUPPORT */
|
gpl-3.0
|
nidhugg/nidhugg
|
tests/litmus/C-tests/MOREDETOUR0928.c
|
2735
|
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo
* This benchmark is part of SWSC */
#include <assert.h>
#include <stdint.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int vars[2];
atomic_int atom_1_r3_0;
atomic_int atom_1_r5_1;
atomic_int atom_3_r4_3;
atomic_int atom_3_r1_1;
void *t0(void *arg){
label_1:;
atomic_store_explicit(&vars[0], 4, memory_order_seq_cst);
atomic_store_explicit(&vars[1], 1, memory_order_seq_cst);
return NULL;
}
void *t1(void *arg){
label_2:;
atomic_store_explicit(&vars[1], 2, memory_order_seq_cst);
int v2_r3 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v4_r5 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
atomic_store_explicit(&vars[0], 3, memory_order_seq_cst);
int v22 = (v2_r3 == 0);
atomic_store_explicit(&atom_1_r3_0, v22, memory_order_seq_cst);
int v23 = (v4_r5 == 1);
atomic_store_explicit(&atom_1_r5_1, v23, memory_order_seq_cst);
return NULL;
}
void *t2(void *arg){
label_3:;
atomic_store_explicit(&vars[0], 1, memory_order_seq_cst);
return NULL;
}
void *t3(void *arg){
label_4:;
int v6_r1 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
atomic_store_explicit(&vars[0], 2, memory_order_seq_cst);
int v8_r4 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v24 = (v8_r4 == 3);
atomic_store_explicit(&atom_3_r4_3, v24, memory_order_seq_cst);
int v25 = (v6_r1 == 1);
atomic_store_explicit(&atom_3_r1_1, v25, memory_order_seq_cst);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t thr0;
pthread_t thr1;
pthread_t thr2;
pthread_t thr3;
atomic_init(&vars[1], 0);
atomic_init(&vars[0], 0);
atomic_init(&atom_1_r3_0, 0);
atomic_init(&atom_1_r5_1, 0);
atomic_init(&atom_3_r4_3, 0);
atomic_init(&atom_3_r1_1, 0);
pthread_create(&thr0, NULL, t0, NULL);
pthread_create(&thr1, NULL, t1, NULL);
pthread_create(&thr2, NULL, t2, NULL);
pthread_create(&thr3, NULL, t3, NULL);
pthread_join(thr0, NULL);
pthread_join(thr1, NULL);
pthread_join(thr2, NULL);
pthread_join(thr3, NULL);
int v9 = atomic_load_explicit(&vars[1], memory_order_seq_cst);
int v10 = (v9 == 2);
int v11 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v12 = (v11 == 4);
int v13 = atomic_load_explicit(&atom_1_r3_0, memory_order_seq_cst);
int v14 = atomic_load_explicit(&atom_1_r5_1, memory_order_seq_cst);
int v15 = atomic_load_explicit(&atom_3_r4_3, memory_order_seq_cst);
int v16 = atomic_load_explicit(&atom_3_r1_1, memory_order_seq_cst);
int v17_conj = v15 & v16;
int v18_conj = v14 & v17_conj;
int v19_conj = v13 & v18_conj;
int v20_conj = v12 & v19_conj;
int v21_conj = v10 & v20_conj;
if (v21_conj == 1) assert(0);
return 0;
}
|
gpl-3.0
|
Letractively/fxlgui
|
co.fxl.gui.style.gplus/src/main/java/co/fxl/gui/style/gplus/GPlusTable.java
|
1909
|
///**
// * This file is part of FXL GUI API.
// *
// * FXL GUI API is free software: you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation, either version 3 of the License, or
// * (at your option) any later version.
// *
// * FXL GUI API 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 FXL GUI API. If not, see <http://www.gnu.org/licenses/>.
// *
// * Copyright (c) 2010-2015 Dangelmayr IT GmbH. All rights reserved.
// */
//package co.fxl.gui.style.gplus;
//
//import co.fxl.gui.api.ILabel;
//import co.fxl.gui.api.IPanel;
//import co.fxl.gui.style.api.IStyle.ITable;
//
//public class GPlusTable implements ITable {
//
// @Override
// public IColumnSelection columnSelection() {
// return new IColumnSelection() {
//
// @Override
// public IColumnSelection panel(IPanel<?> b, boolean visible) {
// if (visible)
// b.color().gray();
// else
// b.color().white();
// return this;
// }
//
// @Override
// public IColumnSelection label(ILabel b, boolean visible) {
// if (visible)
// b.font().color().white();
// else
// b.font().color().gray();
// return this;
// }
//
// };
// }
//
// @Override
// public ITable statusPanel(IPanel<?> statusPanel) {
// statusPanel.color().remove().white();
// // statusPanel.border().remove();
// return this;
// }
//
// @Override
// public ITable topPanel(IPanel<?> topPanel) {
// topPanel.color().remove().white();
// topPanel.border().remove();
// return this;
// }
//
// }
|
gpl-3.0
|
dsalaj/Qt_shmup
|
Qt_shmup/button_w2.h
|
279
|
#ifndef BUTTON_W2_H
#define BUTTON_W2_H
#include "button.h"
#include "game.h"
#include "utility.h"
#include <QObject>
class Button_w2 : public Button
{
Q_OBJECT
public:
Button_w2(QObject *parent = 0);
public slots:
virtual void clicked();
};
#endif // BUTTON_W2_H
|
gpl-3.0
|
drnp/bsp
|
src/lib/bsp-core/bsp_server.h
|
4186
|
/*
* bsp_server.h
*
* Copyright (C) 2012 - Dr.NP
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Network server runtime
*
* @package bsp::libbsp-core
* @author Dr.NP <np@bsgroup.org>
* @update 04/09/2013
* @changelog
* [06/01/2012] - Creation
* [04/09/2013] - New output functions
*/
#ifndef _LIB_BSP_CORE_SERVER_H
#define _LIB_BSP_CORE_SERVER_H
/* Headers */
/* Definations */
#define CLIENT_TYPE_DATA 0x0
#define CLIENT_TYPE_WEBSOCKET_HANDSHAKE 0x1
#define CLIENT_TYPE_WEBSOCKET_DATA 0x2
#define DATA_TYPE_STREAM 0x0
#define DATA_TYPE_PACKET 0x1
#define PACKET_TYPE_REP 0x0
#define PACKET_TYPE_RAW 0x1
#define PACKET_TYPE_OBJ 0x2
#define PACKET_TYPE_CMD 0x3
#define PACKET_TYPE_UNDEFINED 0x6
#define PACKET_TYPE_HEARTBEAT 0x7
#define SERIALIZE_TYPE_NATIVE 0x0
#define SERIALIZE_TYPE_JSON 0x1
#define SERIALIZE_TYPE_MSGPACK 0x2
#define SERIALIZE_TYPE_AMF 0x3
#define SERIALIZE_TYPE_BSON 0x4
#define UDP_PACKET_REG 0x1
#define UDP_PACKET_UNREG 0x2
#define UDP_PACKET_CTRL 0x3
#define UDP_PACKET_HB 0x7F
#define UDP_PACKET_DATA 0x0
// Callback type
#define SERVER_CALLBACK_ON_ACCEPT 0x80
#define SERVER_CALLBACK_ON_CONNECT 0x81
#define SERVER_CALLBACK_ON_CLOSE 0x82
#define SERVER_CALLBACK_ON_ERROR 0x83
#define SERVER_CALLBACK_ON_HEARTBEAT 0x84
#define SERVER_CALLBACK_ON_DATA_RAW 0x1
#define SERVER_CALLBACK_ON_DATA_OBJ 0x2
#define SERVER_CALLBACK_ON_DATA_CMD 0x3
#define SERVER_CALLBACK_ON_LOOP_START 0xC1
#define SERVER_CALLBACK_ON_LOOP_EXIT 0xC2
#define SERVER_CALLBACK_ON_LOOP_TIMER 0xC3
/* Macros */
/* Structs */
struct bsp_main_loop_t
{
int loop_fd;
int notify_fd;
int exit_fd;
int timer_fd;
void (*on_start) (unsigned long long);
void (*on_exit) (unsigned long long);
void (*on_timer) (unsigned long long);
};
typedef struct bsp_callback_t
{
BSP_SERVER *server;
BSP_CLIENT *client;
int event;
int cmd;
BSP_STRING *stream;
BSP_OBJECT *obj;
} BSP_CALLBACK;
/* Functions */
BSP_CLIENT * server_accept(BSP_SERVER *srv, struct sockaddr_storage *addr);
// Set main loop's event callback
// We support 3 types of events now :
// SERVER_CALLBACK_ON_LOOP_START - When loop start
// SERVER_CALLBACK_ON_LOOP_EXIT - When loop stop / exit
// SERVER_CALLBACK_ON_LOOP_TIMER - When main timer(1Hz) triggered
//void set_loop_event(int event_type, void (* callback) (unsigned long long));
// Main loop of a server application
//int start_loop(void);
// Stop main loop
//int exit_loop(void);
// Add server to main loop
int add_server(BSP_SERVER *srv);
BSP_SERVER * get_server(const char *name);
size_t output_client_raw(BSP_CLIENT *clt, const char *data, ssize_t len);
size_t output_client_obj(BSP_CLIENT *clt, BSP_OBJECT *obj);
size_t output_client_cmd(BSP_CLIENT *clt, int cmd, BSP_OBJECT *obj);
#endif /* _LIB_BSP_CORE_SERVER_H */
|
gpl-3.0
|
udonsi-kc/hacker-wanna-be
|
Language_Notes/Python_Language/Python_Language_README.md
|
796
|
Directory Name: Python_Language
Did you learn this as your first language? (High-five if you did :)! lol). Like me, you probably were introduced to it because of its "simplicity" and readiness. Basically spoon fed. That's alright, most times its good to get into something from the easier end.
Where you ever tempted to underestimate the power of this language? If so welcome to my enlightenment camp!. This simple language is a simple weapon and in the right hands, its capable of simply doing mighty things! especially in this field of Computer and information security. So yeah, dig up your boots and old hats, lets go exploring!.
This directory will contain code and notes (a note is something worth sharing that is not entirely code. Analysis, light-bulb material, unique stuffs)
|
gpl-3.0
|
Sejemus/Tower-Unite-Piano-Bot
|
Tower Unite Instrument Autoplayer/Core/Interfaces/INote.cs
|
371
|
namespace Tower_Unite_Instrument_Autoplayer.Core
{
/// <summary>
/// This interface is a set of rules that all notes has to follow
/// in order to qualify as a note
/// </summary>
interface INote
{
/// <summary>
/// This method is invoked when the note is reached in the song
/// </summary>
void Play();
}
}
|
gpl-3.0
|
LCyberspazio/exaconv
|
README.md
|
66
|
exaconv
=======
Exadecimal \xNN format to ASCII format converter
|
gpl-3.0
|
mgood7123/UPM
|
Sources/htmlstreamparser-0.4/src/Makefile
|
17595
|
# Makefile.in generated by automake 1.11.3 from Makefile.am.
# src/Makefile. Generated from Makefile.in by configure.
# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
# Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
pkgdatadir = $(datadir)/htmlstreamparser
pkgincludedir = $(includedir)/htmlstreamparser
pkglibdir = $(libdir)/htmlstreamparser
pkglibexecdir = $(libexecdir)/htmlstreamparser
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = x86_64-unknown-linux-gnu
host_triplet = x86_64-unknown-linux-gnu
subdir = src
DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \
$(srcdir)/Makefile.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(install_sh) -d
CONFIG_HEADER = $(top_builddir)/config.h
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
am__vpath_adj = case $$p in \
$(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
*) f=$$p;; \
esac;
am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
am__install_max = 40
am__nobase_strip_setup = \
srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
am__nobase_strip = \
for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
am__nobase_list = $(am__nobase_strip_setup); \
for p in $$list; do echo "$$p $$p"; done | \
sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
$(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
if (++n[$$2] == $(am__install_max)) \
{ print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
END { for (dir in files) print dir, files[dir] }'
am__base_list = \
sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
am__uninstall_files_from_dir = { \
test -z "$$files" \
|| { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
|| { echo " ( cd '$$dir' && rm -f" $$files ")"; \
$(am__cd) "$$dir" && rm -f $$files; }; \
}
am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"
LTLIBRARIES = $(lib_LTLIBRARIES)
libhtmlstreamparser_la_LIBADD =
am_libhtmlstreamparser_la_OBJECTS = htmlstreamparser.lo
libhtmlstreamparser_la_OBJECTS = $(am_libhtmlstreamparser_la_OBJECTS)
DEFAULT_INCLUDES = -I. -I$(top_builddir)
depcomp = $(SHELL) $(top_srcdir)/depcomp
am__depfiles_maybe = depfiles
am__mv = mv -f
COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
--mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
$(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
CCLD = $(CC)
LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
--mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
$(LDFLAGS) -o $@
SOURCES = $(libhtmlstreamparser_la_SOURCES)
DIST_SOURCES = $(libhtmlstreamparser_la_SOURCES)
HEADERS = $(include_HEADERS)
ETAGS = etags
CTAGS = ctags
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = ${SHELL} /home/zorin-os/UPM/Sources/htmlstreamparser-0.4/missing --run aclocal-1.11
AMTAR = $${TAR-tar}
AR = ar
AUTOCONF = ${SHELL} /home/zorin-os/UPM/Sources/htmlstreamparser-0.4/missing --run autoconf
AUTOHEADER = ${SHELL} /home/zorin-os/UPM/Sources/htmlstreamparser-0.4/missing --run autoheader
AUTOMAKE = ${SHELL} /home/zorin-os/UPM/Sources/htmlstreamparser-0.4/missing --run automake-1.11
AWK = gawk
CC = gcc
CCDEPMODE = depmode=gcc3
CFLAGS = -g -O2
CPP = gcc -E
CPPFLAGS =
CYGPATH_W = echo
DEFS = -DHAVE_CONFIG_H
DEPDIR = .deps
DLLTOOL = false
DSYMUTIL =
DUMPBIN =
ECHO_C =
ECHO_N = -n
ECHO_T =
EGREP = /bin/grep -E
EXEEXT =
FGREP = /bin/grep -F
GREP = /bin/grep
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
LD = /usr/bin/ld -m elf_x86_64
LDFLAGS =
LIBOBJS =
LIBS =
LIBTOOL = $(SHELL) $(top_builddir)/libtool
LIPO =
LN_S = ln -s
LTLIBOBJS =
MAKEINFO = ${SHELL} /home/zorin-os/UPM/Sources/htmlstreamparser-0.4/missing --run makeinfo
MANIFEST_TOOL = :
MKDIR_P = /bin/mkdir -p
NM = /usr/bin/nm -B
NMEDIT =
OBJDUMP = objdump
OBJEXT = o
OTOOL =
OTOOL64 =
PACKAGE = htmlstreamparser
PACKAGE_BUGREPORT =
PACKAGE_NAME = htmlstreamparser
PACKAGE_STRING = htmlstreamparser 0.4
PACKAGE_TARNAME = htmlstreamparser
PACKAGE_URL =
PACKAGE_VERSION = 0.4
PATH_SEPARATOR = :
RANLIB = ranlib
SED = /bin/sed
SET_MAKE =
SHELL = /bin/bash
STRIP = strip
VERSION = 0.4
abs_builddir = /home/zorin-os/UPM/Sources/htmlstreamparser-0.4/src
abs_srcdir = /home/zorin-os/UPM/Sources/htmlstreamparser-0.4/src
abs_top_builddir = /home/zorin-os/UPM/Sources/htmlstreamparser-0.4
abs_top_srcdir = /home/zorin-os/UPM/Sources/htmlstreamparser-0.4
ac_ct_AR = ar
ac_ct_CC = gcc
ac_ct_DUMPBIN =
am__include = include
am__leading_dot = .
am__quote =
am__tar = $${TAR-tar} chof - "$$tardir"
am__untar = $${TAR-tar} xf -
bindir = ${exec_prefix}/bin
build = x86_64-unknown-linux-gnu
build_alias =
build_cpu = x86_64
build_os = linux-gnu
build_vendor = unknown
builddir = .
datadir = ${datarootdir}
datarootdir = ${prefix}/share
docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
dvidir = ${docdir}
exec_prefix = ${prefix}
host = x86_64-unknown-linux-gnu
host_alias =
host_cpu = x86_64
host_os = linux-gnu
host_vendor = unknown
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${datarootdir}/info
install_sh = ${SHELL} /home/zorin-os/UPM/Sources/htmlstreamparser-0.4/install-sh
libdir = ${exec_prefix}/lib
libexecdir = ${exec_prefix}/libexec
localedir = ${datarootdir}/locale
localstatedir = ${prefix}/var
mandir = ${datarootdir}/man
mkdir_p = /bin/mkdir -p
oldincludedir = /usr/include
pdfdir = ${docdir}
prefix = /usr/local
program_transform_name = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
srcdir = .
sysconfdir = ${prefix}/etc
target_alias =
top_build_prefix = ../
top_builddir = ..
top_srcdir = ..
lib_LTLIBRARIES = libhtmlstreamparser.la
libhtmlstreamparser_la_SOURCES = htmlstreamparser.c
include_HEADERS = htmlstreamparser.h
all: all-am
.SUFFIXES:
.SUFFIXES: .c .lo .o .obj
$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --gnu src/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
install-libLTLIBRARIES: $(lib_LTLIBRARIES)
@$(NORMAL_INSTALL)
test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
list2=; for p in $$list; do \
if test -f $$p; then \
list2="$$list2 $$p"; \
else :; fi; \
done; \
test -z "$$list2" || { \
echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
$(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
}
uninstall-libLTLIBRARIES:
@$(NORMAL_UNINSTALL)
@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
for p in $$list; do \
$(am__strip_dir) \
echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \
$(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \
done
clean-libLTLIBRARIES:
-test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES)
@list='$(lib_LTLIBRARIES)'; for p in $$list; do \
dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
test "$$dir" != "$$p" || dir=.; \
echo "rm -f \"$${dir}/so_locations\""; \
rm -f "$${dir}/so_locations"; \
done
libhtmlstreamparser.la: $(libhtmlstreamparser_la_OBJECTS) $(libhtmlstreamparser_la_DEPENDENCIES) $(EXTRA_libhtmlstreamparser_la_DEPENDENCIES)
$(LINK) -rpath $(libdir) $(libhtmlstreamparser_la_OBJECTS) $(libhtmlstreamparser_la_LIBADD) $(LIBS)
mostlyclean-compile:
-rm -f *.$(OBJEXT)
distclean-compile:
-rm -f *.tab.c
include ./$(DEPDIR)/htmlstreamparser.Plo
.c.o:
$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
# source='$<' object='$@' libtool=no \
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
# $(COMPILE) -c $<
.c.obj:
$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
# source='$<' object='$@' libtool=no \
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
# $(COMPILE) -c `$(CYGPATH_W) '$<'`
.c.lo:
$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
# source='$<' object='$@' libtool=yes \
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
# $(LTCOMPILE) -c -o $@ $<
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
install-includeHEADERS: $(include_HEADERS)
@$(NORMAL_INSTALL)
test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
@list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \
for p in $$list; do \
if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
echo "$$d$$p"; \
done | $(am__base_list) | \
while read files; do \
echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
$(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
done
uninstall-includeHEADERS:
@$(NORMAL_UNINSTALL)
@list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \
files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir)
ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
mkid -fID $$unique
tags: TAGS
TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
set x; \
here=`pwd`; \
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: CTAGS
CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile $(LTLIBRARIES) $(HEADERS)
installdirs:
for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"; do \
test -z "$$dir" || $(MKDIR_P) "$$dir"; \
done
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
if test -z '$(STRIP)'; then \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
fi
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \
mostlyclean-am
distclean: distclean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
distclean-am: clean-am distclean-compile distclean-generic \
distclean-tags
dvi: dvi-am
dvi-am:
html: html-am
html-am:
info: info-am
info-am:
install-data-am: install-includeHEADERS
install-dvi: install-dvi-am
install-dvi-am:
install-exec-am: install-libLTLIBRARIES
install-html: install-html-am
install-html-am:
install-info: install-info-am
install-info-am:
install-man:
install-pdf: install-pdf-am
install-pdf-am:
install-ps: install-ps-am
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -rf ./$(DEPDIR)
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-compile mostlyclean-generic \
mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am: uninstall-includeHEADERS uninstall-libLTLIBRARIES
.MAKE: install-am install-strip
.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
clean-libLTLIBRARIES clean-libtool ctags distclean \
distclean-compile distclean-generic distclean-libtool \
distclean-tags distdir dvi dvi-am html html-am info info-am \
install install-am install-data install-data-am install-dvi \
install-dvi-am install-exec install-exec-am install-html \
install-html-am install-includeHEADERS install-info \
install-info-am install-libLTLIBRARIES install-man install-pdf \
install-pdf-am install-ps install-ps-am install-strip \
installcheck installcheck-am installdirs maintainer-clean \
maintainer-clean-generic mostlyclean mostlyclean-compile \
mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
tags uninstall uninstall-am uninstall-includeHEADERS \
uninstall-libLTLIBRARIES
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
|
gpl-3.0
|
mvpel/core
|
libpromises/mod_storage.h
|
1143
|
/*
Copyright (C) CFEngine AS
This file is part of CFEngine 3 - written and maintained by CFEngine AS.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; version 3.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
To the extent this program is licensed as part of the Enterprise
versions of CFEngine, the applicable Commerical Open Source License
(COSL) may apply to this file if you as a licensee so wish it. See
included file COSL.txt.
*/
#ifndef CFENGINE_MOD_STORAGE_H
#define CFENGINE_MOD_STORAGE_H
#include "cf3.defs.h"
extern const PromiseTypeSyntax CF_STORAGE_PROMISE_TYPES[];
#endif
|
gpl-3.0
|
MaxGavr/breakdown_game
|
globs.py
|
3049
|
import libtcodpy as libtcod
#globs are imported almost everywhere, so unnecessary libtcod imports should be omitted
##########################################################
# Options
##########################################################
#it's better to pack them into separate file
LIMIT_FPS = 20
#size of the map
MAP_WIDTH = 100
MAP_HEIGHT = 80
#size of the camera screen
CAMERA_WIDTH = 80
CAMERA_HEIGHT = 43
#size of the window
SCREEN_WIDTH = 80
SCREEN_HEIGHT = 50
#map generating settings
MAX_ROOM_ENEMIES = 3
MAX_ROOM_ITEMS = 3
#BSP options
DEPTH = 10 #number of node splittings
ROOM_MIN_SIZE = 6
FULL_ROOMS = False
#sizes and coordinates for GUI
PANEL_HEIGHT = 7
BAR_WIDTH = 20
PANEL_Y = SCREEN_HEIGHT - PANEL_HEIGHT
MESSAGE_X = BAR_WIDTH + 2
MESSAGE_WIDTH = SCREEN_WIDTH - BAR_WIDTH - 2
MESSAGE_HEIGHT = PANEL_HEIGHT - 1
#inventory properties
MAX_INVENTORY_SIZE = 26
INVENTORY_WIDTH = 50
#item properties
STIM_HEAL_AMOUNT = 50
DISCHARGE_DAMAGE = 100
ITEM_USING_RANGE = 5
CONFUSE_TURNS = 10
GRENADE_DAMAGE = 30
GRENADE_RADIUS = 3
#weapon properties
WEAPON_RANGE = 5
LASER_PISTOL_DAMAGE = 20
LASER_RIFLE_DAMAGE = 50
#experience properties
LEVEL_UP_BASE = 100
LEVEL_UP_FACTOR = 150
#FOV properties
FOV_ALGO = 0
FOV_LIGHT_WALLS = True
TORCH_RADIUS = 10
##########################################################
#colors of invisible tiles
c_hid_wall = libtcod.Color(22, 7, 115)
c_hid_floor = libtcod.Color(55, 46, 133)
#colors of visible tiles
c_vis_wall = libtcod.Color(148, 122, 23)
c_vis_floor = libtcod.Color(180, 155, 58)
#colors of highlighted tiles
c_hi_wall = libtcod.Color(67, 128, 211)
c_hi_floor = libtcod.Color(105, 150, 211)
#possible tile types
#properties description:
# title - just a name for a specific terrain, also used as key for a corresponding tile type in 'TYLE_TYPES' dict
# walkable - indicates, if tiles of this type can hold an object (character, item and so on) on the top of itself
# transparent - indicates, whether the tile blocks line of sight during calculating FOV for characters or not
# vis_color, hid_color, hi_color - visible color, hidden color, highlighted color respectively; used in 'calculate_color' function
#
#current types: 'floor', 'wall'
#
#in order to add new type, just create additional dict holding its properties as shown below and append it to 'TYLE_TYPES'
#'tile_type' used in 'Tile.set_type' is the keyword of a corresponding type in 'TILE_TYPES'
floor = {'title': 'f1loor', 'walkable': True, 'transparent': True, 'vis_color': c_vis_floor, 'hid_color': c_hid_floor, 'hi_color': c_hi_floor}
wall = {'title': 'metal wall', 'walkable': False, 'transparent': False, 'vis_color': c_vis_wall, 'hid_color': c_hid_wall, 'hi_color': c_hi_wall}
TILE_TYPES = {'floor': floor, 'wall': wall}
#variables for input handling
#they are kept here, as they don't hold any used information outside input-handling functions
#it doesn't matter, if they are constantly reinitializing
key = libtcod.Key()
mouse = libtcod.Mouse()
##########################################################
|
gpl-3.0
|
UPenn-RoboCup/UPennalizers
|
Player/Motion/divewait.lua
|
3451
|
module(..., package.seeall);
name = ...;
require('Config')
require('vector')
require('Kinematics')
require('Body')
require('walk')
require('mcm')
active = true;
t0 = 0;
footY = Config.walk.footY;
supportX = Config.walk.supportX;
bodyHeight = Config.stance.bodyHeightDive or 0.25;
bodyTilt = Config.stance.bodyTiltDive or 0;
-- Max change in postion6D to reach stance:
dpLimit=Config.stance.dpLimitDive or
vector.new({.1,.01,.03,.1,.3,.1});
tFinish=0;
tStartWait=0.2;
tEndWait=0.1;
tStart=0;
finished=false;
function entry()
print("Motion SM:".._NAME.." entry");
footX = mcm.get_footX();
-- Final stance foot position6D
pTorsoTarget = vector.new({0, 0, bodyHeight, 0,bodyTilt,0});
pLLeg = vector.new({-supportX + footX, footY, 0, 0,0,0});
pRLeg = vector.new({-supportX + footX, -footY, 0, 0,0,0});
walk.stop();
started=false;
finished=false;
-- Body.set_head_hardness(.5);
Body.set_larm_hardness(.1);
Body.set_rarm_hardness(.1);
t0=Body.get_time();
mcm.set_walk_isMoving(0); --not walking
end
function update()
local t = Body.get_time();
if walk.active then
walk.update();
t0=Body.get_time();
return;
end
if finished then
return;
end
--[[
if not started then
--For OP, wait a bit to read joint readings
if t-t0>tStartWait then
started=true;
local qLLeg = Body.get_lleg_position();
local qRLeg = Body.get_rleg_position();
local dpLLeg = Kinematics.torso_lleg(qLLeg);
local dpRLeg = Kinematics.torso_rleg(qRLeg);
pTorsoL=pLLeg+dpLLeg;
pTorsoR=pRLeg+dpRLeg;
pTorso=(pTorsoL+pTorsoR)*0.5;
Body.set_lleg_command(qLLeg);
Body.set_rleg_command(qRLeg);
Body.set_lleg_hardness(1);
Body.set_rleg_hardness(1);
t0 = Body.get_time();
tStart=t;
count=1;
Body.set_syncread_enable(0);
else
Body.set_syncread_enable(1);
return;
end
end
--]]
--Sit init NOT using joint encoder
if not started then
started=true;
--Now we assume that the robot always start sitting from stance position
pTorso = vector.new({-footX,0,vcm.get_camera_bodyHeight(),
0,vcm.get_camera_bodyTilt(),0});
pLLeg = vector.new({-supportX,footY,0,0,0,0});
pRLeg= vector.new({-supportX,-footY,0,0,0,0});
Body.set_lleg_hardness(1);
Body.set_rleg_hardness(1);
t0 = Body.get_time();
tStart=t;
count=1;
end
local dt = t - t0;
t0 = t;
local tol = true;
local tolLimit = 1e-6;
dpDeltaMax = dt*dpLimit;
dpTorso = pTorsoTarget - pTorso;
for i = 1,6 do
if (math.abs(dpTorso[i]) > tolLimit) then
tol = false;
if (dpTorso[i] > dpDeltaMax[i]) then
dpTorso[i] = dpDeltaMax[i];
elseif (dpTorso[i] < -dpDeltaMax[i]) then
dpTorso[i] = -dpDeltaMax[i];
end
end
end
pTorso=pTorso+dpTorso;
vcm.set_camera_bodyHeight(pTorso[3]);
vcm.set_camera_bodyTilt(pTorso[5]);
-- print("BodyHeight/Tilt:",pTorso[3],pTorso[5]*180/math.pi)
q = Kinematics.inverse_legs(pLLeg, pRLeg, pTorso, 0);
Body.set_lleg_command(q);
if Config.platform.name == 'NaoV4' then
for i=1,12 do
Body.commanded_joint_angles[6+i] = q[i];
end
end
if (tol) then
if tFinish==0 then
tFinish=t;
else
if t-tFinish>tEndWait then
finished=true;
print("Sit done, time elapsed",t-tStart)
end
end
end
end
function exit()
Body.set_syncread_enable(1);
end
|
gpl-3.0
|