code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
#!/usr/bin/env node
/*
Saves the DB to country specific downloads packages
*/
const fs = require("fs");
const path = require("path");
const zlib = require("zlib");
const async = require("async");
const ndjson = require("ndjson");
const status = require("node-status");
const Store = require("../lib/store.js");
const config = require("../config.js");
const console = status.console();
const Utils = require("../lib/utils");
const CSV = require("../lib/csv");
const Library = require("../lib/library.js");
const archiver = require("archiver");
const now = new Date().valueOf();
const library = new Library(config);
const csv = new CSV(library);
let currentCountry = "-";
let currentAction = "";
let status_items = status.addItem("items");
status.addItem("country", {
custom: () => {
return currentCountry;
}
});
let status_portals = status.addItem("portals");
status.addItem("current", {
custom: () => {
return currentAction;
}
});
let downloadsFolder = path.join(config.data.shared, "downloads");
let portals = JSON.parse(fs.readFileSync(path.join(config.data.shared, "portals.json")).toString()).reverse();
portals.push({
id: "ted",
name: "TED"
});
let store = new Store(config);
let results = [];
let compressStream = (stream) => {
let compress = zlib.createGzip();
compress.pipe(stream);
return compress;
};
let uncompressStream = (stream) => {
let uncompress = zlib.createGunzip();
stream.pipe(uncompress);
return uncompress;
};
let streamItems = (country_id, onItems, onEnd) => {
let query = { match_all: {} };
if (country_id.toUpperCase() !== "ALL") {
query = { term: { "ot.country": country_id.toUpperCase() } };
}
if (country_id.toUpperCase() == "TED") {
query = {
bool: {
should: [
{
bool: {
must: [
{ match: { "publications.source": "http://ted.europa.eu" } },
{ match: { "publications.isIncluded": true } }
]
}
},
{
bool: {
must: [
{ match: { "publications.source": "http://data.europa.eu" } },
{ match: { "publications.isIncluded": true } }
]
}
}
]
}
};
}
let pos = 0;
store.Tender.streamQuery(
1000,
query,
(items, total) => {
pos += items.length;
if (!onItems(items, pos, total)) {
return false;
}
status_items.count = pos;
status_items.max = total;
return true;
},
(err) => {
onEnd(err, pos);
}
);
};
let downloadFolderFileStream = (filename) => {
let fullFilename = path.join(downloadsFolder, filename);
let outputStream = fs.createWriteStream(fullFilename);
return outputStream;
};
class DownloadPack {
constructor(format, filename) {
this.format = format;
this.filename = filename;
this.zipfilename = filename + "-" + this.format + ".zip";
this.streams = {};
}
openStream(filename) {
let filestream = downloadFolderFileStream(filename);
let stream = compressStream(filestream);
stream.orgstream = filestream;
return stream;
}
closeStream(stream, cb) {
stream.orgstream.on("close", (err) => {
cb();
});
stream.end();
}
validateStream(year) {
if (!this.streams[year]) {
let filename = this.filename + "-" + year + "." + this.format;
this.streams[year] = {
filename: filename,
stream: this.openStream(filename + ".gz"),
count: 0
};
}
return this.streams[year];
}
write(year, data) {
let yearstream = this.validateStream(year);
yearstream.stream.write(data);
yearstream.count++;
}
zip(cb) {
let toZipFilenames = Object.keys(this.streams).map((key) => this.streams[key].filename);
const stream = downloadFolderFileStream(this.zipfilename);
const archive = archiver("zip", {
// store: true
zlib: { level: 9 } // Sets the compression level.
});
stream.on("close", function () {
currentAction = "";
// console.log(archive.pointer() + ' total bytes');
cb();
});
stream.on("end", function () {
// console.log('Data has been drained');
});
archive.on("entry", function (entry) {
currentAction = "Zipping: " + entry.name;
});
archive.on("warning", function (err) {
console.log(err);
});
archive.on("error", function (err) {
console.log(err);
});
archive.on("progress", function (progress) {
// console.log(progress);
});
toZipFilenames.forEach((toZipFilename) => {
let fullFilename = path.join(downloadsFolder, toZipFilename + ".gz");
let filestream = fs.createReadStream(fullFilename);
let stream = uncompressStream(filestream);
archive.append(stream, { name: toZipFilename });
// archive.file(fullFilename, {name: toZipFilename});
});
// console.log('Zipping', filename, 'Files:', JSON.stringify(toZipFilenames));
archive.pipe(stream);
archive.finalize();
}
removeFiles(cb) {
async.forEach(
Object.keys(this.streams),
(key, next) => {
let fullFilename = path.join(downloadsFolder, this.streams[key].filename + ".gz");
fs.unlink(fullFilename, (err) => {
next(err);
});
},
(err) => {
cb(err);
}
);
}
closeStreams(cb) {
async.forEach(
Object.keys(this.streams),
(key, next) => {
this.closeStream(this.streams[key].stream, next);
},
(err) => {
cb(err);
}
);
}
close(cb) {
this.closeStreams((err) => {
if (err) {
return cb(err);
}
this.zip((err) => {
if (err) {
return cb(err);
}
this.removeFiles((err) => {
cb(err, {
filename: this.zipfilename,
size: fs.statSync(path.join(downloadsFolder, this.zipfilename)).size
});
});
});
});
}
writeTender(data, index, total) {}
}
class DownloadPackCSV extends DownloadPack {
constructor(filename) {
super("csv", filename);
}
writeTender(year, tender) {
let yearstream = this.validateStream(year);
if (yearstream.count === 0) {
yearstream.stream.write(csv.header());
}
this.write(year, csv.transform(tender, yearstream.count + 1));
}
}
class DownloadPackJSON extends DownloadPack {
constructor(filename) {
super("json", filename);
}
openStream(filename) {
let filestream = downloadFolderFileStream(filename);
let stream = compressStream(filestream);
stream.orgstream = filestream;
stream.write("[");
return stream;
}
closeStream(stream, cb) {
stream.write("]");
stream.orgstream.on("close", (err) => {
cb();
});
stream.end();
}
writeTender(year, tender) {
let yearstream = this.validateStream(year);
this.write(year, (yearstream.count !== 0 ? "," : "") + JSON.stringify(tender));
}
}
class DownloadPackNDJSON extends DownloadPack {
constructor(filename) {
super("ndjson", filename);
}
openStream(filename) {
let filestream = downloadFolderFileStream(filename);
let compressstream = compressStream(filestream);
let stream = ndjson.serialize();
stream.compressstream = compressstream;
stream.orgstream = filestream;
stream.on("data", (line) => {
compressstream.write(line);
});
return stream;
}
closeStream(stream, cb) {
stream.orgstream.on("close", () => {
cb();
});
stream.end();
stream.compressstream.end();
}
writeTender(year, tender) {
this.write(year, tender);
}
}
let dump = (country, cb) => {
currentCountry = country.name;
let countryId = country.id ? country.id.toLowerCase() : "all";
let filename = "data-" + countryId;
console.log("Saving downloads for " + currentCountry);
let totalItems = 0;
let csvpack = new DownloadPackCSV(filename);
let jsonpack = new DownloadPackJSON(filename);
let ndjsonpack = new DownloadPackNDJSON(filename);
currentAction = "Streaming: " + filename;
streamItems(
countryId,
(items, pos, total) => {
items.forEach((item, index) => {
let year = (item._source.ot.date || "").slice(0, 4);
if (year.length !== 4) {
year = "year-unavailable";
}
Utils.cleanOtFields(item._source);
csvpack.writeTender(year, item._source);
jsonpack.writeTender(year, item._source);
ndjsonpack.writeTender(year, item._source);
});
status_items.count = pos;
status_items.max = total;
totalItems = total;
return true;
},
(err, total) => {
totalItems = total;
csvpack.close((err, file_csv) => {
jsonpack.close((err, file_json) => {
ndjsonpack.close((err, file_ndjson) => {
let result = {
country: countryId,
count: totalItems,
lastUpdate: now,
formats: {
json: file_json,
ndjson: file_ndjson,
csv: file_csv
}
};
results.push(result);
cb();
});
});
});
}
);
};
store.init((err) => {
if (err) {
return console.log(err);
}
status.start({ pattern: "@{uptime} | {spinner.cyan} | {items} | {country.custom} | {portals} | {current.custom}" });
let pos = 0;
status_portals.count = 0;
status_portals.max = portals.length;
async.forEachSeries(
portals,
(portal, next) => {
status_portals.count = ++pos;
// if (!portal.id) return next();
dump(portal, next);
},
(err) => {
if (err) {
console.log(err);
}
store.close(() => {
status.stop();
fs.writeFileSync(path.join(downloadsFolder, "downloads.json"), JSON.stringify(results, null, "\t"));
console.log("done");
});
}
);
});
|
digiwhist/opentender-backend
|
bin/save_downloads.js
|
JavaScript
|
mit
| 11,617
|
/**
* @module node-opcua-address-space.AlarmsAndConditions
*/
import { assert } from "node-opcua-assert";
import { DataValue } from "node-opcua-data-value";
import { NodeId } from "node-opcua-nodeid";
import { DataType } from "node-opcua-variant";
import { UAExclusiveDeviationAlarm_Base } from "node-opcua-nodeset-ua";
import { UAVariable, UAVariableT } from "../../source";
import { AddressSpace } from "../address_space";
import { NamespacePrivate } from "../namespace_private";
import {
DeviationAlarmHelper_getSetpointNodeNode,
DeviationAlarmHelper_getSetpointValue,
DeviationAlarmHelper_install_setpoint,
DeviationAlarmHelper_onSetpointDataValueChange,
DeviationStuff,
InstallSetPointOptions
} from "./deviation_alarm_helper";
import { UAExclusiveLimitAlarmEx, UAExclusiveLimitAlarmImpl } from "./ua_exclusive_limit_alarm_impl";
import { UALimitAlarmImpl } from "./ua_limit_alarm_impl";
export interface UAExclusiveDeviationAlarmEx
extends Omit<
UAExclusiveDeviationAlarm_Base,
| "ackedState"
| "activeState"
| "confirmedState"
| "enabledState"
| "latchedState"
| "limitState"
| "outOfServiceState"
| "shelvingState"
| "silenceState"
| "suppressedState"
>,
UAExclusiveLimitAlarmEx,
DeviationStuff {}
export declare interface UAExclusiveDeviationAlarmImpl extends UAExclusiveDeviationAlarmEx, UAExclusiveLimitAlarmImpl {
on(eventName: string, eventHandler: any): this;
get addressSpace(): AddressSpace;
}
export class UAExclusiveDeviationAlarmImpl extends UAExclusiveLimitAlarmImpl implements UAExclusiveDeviationAlarmEx {
public static instantiate(
namespace: NamespacePrivate,
type: string | NodeId,
options: any,
data: any
): UAExclusiveDeviationAlarmImpl {
const addressSpace = namespace.addressSpace;
const exclusiveDeviationAlarmType = addressSpace.findEventType("ExclusiveDeviationAlarmType");
/* istanbul ignore next */
if (!exclusiveDeviationAlarmType) {
throw new Error("cannot find ExclusiveDeviationAlarmType");
}
assert(type === exclusiveDeviationAlarmType.browseName.toString());
const alarm = UAExclusiveLimitAlarmImpl.instantiate(namespace, type, options, data) as UAExclusiveDeviationAlarmImpl;
Object.setPrototypeOf(alarm, UAExclusiveDeviationAlarmImpl.prototype);
assert(alarm instanceof UAExclusiveDeviationAlarmImpl);
assert(alarm instanceof UAExclusiveLimitAlarmImpl);
assert(alarm instanceof UALimitAlarmImpl);
alarm._install_setpoint(options);
return alarm;
}
public getSetpointNodeNode(): UAVariable {
return DeviationAlarmHelper_getSetpointNodeNode.call(this);
}
public getSetpointValue(): number | null {
return DeviationAlarmHelper_getSetpointValue.call(this);
}
public _onSetpointDataValueChange(dataValue: DataValue): void {
DeviationAlarmHelper_onSetpointDataValueChange.call(this, dataValue);
}
public _install_setpoint(options: InstallSetPointOptions): any {
return DeviationAlarmHelper_install_setpoint.call(this, options);
}
public _setStateBasedOnInputValue(value: number): void {
const setpointValue = this.getSetpointValue();
if (setpointValue === null) {
return;
}
assert(isFinite(setpointValue));
// call base class implementation
UAExclusiveLimitAlarmImpl.prototype._setStateBasedOnInputValue.call(this, value - setpointValue);
}
}
export interface UAExclusiveDeviationAlarmHelper {
setpointNode: UAVariableT<NodeId, DataType.NodeId>;
setpointNodeNode: UAVariable;
}
/*
UAExclusiveDeviationAlarm.prototype.getSetpointNodeNode = DeviationAlarmHelper.getSetpointNodeNode;
UAExclusiveDeviationAlarm.prototype.getSetpointValue = DeviationAlarmHelper.getSetpointValue;
UAExclusiveDeviationAlarm.prototype._onSetpointDataValueChange = DeviationAlarmHelper._onSetpointDataValueChange;
UAExclusiveDeviationAlarm.prototype._install_setpoint = DeviationAlarmHelper._install_setpoint;
*/
|
node-opcua/node-opcua
|
packages/node-opcua-address-space/src/alarms_and_conditions/ua_exclusive_deviation_alarm_impl.ts
|
TypeScript
|
mit
| 4,233
|
/*
* Copyright (c) Kuno Contributors
*
* This file is subject to the terms and conditions defined in
* the LICENSE file, which is part of this source code package.
*/
namespace Kuno.Validation
{
/// <summary>
/// Indicates the validation error type.
/// </summary>
public enum ValidationType
{
/// <summary>
/// Indicates a type was not specified.
/// </summary>
None,
/// <summary>
/// Indicates an input validation message.
/// </summary>
Input,
/// <summary>
/// Indicates an security validation message.
/// </summary>
Security,
/// <summary>
/// Indicates a business validation message.
/// </summary>
Business
}
}
|
kuno-framework/kuno
|
Core/Kuno/Validation/ValidationType.cs
|
C#
|
mit
| 785
|
import IGMResource from "./IGMResource";
import GMSubscript from "./GMSubscript";
export default interface IGMScript extends IGMResource {
/**
* The file location of the GML file
*/
readonly filepath: string;
/**
* Returns an iterator with each SubScript in this script
*/
subScripts(gmlText: string): IterableIterator<GMSubscript>;
}
|
jhm-ciberman/docs_gm
|
src/gm_project/IGMScript.d.ts
|
TypeScript
|
mit
| 363
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description':'End to end solution for bitcoin data gathering, backtesting, and live trading',
'author': 'ross palmer',
'url':'http://rosspalmer.github.io/bitQuant/',
'license':'MIT',
'version': '0.2.10',
'install_requires': ['SQLAlchemy','pandas','numpy','scipy','PyMySQL'],
'packages': ['bitquant'],
'scripts': [],
'name':'bitquant'
}
setup(**config)
|
multidis/bitQuant02
|
setup.py
|
Python
|
mit
| 464
|
/**
* Created by andypax on 15/10/16.
*/
export class PasseadorModel {
constructor(
public nome?: string,
public sobreNome?: string,
public endereco?: string,
public numero?: string,
public complemento?: string,
public cidade?: string,
public cep?: string,
public estado?: string,
public telefone?: string,
public celular?: string,
public foto?: string,
public email?: string,
public preco?: number,
public login?: string,
public senha?: string,
public confirmarSenha?: string
){}
}
|
andpax/PetMais
|
app/passeador/passeador.model.ts
|
TypeScript
|
mit
| 621
|
import { Container, Optional } from 'aurelia-dependency-injection';
import {
GlobalValidationConfiguration,
ValidationControllerFactory,
ValidationController,
Validator,
validateTrigger
} from '../src/aurelia-validation';
describe('ValidationControllerFactory', () => {
it('createForCurrentScope', () => {
const container = new Container();
const standardValidator = {};
container.registerInstance(Validator, standardValidator);
const config = new GlobalValidationConfiguration();
config.defaultValidationTrigger(validateTrigger.manual);
container.registerInstance(GlobalValidationConfiguration, config);
const childContainer = container.createChild();
const factory = childContainer.get(ValidationControllerFactory);
const controller = factory.createForCurrentScope();
expect(controller['validator']).toBe(standardValidator);
expect(controller.validateTrigger).toBe(validateTrigger.manual);
expect(container.get(Optional.of(ValidationController))).toBe(null);
expect(childContainer.get(Optional.of(ValidationController))).toBe(controller);
const customValidator = {};
expect(factory.createForCurrentScope(customValidator as Validator)['validator']).toBe(customValidator);
});
});
|
aurelia/validation
|
test/validation-controller-factory.ts
|
TypeScript
|
mit
| 1,284
|
# GitterSmsBridge
[](https://gitter.im/jtrinklein/GitterSmsBridge?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
jtrinklein/GitterSmsBridge
|
README.md
|
Markdown
|
mit
| 192
|
<!DOCTYPE html>
<!--[if IE 9 ]><html class="ie9"><![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SUC</title>
<?php $this->load->view('templates/styles'); ?>
</head>
<body data-ma-header="teal">
<?php $this->load->view('templates/header'); ?>
<section id="main">
<?php $this->load->view($this->strategy_context->get_menu()); ?>
<section id="content">
<div class="container">
<div class="c-header">
<h2>Tipos de Alimentos</h2> <!--TODO CC: Pass style inline to css class-->
</div>
<div class="card">
<div class="card-body card-padding">
<form class="row" role="form">
<div class="col-sm-4">
<div style="position: relative;display: block;margin-top: 10px;margin-bottom: 10px;"> <!--TODO CC: Pass style inline to css class-->
<label>
¿Desea crear un nuevo tipo de alimento?
</label>
</div>
</div>
<div class="col-sm-4">
<a href="<?php echo base_url('food_type/add');?>" class="btn btn-primary btn-sm m-t-5 waves-effect">Crear</a>
</div>
</form>
</div>
</div>
<div class="card">
<div class="card-body card-padding" style="padding-bottom:0"></div> <!--TODO CC: Pass style inline to css class-->
<table id="data-table-command" class="table table-striped table-vmiddle bootgrid-table">
<thead>
<tr>
<th data-column-id="id" data-visible="false">ID</th>
<th data-column-id="code" data-order="desc">Código</th>
<th data-column-id="name" data-order="desc">Nombre</th>
<th data-column-id="description">Descripción</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Modificar/Borrar</th>
</tr>
</thead>
</table>
</div>
</div>
<input hidden id="data-request-url" value="<?php echo isset($_ci_vars['data-request-url']) ? $_ci_vars['data-request-url'] : '' ?>"></input>
</section>
<?php $this->load->view('templates/footer'); ?>
</section>
<?php $this->load->view('templates/scripts'); ?>
<script src="<?php echo base_url('js/tableGrid.js')?>"></script>
<!-- Data Table -->
<script type="text/javascript">
loadBootgrid({
selector: "#data-table-command",
requestUrl: $("#data-request-url")[0].value,
noResultText: "No hay tipos de alimentos cargados",
infos: "Viendo {{ctx.start}} de {{ctx.end}} de {{ctx.total}} tipos de alimento",
editUrl: "<?php echo site_url($this->strategy_context->get_url('food_type/edit/')) ?>",
deleteUrl: "<?php echo site_url($this->strategy_context->get_url('food_type/delete/')) ?>",
deleteDialogTitle: "¿Está seguro en borrar este tipo de alimento?",
deleteDialogText: "El tipo de alimento se borrará permanentemente del sistema",
deleteDialogSuccess: "El tipo de alimento se ha borrado del sistema.",
searchTxt: "Buscar por nombre",
showDelete: true
});
</script>
</body>
</html>
|
caeceteam/suc_web
|
application/views/food_type/search.php
|
PHP
|
mit
| 3,841
|
import React from 'react'
import PropTypes from 'prop-types'
import { EditorialOverlay } from '../editorials/EditorialParts'
import { css, media } from '../../styles/jss'
import * as s from '../../styles/jso'
import * as ENV from '../../../env'
const spinGif = '/static/images/support/ello-spin.gif'
const imageStyle = css(s.block, { margin: '0 auto 75px' })
const errorStyle = css(
{ maxWidth: 780 },
s.px10,
s.mb30,
s.fontSize14,
media(s.minBreak2, s.px0),
)
export const ErrorStateImage = () =>
<img className={imageStyle} src={spinGif} alt="Ello" width="130" height="130" />
export const ErrorState = ({ children = 'Something went wrong.' }) =>
(<div className={errorStyle}>
{children}
</div>)
ErrorState.propTypes = {
children: PropTypes.node,
}
export const ErrorState4xx = ({ withImage = true }) =>
(<ErrorState>
{withImage ? <ErrorStateImage /> : null}
<p>This doesn’t happen often, but it looks like something is broken. Hitting the back button and trying again might be your best bet. If that doesn’t work you can <a href="http://ello.co/">head back to the homepage.</a></p>
<p>There might be more information on our <a href="http://status.ello.co/">status page</a>.</p>
<p>If all else fails you can try checking out our <a href="http://ello.threadless.com/" target="_blank" rel="noopener noreferrer">Store</a> or the <a href={`${ENV.AUTH_DOMAIN}/wtf/post/communitydirectory`}>Community Directory</a>.</p>
</ErrorState>)
ErrorState4xx.propTypes = {
withImage: PropTypes.bool,
}
export const ErrorState5xx = ({ withImage = true }) =>
(<ErrorState>
{withImage ? <ErrorStateImage /> : null}
<p>It looks like something is broken and we couldn’t complete your request. Please try again in a few minutes. If that doesn’t work you can <a href="http://ello.co/">head back to the homepage.</a></p>
<p>There might be more information on our <a href="http://status.ello.co/">status page</a>.</p>
<p>If all else fails you can try checking out our <a href="http://ello.threadless.com/" target="_blank" rel="noopener noreferrer">Store</a> or the <a href={`${ENV.AUTH_DOMAIN}/wtf/post/communitydirectory`}>Community Directory</a>.</p>
</ErrorState>)
ErrorState5xx.propTypes = {
withImage: PropTypes.bool,
}
// -------------------------------------
const errorEditorialStyle = css(
s.absolute,
s.flood,
s.flex,
s.justifyCenter,
s.itemsCenter,
s.fontSize14,
s.colorWhite,
s.bgcRed,
s.pointerNone,
)
const errorEditorialTextStyle = css(
s.relative,
s.zIndex2,
s.colorWhite,
)
export const ErrorStateEditorial = () => (
<div className={errorEditorialStyle}>
<span className={errorEditorialTextStyle}>Something went wrong.</span>
<EditorialOverlay />
</div>
)
|
ello/webapp
|
src/components/errors/Errors.js
|
JavaScript
|
mit
| 2,790
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_112) on Fri Feb 17 01:05:18 ICT 2017 -->
<title>User (Github-Request 2.2.3)</title>
<meta name="date" content="2017-02-17">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="User (Github-Request 2.2.3)";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10,"i10":10,"i11":10,"i12":9,"i13":10,"i14":10,"i15":10};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/kamontat/model/github/TableInformation.html" title="interface in com.kamontat.model.github"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/kamontat/model/github/User.html" target="_top">Frames</a></li>
<li><a href="User.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.kamontat.model.github</div>
<h2 title="Class User" class="title">Class User</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.kamontat.model.github.User</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../com/kamontat/model/github/TableInformation.html" title="interface in com.kamontat.model.github">TableInformation</a><<a href="../../../../com/kamontat/model/github/User.html" title="class in com.kamontat.model.github">User</a>></dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">User</span>
extends java.lang.Object
implements <a href="../../../../com/kamontat/model/github/TableInformation.html" title="interface in com.kamontat.model.github">TableInformation</a><<a href="../../../../com/kamontat/model/github/User.html" title="class in com.kamontat.model.github">User</a>></pre>
<dl>
<dt><span class="simpleTagLabel">Since:</span></dt>
<dd>1/25/2017 AD - 10:42 PM</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.net.URL</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#api_url">api_url</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.Date</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#createAt">createAt</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>org.kohsuke.github.GHMyself</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#githubMy">githubMy</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>org.kohsuke.github.GHUser</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#githubUser">githubUser</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.net.URL</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#image_url">image_url</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#location">location</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#loginName">loginName</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#name">name</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#surname">surname</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.Date</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#updateAt">updateAt</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.net.URL</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#url">url</a></span></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#User-org.kohsuke.github.GHMyself-">User</a></span>(org.kohsuke.github.GHMyself my)</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#User-org.kohsuke.github.GHUser-">User</a></span>(org.kohsuke.github.GHUser user)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#equals-java.lang.Object-">equals</a></span>(java.lang.Object obj)</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getCompany--">getCompany</a></span>()</code> </td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getEmail--">getEmail</a></span>()</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getID--">getID</a></span>()</code> </td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>javax.swing.ImageIcon</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getImage--">getImage</a></span>()</code> </td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>javax.swing.ImageIcon</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getImage-int-int-">getImage</a></span>(int w,
int h)</code> </td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getName--">getName</a></span>()</code> </td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code><a href="../../../../com/kamontat/model/github/User.html" title="class in com.kamontat.model.github">User</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getRawData--">getRawData</a></span>()</code> </td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>java.util.Map<java.lang.String,org.kohsuke.github.GHRepository></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getRepositories--">getRepositories</a></span>()</code> </td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>org.kohsuke.github.GHRepository</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getRepository-java.lang.String-">getRepository</a></span>(java.lang.String name)</code> </td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>java.util.Vector<java.lang.Object></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getStringInformationVector--">getStringInformationVector</a></span>()</code> </td>
</tr>
<tr id="i11" class="rowColor">
<td class="colFirst"><code>java.util.Vector<java.lang.String></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getStringTitleVector--">getStringTitleVector</a></span>()</code> </td>
</tr>
<tr id="i12" class="altColor">
<td class="colFirst"><code>static java.util.Vector<java.lang.String></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#getStringTitleVectorStatic--">getStringTitleVectorStatic</a></span>()</code> </td>
</tr>
<tr id="i13" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#isFullName--">isFullName</a></span>()</code>
<div class="block">should have both name and surname</div>
</td>
</tr>
<tr id="i14" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#isMine--">isMine</a></span>()</code>
<div class="block">check this user is a current sign in user or not</div>
</td>
</tr>
<tr id="i15" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/kamontat/model/github/User.html#toString--">toString</a></span>()</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="githubUser">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>githubUser</h4>
<pre>public org.kohsuke.github.GHUser githubUser</pre>
</li>
</ul>
<a name="githubMy">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>githubMy</h4>
<pre>public org.kohsuke.github.GHMyself githubMy</pre>
</li>
</ul>
<a name="loginName">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>loginName</h4>
<pre>public final java.lang.String loginName</pre>
</li>
</ul>
<a name="name">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>name</h4>
<pre>public java.lang.String name</pre>
</li>
</ul>
<a name="surname">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>surname</h4>
<pre>public java.lang.String surname</pre>
</li>
</ul>
<a name="location">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>location</h4>
<pre>public final java.lang.String location</pre>
</li>
</ul>
<a name="api_url">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>api_url</h4>
<pre>public final java.net.URL api_url</pre>
</li>
</ul>
<a name="url">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>url</h4>
<pre>public final java.net.URL url</pre>
</li>
</ul>
<a name="image_url">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>image_url</h4>
<pre>public final java.net.URL image_url</pre>
</li>
</ul>
<a name="createAt">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>createAt</h4>
<pre>public final java.util.Date createAt</pre>
</li>
</ul>
<a name="updateAt">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>updateAt</h4>
<pre>public final java.util.Date updateAt</pre>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="User-org.kohsuke.github.GHUser-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>User</h4>
<pre>public User(org.kohsuke.github.GHUser user)
throws <a href="../../../../com/kamontat/exception/RequestException.html" title="class in com.kamontat.exception">RequestException</a></pre>
<dl>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../../com/kamontat/exception/RequestException.html" title="class in com.kamontat.exception">RequestException</a></code></dd>
</dl>
</li>
</ul>
<a name="User-org.kohsuke.github.GHMyself-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>User</h4>
<pre>public User(org.kohsuke.github.GHMyself my)
throws <a href="../../../../com/kamontat/exception/RequestException.html" title="class in com.kamontat.exception">RequestException</a></pre>
<dl>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../../com/kamontat/exception/RequestException.html" title="class in com.kamontat.exception">RequestException</a></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="isFullName--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isFullName</h4>
<pre>public boolean isFullName()</pre>
<div class="block">should have both name and surname</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true if full name</dd>
</dl>
</li>
</ul>
<a name="isMine--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isMine</h4>
<pre>public boolean isMine()</pre>
<div class="block">check this user is a current sign in user or not</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true if yes, otherwise return false</dd>
</dl>
</li>
</ul>
<a name="toString--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>toString</h4>
<pre>public final java.lang.String toString()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>toString</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="equals-java.lang.Object-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equals</h4>
<pre>public boolean equals(java.lang.Object obj)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>equals</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="getID--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getID</h4>
<pre>public java.lang.String getID()</pre>
</li>
</ul>
<a name="getImage--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getImage</h4>
<pre>public javax.swing.ImageIcon getImage()</pre>
</li>
</ul>
<a name="getCompany--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getCompany</h4>
<pre>public java.lang.String getCompany()</pre>
</li>
</ul>
<a name="getEmail--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getEmail</h4>
<pre>public java.lang.String getEmail()</pre>
</li>
</ul>
<a name="getImage-int-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getImage</h4>
<pre>public javax.swing.ImageIcon getImage(int w,
int h)</pre>
</li>
</ul>
<a name="getRepository-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getRepository</h4>
<pre>public org.kohsuke.github.GHRepository getRepository(java.lang.String name)
throws <a href="../../../../com/kamontat/exception/RequestException.html" title="class in com.kamontat.exception">RequestException</a></pre>
<dl>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../../com/kamontat/exception/RequestException.html" title="class in com.kamontat.exception">RequestException</a></code></dd>
</dl>
</li>
</ul>
<a name="getRepositories--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getRepositories</h4>
<pre>public java.util.Map<java.lang.String,org.kohsuke.github.GHRepository> getRepositories()
throws <a href="../../../../com/kamontat/exception/RequestException.html" title="class in com.kamontat.exception">RequestException</a></pre>
<dl>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../../com/kamontat/exception/RequestException.html" title="class in com.kamontat.exception">RequestException</a></code></dd>
</dl>
</li>
</ul>
<a name="getRawData--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getRawData</h4>
<pre>public <a href="../../../../com/kamontat/model/github/User.html" title="class in com.kamontat.model.github">User</a> getRawData()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../com/kamontat/model/github/TableInformation.html#getRawData--">getRawData</a></code> in interface <code><a href="../../../../com/kamontat/model/github/TableInformation.html" title="interface in com.kamontat.model.github">TableInformation</a><<a href="../../../../com/kamontat/model/github/User.html" title="class in com.kamontat.model.github">User</a>></code></dd>
</dl>
</li>
</ul>
<a name="getName--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getName</h4>
<pre>public java.lang.String getName()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../com/kamontat/model/github/TableInformation.html#getName--">getName</a></code> in interface <code><a href="../../../../com/kamontat/model/github/TableInformation.html" title="interface in com.kamontat.model.github">TableInformation</a><<a href="../../../../com/kamontat/model/github/User.html" title="class in com.kamontat.model.github">User</a>></code></dd>
</dl>
</li>
</ul>
<a name="getStringInformationVector--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getStringInformationVector</h4>
<pre>public java.util.Vector<java.lang.Object> getStringInformationVector()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../com/kamontat/model/github/TableInformation.html#getStringInformationVector--">getStringInformationVector</a></code> in interface <code><a href="../../../../com/kamontat/model/github/TableInformation.html" title="interface in com.kamontat.model.github">TableInformation</a><<a href="../../../../com/kamontat/model/github/User.html" title="class in com.kamontat.model.github">User</a>></code></dd>
</dl>
</li>
</ul>
<a name="getStringTitleVector--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getStringTitleVector</h4>
<pre>public java.util.Vector<java.lang.String> getStringTitleVector()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../com/kamontat/model/github/TableInformation.html#getStringTitleVector--">getStringTitleVector</a></code> in interface <code><a href="../../../../com/kamontat/model/github/TableInformation.html" title="interface in com.kamontat.model.github">TableInformation</a><<a href="../../../../com/kamontat/model/github/User.html" title="class in com.kamontat.model.github">User</a>></code></dd>
</dl>
</li>
</ul>
<a name="getStringTitleVectorStatic--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getStringTitleVectorStatic</h4>
<pre>public static java.util.Vector<java.lang.String> getStringTitleVectorStatic()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/kamontat/model/github/TableInformation.html" title="interface in com.kamontat.model.github"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/kamontat/model/github/User.html" target="_top">Frames</a></li>
<li><a href="User.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
kamontat/Github-Request
|
docs/com/kamontat/model/github/User.html
|
HTML
|
mit
| 27,096
|
# ursa
统计模块
|
husu/ursa
|
README.md
|
Markdown
|
mit
| 20
|
class ApplicationController < ActionController::Base
before_filter :authenticate_auth!
before_action :configure_permitted_parameters, if: :devise_controller?
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :set_locale
def set_locale
I18n.locale = request.env['HTTP_ACCEPT_LANGUAGE'].split(",").first
rescue I18n::InvalidLocale
I18n.locale = "ja"
end
protected
def current_user
current_auth
end
def logged_in?
auth_signed_in?
end
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :nickname
devise_parameter_sanitizer.for(:account_update) << :nickname
end
end
|
qtamaki/three-d-mind
|
app/controllers/application_controller.rb
|
Ruby
|
mit
| 761
|
#include "xGenType_List.h"
xGenType* xGenType_List::Clone()
{
return new xGenType_List(*this);
}
std::string xGenType_List::GetName()
{
return "list";
}
std::string xGenType_List::GetUseName()
{
return "std::list<" + GetValueTypeName() + ">";
}
std::string xGenType_List::GetInclude()
{
return "#include <list>";
}
|
xgm-skywave/sw
|
xgen/xgen/xGenType_List.cpp
|
C++
|
mit
| 349
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
typedef std::vector<ListNode*> NodeVec;
typedef NodeVec::iterator Iter;
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.empty()) return NULL;
while (1 != lists.size()) {
ListNode* last = lists.back();
lists.pop_back();
merge2Lists(lists.back(), last);
}
return lists.front();
}
void merge2Lists(ListNode*& l1, ListNode* l2) {
if (!l2) return;
if (!l1) {
l1 = l2;
return;
}
if (l1->val > l2->val) {
ListNode* temp = l2->next;
l2->next = l1;
l1 = l2;
l2 = temp;
}
ListNode* localL1 = l1;
// localL1->val is always small than l2->val
while (l2) {
ListNode* temp = l2->next;
insertToList(localL1, l2);
if (temp == l2->next) {
return;
}
localL1 = l2;
l2 = temp;
}
}
inline void insertToList(ListNode* list, ListNode* node) {
if (!list) {
list = node;
return;
}
while (1) {
if (!list->next) {
list->next = node;
return;
}
if (list->next->val > node->val) {
ListNode* temp = list->next;
list->next = node;
node->next = temp;
return;
}
list = list->next;
}
}
};
|
orphie/lc
|
023. Merge k Sorted Lists.cc
|
C++
|
mit
| 1,750
|
body {
background-color: #e4f1fd;
padding: 100px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00B7FF;
}
h1 {
text-align:center;
font-size: 60px;
color: #0E2F44;
}
p {
text-align:center;
font-size: 20px;
color: #66CCCC;
}
input {
text-align:center;
border-right:2px solid black;
border-bottom:2px solid black;
background-color: #FFFFE0;
}
div {
text-align:center;
border-right:3px solid black;
border-bottom:3px solid black;
background-color: #0E2F44;
}
|
niksolaz/GeoJS
|
geojs/public/stylesheets/style.css
|
CSS
|
mit
| 512
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Altairis.Fakturoid.Client {
/// <summary>
/// Proxy class for working with todo tasks.
/// </summary>
public class FakturoidTodosProxy : FakturoidEntityProxy {
internal FakturoidTodosProxy(FakturoidContext context) : base(context) { }
/// <summary>
/// Gets list of all current todos.
/// </summary>
/// <param name="since">The date since when todos are to be selected.</param>
/// <returns>List of <see cref="JsonTodo"/> instances.</returns>
/// <remarks>The result may contain duplicate entities, if they are modified between requests for pages. In current version of API, there is no way to solve rhis.</remarks>
public IEnumerable<JsonTodo> Select(DateTime? since = null) => base.GetAllPagedEntities<JsonTodo>("todos.json", new { since });
/// <summary>
/// Gets asynchronously list of all current todos.
/// </summary>
/// <param name="since">The date since when todos are to be selected.</param>
/// <returns>List of <see cref="JsonTodo"/> instances.</returns>
/// <remarks>The result may contain duplicate entities, if they are modified between requests for pages. In current version of API, there is no way to solve rhis.</remarks>
public async Task<IEnumerable<JsonTodo>> SelectAsync(DateTime? since = null) => await base.GetAllPagedEntitiesAsync<JsonTodo>("todos.json", new { since });
/// <summary>
/// Gets paged list of current todos
/// </summary>
/// <param name="page">The page number.</param>
/// <param name="since">The date since when todos are to be selected.</param>
/// <returns>
/// List of <see cref="JsonTodo" /> instances.
/// </returns>
/// <exception cref="System.ArgumentOutOfRangeException">page;Page must be greater than zero.</exception>
public IEnumerable<JsonTodo> Select(int page, DateTime? since = null) {
return page < 1
? throw new ArgumentOutOfRangeException(nameof(page), "Page must be greater than zero.")
: base.GetPagedEntities<JsonTodo>("todos.json", page, new { since });
}
/// <summary>
/// Gets asynchronously paged list of current todos
/// </summary>
/// <param name="page">The page number.</param>
/// <param name="since">The date since when todos are to be selected.</param>
/// <returns>
/// List of <see cref="JsonTodo" /> instances.
/// </returns>
/// <exception cref="System.ArgumentOutOfRangeException">page;Page must be greater than zero.</exception>
public async Task<IEnumerable<JsonTodo>> SelectAsync(int page, DateTime? since = null) {
return page < 1
? throw new ArgumentOutOfRangeException(nameof(page), "Page must be greater than zero.")
: await base.GetPagedEntitiesAsync<JsonTodo>("todos.json", page, new { since });
}
}
}
|
ridercz/Fakturoid-API
|
Altairis.Fakturoid.Client/FakturoidTodosProxy.cs
|
C#
|
mit
| 3,095
|
/*
multiboot.h : Stuff for multiboot.
(C)2012-2013 Marisa Kirisame, UnSX Team.
Part of AliceOS, the Alice Operating System.
Released under the MIT License.
*/
/* defines */
#define MULTIBOOT_MAGIC 0x1BADB002
#define MULTIBOOT_EAX_MAGIC 0x2BADB002
#define MULTIBOOT_FLAG_MEM 0x001
#define MULTIBOOT_FLAG_DEVICE 0x002
#define MULTIBOOT_FLAG_CMDLINE 0x004
#define MULTIBOOT_FLAG_MODS 0x008
#define MULTIBOOT_FLAG_AOUT 0x010
#define MULTIBOOT_FLAG_ELF 0x020
#define MULTIBOOT_FLAG_MMAP 0x040
#define MULTIBOOT_FLAG_CONFIG 0x080
#define MULTIBOOT_FLAG_LOADER 0x100
#define MULTIBOOT_FLAG_APM 0x200
#define MULTIBOOT_FLAG_VBE 0x400
/* structures */
typedef struct
{
uint32_t size;
uint32_t addr_l;
uint32_t addr_h;
uint32_t len_l;
uint32_t len_h;
uint32_t type;
} mmap_entry_t;
typedef struct
{
uint32_t mod_start;
uint32_t mod_end;
uint32_t cmdline;
uint32_t pad;
} mbootmod_t;
typedef struct
{
uint32_t tabsize;
uint32_t strsize;
uint32_t addr;
uint32_t reserved;
} aout_syms_t;
typedef struct
{
uint32_t num;
uint32_t size;
uint32_t addr;
uint32_t shndx;
} elf_hdr_t;
typedef struct
{
uint32_t size;
uint8_t drive_number;
uint8_t drive_mode;
uint16_t drive_cylinders;
uint8_t drive_heads;
uint8_t drive_sectors;
uint8_t *drive_ports;
} drive_t;
typedef struct
{
uint16_t version;
uint16_t cseg;
uint32_t offset;
uint16_t cseg_16;
uint16_t dseg;
uint16_t flags;
uint16_t cseg_len;
uint16_t cseg_16_len;
uint16_t dseg_len;
} apm_table_t;
typedef struct
{
uint16_t attributes;
uint8_t winA,winB;
uint16_t granularity;
uint16_t winsize;
uint16_t segmentA, segmentB;
uint32_t realFctPtr;
uint16_t pitch;
uint16_t Xres, Yres;
uint8_t Wchar, Ychar, planes, bpp, banks;
uint8_t memory_model, bank_size, image_pages;
uint8_t reserved0;
uint8_t red_mask, red_position;
uint8_t green_mask, green_position;
uint8_t blue_mask, blue_position;
uint8_t rsv_mask, rsv_position;
uint8_t directcolor_attributes;
uint32_t physbase;
uint32_t reserved1;
uint16_t reserved2;
} vbe_info_t;
typedef struct
{
uint32_t flags;
uint32_t mem_lower;
uint32_t mem_upper;
uint32_t boot_device;
uint32_t cmdline;
uint32_t mods_count;
uint32_t mods_addr;
union
{
aout_syms_t aout;
elf_hdr_t elf;
} syms;
uint32_t mmap_length;
uint32_t mmap_addr;
uint32_t drives_length;
uint32_t drives_addr;
uint32_t config_table;
uint32_t boot_loader_name;
uint32_t apm_table;
uint32_t vbe_control_info;
uint32_t vbe_mode_info;
uint32_t vbe_mode;
uint32_t vbe_interface_seg;
uint32_t vbe_interface_off;
uint32_t vbe_interface_len;
} multiboot_t;
|
OrdinaryMagician/aliceos-kernel
|
kernel/include/sys/multiboot.h
|
C
|
mit
| 2,615
|
var framework = require('framework');
exports.info = function() {
return 'fooPlugin (in Framework v' + framework.version + ')';
};
|
jaredhanson/node-parent-require
|
test/projects/app/node_modules/foo-plugin/index.js
|
JavaScript
|
mit
| 134
|
$('document').ready(function() {
initTooltips();
});
$(window).on('action:posts.loaded action:topic.loaded action:posts.edited', function() {
initTooltips();
});
$(window).on('action:ajaxify.contentLoaded', function(){
$('.item-tooltip').hide();
});
function initTooltips() {
$('.vanilla-tooltip').each(function(tooltip){
var name = $(this).attr('data-name');
var $this = $(this);
$.getJSON('http://api.theorycraft.fi/v1/item', {name: name}, function(response){
$this.text('['+response.data[0].name+']').attr('rel', 'item='+response.data[0].entry).addClass('q'+response.data[0].quality);
ajaxify('http://db.vanillagaming.org/ajax.php?item='+response.data[0].entry+'&power');
});
$this.mouseenter(function(){
showTooltip($this.data('id'), $this.data('tooltip'));
}).mouseleave(function(){
$('.item-tooltip').hide();
});
});
$(document).mousemove(function(event) {
$('.item-tooltip').css({
left: event.pageX+10,
top: event.pageY+10
});
});
}
function showTooltip(id, data) {
if(!$('.item-tooltip#'+id).length) {
var iconUrl = typeof data.icon == 'undefined' ? '' : 'http://db.vanillagaming.org/images/icons/medium/'+data.icon.toLowerCase()+'.jpg';
var $tooltip = $('<div id="'+id+'" class="item-tooltip"><p style="background-image: url('+iconUrl+');"><span></span></p><table><tr><td>'+data.tooltip_enus+'</td><th style="background-position: 100% 0%;"></th></tr><tr><th style="background-position: 0% 100%;"></th><th style="background-position: 100% 100%;"></th></tr></div>');
$tooltip.css('visibility', 'visible').appendTo('body').show();
} else $('.item-tooltip#'+id).show();
}
function ajaxify(url) {
$('<script type="text/javascript" src="'+url+'"></script>').appendTo('body');
}
$WowheadPower = {
registerItem: function(a,b,item) {
$('a.vanilla-tooltip[rel="item='+a+'"]').data('tooltip', item).data('id', a);
}
}
|
liekki/nodebb-plugin-vanillatooltips
|
static/vanillatooltips.js
|
JavaScript
|
mit
| 1,883
|
#! /usr/bin/env python
"""
Module with the MCMC (``emcee``) sampling for NEGFC parameter estimation.
"""
__author__ = 'O. Wertz, Carlos Alberto Gomez Gonzalez, V. Christiaens'
__all__ = ['mcmc_negfc_sampling',
'chain_zero_truncated',
'show_corner_plot',
'show_walk_plot',
'confidence']
import numpy as np
import os
import emcee
from multiprocessing import cpu_count
import inspect
import datetime
import corner
from matplotlib import pyplot as plt
from matplotlib.ticker import MaxNLocator
import pickle
from scipy.stats import norm
from ..fm import cube_inject_companions
from ..config import time_ini, timing
from ..config.utils_conf import sep
from ..psfsub import pca_annulus
from .negfc_fmerit import get_values_optimize, get_mu_and_sigma
from .utils_mcmc import gelman_rubin, autocorr_test
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
from ..fits import write_fits
def lnprior(param, bounds):
""" Define the prior log-function.
Parameters
----------
param: tuple
The model parameters.
bounds: list
The bounds for each model parameter.
Ex: bounds = [(10,20),(0,360),(0,5000)]
Returns
-------
out: float.
0 if all the model parameters satisfy the prior conditions defined here.
-np.inf if at least one model parameters is out of bounds.
"""
try:
r, theta, flux = param
except TypeError:
print('param must be a tuple, {} given'.format(type(param)))
try:
r_bounds, theta_bounds, flux_bounds = bounds
except TypeError:
print('bounds must be a list of tuple, {} given'.format(type(bounds)))
if r_bounds[0] <= r <= r_bounds[1] and \
theta_bounds[0] <= theta <= theta_bounds[1] and \
flux_bounds[0] <= flux <= flux_bounds[1]:
return 0.0
else:
return -np.inf
def lnlike(param, cube, angs, plsc, psf_norm, fwhm, annulus_width, ncomp,
aperture_radius, initial_state, cube_ref=None, svd_mode='lapack',
scaling='temp-mean', algo=pca_annulus, delta_rot=1, fmerit='sum',
imlib='vip-fft', interpolation='lanczos4', collapse='median',
algo_options={}, weights=None, transmission=None, mu_sigma=True,
sigma='spe+pho', debug=False):
""" Define the likelihood log-function.
Parameters
----------
param: tuple
The model parameters, typically (r, theta, flux).
cube: numpy.array
The cube of fits images expressed as a numpy.array.
angs: numpy.array
The parallactic angle fits image expressed as a numpy.array.
plsc: float
The platescale, in arcsec per pixel.
psf_norm: numpy.array
The scaled psf expressed as a numpy.array.
annulus_width: float
The width of the annulus of interest in pixels.
ncomp: int or None
The number of principal components for PCA-based algorithms.
fwhm : float
The FHWM in pixels.
aperture_radius: float
The radius of the circular aperture in terms of the FWHM.
initial_state: numpy.array
The initial guess for the position and the flux of the planet.
cube_ref: numpy ndarray, 3d, optional
Reference library cube. For Reference Star Differential Imaging.
svd_mode : {'lapack', 'randsvd', 'eigen', 'arpack'}, str optional
Switch for different ways of computing the SVD and selected PCs.
scaling : {'temp-mean', 'temp-standard'} or None, optional
With None, no scaling is performed on the input data before SVD. With
"temp-mean" then temporal px-wise mean subtraction is done and with
"temp-standard" temporal mean centering plus scaling to unit variance
is done.
algo: vip function, optional {pca_annulus, pca_annular}
Post-processing algorithm used.
delta_rot: float, optional
If algo is set to pca_annular, delta_rot is the angular threshold used
to select frames in the PCA library (see description of pca_annular).
fmerit : {'sum', 'stddev'}, string optional
Chooses the figure of merit to be used. stddev works better for close in
companions sitting on top of speckle noise.
imlib : str, optional
See the documentation of the ``vip_hci.preproc.frame_shift`` function.
interpolation : str, optional
See the documentation of the ``vip_hci.preproc.frame_shift`` function.
collapse : {'median', 'mean', 'sum', 'trimmean', None}, str or None, optional
Sets the way of collapsing the frames for producing a final image. If
None then the cube of residuals is used when measuring the function of
merit (instead of a single final frame).
algo_options: dict, opt
Dictionary with additional parameters related to the algorithm
(e.g. tol, min_frames_lib, max_frames_lib). If 'algo' is not a vip
routine, this dict should contain all necessary arguments apart from
the cube and derotation angles. Note: arguments such as ncomp, svd_mode,
scaling, imlib, interpolation or collapse can also be included in this
dict (the latter are also kept as function arguments for consistency
with older versions of vip).
weights : 1d array, optional
If provided, the negative fake companion fluxes will be scaled according
to these weights before injection in the cube. Can reflect changes in
the observing conditions throughout the sequence.
transmission: numpy array, optional
Radial transmission of the coronagraph, if any. Array with 2 columns.
First column is the radial separation in pixels. Second column is the
off-axis transmission (between 0 and 1) at the radial separation given
in column 1.
mu_sigma: tuple of 2 floats or None, opt
If set to None: not used, and falls back to original version of the
algorithm, using fmerit. Otherwise, should be a tuple of 2 elements,
containing the mean and standard deviation of pixel intensities in an
annulus centered on the location of the companion, excluding the area
directly adjacent to the companion.
sigma: str, opt
Sets the type of noise to be included as sigma^2 in the log-probability
expression. Choice between 'pho' for photon (Poisson) noise, 'spe' for
residual (mostly whitened) speckle noise, or 'spe+pho' for both.
debug: boolean
If True, the cube is returned along with the likelihood log-function.
Returns
-------
out: float
The log of the likelihood.
"""
## set imlib for rotation and shift
if imlib == 'opencv':
imlib_rot = imlib
imlib_sh = imlib
elif imlib == 'skimage' or imlib == 'ndimage-interp':
imlib_rot = 'skimage'
imlib_sh = 'ndimage-interp'
elif imlib == 'vip-fft' or imlib == 'ndimage-fourier':
imlib_rot = 'vip-fft'
imlib_sh = 'ndimage-fourier'
else:
raise TypeError("Interpolation not recognized.")
# Create the cube with the negative fake companion injected
if weights is None:
flux = -param[2]
norm_weights=weights
else:
flux = -param[2]*weights
norm_weights = weights/np.sum(weights)
cube_negfc = cube_inject_companions(cube, psf_norm, angs, flevel=flux,
plsc=plsc, rad_dists=[param[0]],
n_branches=1, theta=param[1],
imlib=imlib_sh,
interpolation=interpolation,
transmission=transmission,
verbose=False)
# Perform PCA and extract the zone of interest
values = get_values_optimize(cube_negfc, angs, ncomp, annulus_width,
aperture_radius, fwhm, initial_state[0],
initial_state[1], cube_ref=cube_ref,
svd_mode=svd_mode, scaling=scaling,
algo=algo, delta_rot=delta_rot, imlib=imlib_rot,
interpolation=interpolation, collapse=collapse,
algo_options=algo_options,
weights=norm_weights)
if isinstance(mu_sigma, tuple):
mu = mu_sigma[0]
sigma2 = mu_sigma[1]**2
num = np.power(mu-values,2)
denom = 0
if 'spe' in sigma:
denom += sigma2
if 'pho' in sigma:
denom += np.abs(values-mu)
lnlikelihood = -0.5* np.sum(num/denom)
else:
mu = mu_sigma
# old version - delete?
if fmerit == 'sum':
lnlikelihood = -0.5 * np.sum(np.abs(values-mu))
elif fmerit == 'stddev':
values = values[values != 0]
lnlikelihood = -np.std(values,ddof=1)*values.size
else:
raise RuntimeError('fmerit choice not recognized.')
if debug:
return lnlikelihood, cube_negfc
else:
return lnlikelihood
def lnprob(param,bounds, cube, angs, plsc, psf_norm, fwhm,
annulus_width, ncomp, aperture_radius, initial_state, cube_ref=None,
svd_mode='lapack', scaling='temp-mean', algo=pca_annulus,
delta_rot=1, fmerit='sum', imlib='vip-fft', interpolation='lanczos4',
collapse='median', algo_options={}, weights=None, transmission=None,
mu_sigma=True, sigma='spe+pho', display=False):
""" Define the probability log-function as the sum between the prior and
likelihood log-funtions.
Parameters
----------
param: tuple
The model parameters.
bounds: list
The bounds for each model parameter.
Ex: bounds = [(10,20),(0,360),(0,5000)]
cube: numpy.array
The cube of fits images expressed as a numpy.array.
angs: numpy.array
The parallactic angle fits image expressed as a numpy.array.
plsc: float
The platescale, in arcsec per pixel.
psf_norm: numpy.array
The scaled psf expressed as a numpy.array.
fwhm : float
The FHWM in pixels.
annulus_width: float
The width in pixel of the annulus on wich the PCA is performed.
ncomp: int or None
The number of principal components for PCA-based algorithms.
aperture_radius: float
The radius of the circular aperture in FWHM.
initial_state: numpy.array
The initial guess for the position and the flux of the planet.
cube_ref : numpy ndarray, 3d, optional
Reference library cube. For Reference Star Differential Imaging.
svd_mode : {'lapack', 'randsvd', 'eigen', 'arpack'}, str optional
Switch for different ways of computing the SVD and selected PCs.
scaling : {'temp-mean', 'temp-standard'} or None, optional
With None, no scaling is performed on the input data before SVD. With
"temp-mean" then temporal px-wise mean subtraction is done and with
"temp-standard" temporal mean centering plus scaling to unit variance
is done.
fmerit : {'sum', 'stddev'}, string optional
Chooses the figure of merit to be used. stddev works better for close in
companions sitting on top of speckle noise.
imlib : str, optional
See the documentation of the ``vip_hci.preproc.frame_rotate`` function.
interpolation : str, optional
See the documentation of the ``vip_hci.preproc.frame_rotate`` function.
algo_options, : dict, opt
Dictionary with additional parameters related to the algorithm
(e.g. tol, min_frames_lib, max_frames_lib). If 'algo' is not a vip
routine, this dict should contain all necessary arguments apart from
the cube and derotation angles. Note: arguments such as ncomp, svd_mode,
scaling, imlib, interpolation or collapse can also be included in this
dict (the latter are also kept as function arguments for consistency
with older versions of vip).
collapse : {'median', 'mean', 'sum', 'trimmean', None}, str or None, optional
Sets the way of collapsing the frames for producing a final image. If
None then the cube of residuals is used when measuring the function of
merit (instead of a single final frame).
weights : 1d array, optional
If provided, the negative fake companion fluxes will be scaled according
to these weights before injection in the cube. Can reflect changes in
the observing conditions throughout the sequence.
transmission: numpy array, optional
Radial transmission of the coronagraph, if any. Array with 2 columns.
First column is the radial separation in pixels. Second column is the
off-axis transmission (between 0 and 1) at the radial separation given
in column 1.
mu_sigma: tuple of 2 floats or None, opt
If set to None: not used, and falls back to original version of the
algorithm, using fmerit. Otherwise, should be a tuple of 2 elements,
containing the mean and standard deviation of pixel intensities in an
annulus centered on the location of the companion, excluding the area
directly adjacent to the companion.
sigma: str, opt
Sets the type of noise to be included as sigma^2 in the log-probability
expression. Choice between 'pho' for photon (Poisson) noise, 'spe' for
residual (mostly whitened) speckle noise, or 'spe+pho' for both.
display: boolean
If True, the cube is displayed with ds9.
Returns
-------
out: float
The probability log-function.
"""
if initial_state is None:
initial_state = param
lp = lnprior(param, bounds)
if np.isinf(lp):
return -np.inf
return lp + lnlike(param, cube, angs, plsc, psf_norm, fwhm, annulus_width,
ncomp, aperture_radius, initial_state, cube_ref,
svd_mode, scaling, algo, delta_rot, fmerit, imlib,
interpolation, collapse, algo_options, weights,
transmission, mu_sigma, sigma)
def mcmc_negfc_sampling(cube, angs, psfn, ncomp, plsc, initial_state, fwhm=4,
annulus_width=8, aperture_radius=1, cube_ref=None,
svd_mode='lapack', scaling=None, algo=pca_annulus,
delta_rot=1, fmerit='sum', imlib='vip-fft',
interpolation='lanczos4', collapse='median',
algo_options={}, wedge=None, weights=None,
transmission=None, mu_sigma=True, sigma='spe+pho',
nwalkers=100, bounds=None, a=2.0, burnin=0.3,
rhat_threshold=1.01, rhat_count_threshold=1,
niteration_min=10, niteration_limit=10000,
niteration_supp=0, check_maxgap=20, conv_test='ac',
ac_c=50, ac_count_thr=3, nproc=1, output_dir='results/',
output_file=None, display=False, verbosity=0,
save=False):
r""" Runs an affine invariant mcmc sampling algorithm in order to determine
the position and the flux of the planet using the 'Negative Fake Companion'
technique. The result of this procedure is a chain with the samples from the
posterior distributions of each of the 3 parameters.
This technique can be summarized as follows:
1) We inject a negative fake companion (one candidate) at a given position
and characterized by a given flux, both close to the expected values.
2) We run PCA on an full annulus which pass through the initial guess,
regardless of the position of the candidate.
3) We extract the intensity values of all the pixels contained in a
circular aperture centered on the initial guess.
4) We calculate a function of merit :math:`\chi^2` (see below).
The steps 1) to 4) are then looped. At each iteration, the candidate model
parameters are defined by the emcee Affine Invariant algorithm.
There are different possibilities for the figure of merit (step 4):
- mu_sigma=None; fmerit='sum' (as in Wertz et al. 2017):
.. math:: \chi^2 = \sum(\|I_j\|)
- mu_sigma=None; fmerit='stddev' (likely more appropriate when speckle
noise still significant):
.. math:: \chi^2 = N \sigma_{I_j}(values,ddof=1)*values.size
- mu_sigma=True or a tuple (as in Christiaens et al. 2021, new default):
.. math:: \chi^2 = \sum\frac{(I_j- mu)^2}{\sigma^2}
where :math:`j \in {1,...,N}` with N the total number of pixels
contained in the circular aperture, :math:`\sigma_{I_j}` is the standard
deviation of :math:`I_j` values, and :math:`\mu` is the mean pixel
intensity in a truncated annulus at the radius of the companion candidate
(i.e. excluding the cc region).
See description of `mu_sigma` and `sigma` for more details on
:math:`\sigma\`.
Parameters
----------
cube: numpy.array
ADI fits cube.
angs: numpy.array
The parallactic angle vector.
psfn: numpy 2D or 3D array
Normalised PSF template used for negative fake companion injection.
The PSF must be centered and the flux in a 1xFWHM aperture must equal 1
(use ``vip_hci.metrics.normalize_psf``).
If a 3D array is provided, it must match the number of frames of ADI
cube. This can be useful if the cube was unsaturated and conditions
were variable.
ncomp: int or None
The number of principal components for PCA-based algorithms.
plsc: float
The platescale, in arcsec per pixel.
annulus_width: float, optional
The width in pixels of the annulus on which the PCA is performed.
aperture_radius: float, optional
The radius in FWHM of the circular aperture.
nwalkers: int optional
The number of Goodman & Weare 'walkers'.
initial_state: numpy.array
The first guess for the position and flux of the planet, respectively.
Each walker will start in a small ball around this preferred position.
cube_ref : numpy ndarray, 3d, optional
Reference library cube. For Reference Star Differential Imaging.
svd_mode : {'lapack', 'randsvd', 'eigen', 'arpack'}, str optional
Switch for different ways of computing the SVD and selected PCs.
'randsvd' is not recommended for the negative fake companion technique.
algo : python routine
Post-processing algorithm used to model and subtract the star. First
2 arguments must be input cube and derotation angles. Must return a
post-processed 2d frame.
scaling : {'temp-mean', 'temp-standard'} or None, optional
With None, no scaling is performed on the input data before SVD. With
"temp-mean" then temporal px-wise mean subtraction is done and with
"temp-standard" temporal mean centering plus scaling to unit variance
is done.
fmerit : {'sum', 'stddev'}, string optional
Chooses the figure of merit to be used. stddev works better for
close-in companions sitting on top of speckle noise.
imlib : str, optional
Imlib used for both image rotation and sub-px shift:
- "opencv": will use it for both;
- "skimage" or "ndimage-interp" will use scikit-image and \
scipy.ndimage for rotation and shift resp.;
- "ndimage-fourier" or "vip-fft" will use Fourier transform based \
methods for both.
interpolation : str, optional
Interpolation order. See the documentation of the
``vip_hci.preproc.frame_rotate`` function. Note that the interpolation
options are identical for rotation and shift within each of the 3 imlib
cases above.
collapse : {'median', 'mean', 'sum', 'trimmean', None}, str or None, optional
Sets the way of collapsing the frames for producing a final image. If
None then the cube of residuals is used when measuring the function of
merit (instead of a single final frame).
algo_options: dict, opt
Dictionary with additional parameters related to the algorithm
(e.g. tol, min_frames_lib, max_frames_lib). If 'algo' is not a vip
routine, this dict should contain all necessary arguments apart from
the cube and derotation angles. Note: arguments such as ncomp, svd_mode,
scaling, imlib, interpolation or collapse can also be included in this
dict (the latter are also kept as function arguments for consistency
with older versions of vip).
wedge: tuple, opt
Range in theta where the mean and standard deviation are computed in an
annulus defined in the PCA image. If None, it will be calculated
automatically based on initial guess and derotation angles to avoid.
If some disc signal is present elsewhere in the annulus, it is
recommended to provide wedge manually. The provided range should be
continuous and >0. E.g. provide (270, 370) to consider a PA range
between [-90,+10].
weights : 1d array, optional
If provided, the negative fake companion fluxes will be scaled according
to these weights before injection in the cube. Can reflect changes in
the observing conditions throughout the sequence.
transmission: numpy array, optional
Radial transmission of the coronagraph, if any. Array with 2 columns.
First column is the radial separation in pixels. Second column is the
off-axis transmission (between 0 and 1) at the radial separation given
in column 1.
mu_sigma: tuple of 2 floats or bool, opt
If set to None: not used, and falls back to original version of the
algorithm, using fmerit (Wertz et al. 2017).
If a tuple of 2 elements: should be the mean and standard deviation of
pixel intensities in an annulus centered on the location of the
companion candidate, excluding the area directly adjacent to the CC.
If set to anything else, but None/False/tuple: will compute said mean
and standard deviation automatically.
These values will then be used in the log-probability of the MCMC.
sigma: str, opt
Sets the type of noise to be included as sigma^2 in the log-probability
expression. Choice between 'pho' for photon (Poisson) noise, 'spe' for
residual (mostly whitened) speckle noise, or 'spe+pho' for both.
bounds: numpy.array or list, default=None, optional
The prior knowledge on the model parameters. If None, large bounds will
be automatically estimated from the initial state.
a: float, default=2.0
The proposal scale parameter. See notes.
burnin: float, default=0.3
The fraction of a walker chain which is discarded. NOTE: only used for
Gelman-Rubin convergence test - the chains are returned full.
rhat_threshold: float, default=0.01
The Gelman-Rubin threshold used for the test for nonconvergence.
rhat_count_threshold: int, optional
The Gelman-Rubin test must be satisfied 'rhat_count_threshold' times in
a row before claiming that the chain has converged.
conv_test: str, optional {'gb','ac'}
Method to check for convergence:
- 'gb' for gelman-rubin test
(http://digitalassets.lib.berkeley.edu/sdtr/ucb/text/305.pdf)
- 'ac' for autocorrelation analysis
(https://emcee.readthedocs.io/en/stable/tutorials/autocorr/)
ac_c: float, optional
If the convergence test is made using the auto-correlation, this is the
value of C such that tau/N < 1/C is the condition required for tau to be
considered a reliable auto-correlation time estimate (for N number of
samples). Recommended: C>50.
More details here:
https://emcee.readthedocs.io/en/stable/tutorials/autocorr/
ac_c_thr: int, optional
The auto-correlation test must be satisfied ac_c_thr times in a row
before claiming that the chain has converged.
niteration_min: int, optional
Steps per walker lower bound. The simulation will run at least this
number of steps per walker.
niteration_limit: int, optional
Steps per walker upper bound. If the simulation runs up to
'niteration_limit' steps without having reached the convergence
criterion, the run is stopped.
niteration_supp: int, optional
Number of iterations to run after having "reached the convergence".
check_maxgap: int, optional
Maximum number of steps per walker between two Gelman-Rubin test.
nproc: int, optional
The number of processes to use for parallelization.
output_dir: str, optional
The name of the output directory which contains the output files in the
case ``save`` is True.
output_file: str, optional
The name of the output file which contains the MCMC results in the case
``save`` is True.
display: bool, optional
If True, the walk plot is displayed at each evaluation of the Gelman-
Rubin test.
verbosity: 0, 1, 2 or 3, optional
Verbosity level. 0 for no output and 3 for full information.
(only difference between 2 and 3 is that 3 also writes intermediate
pickles containing the state of the chain at convergence tests; these
can end up taking a lot of space).
save: bool, optional
If True, the MCMC results are pickled.
Returns
-------
out : numpy.array
The MCMC chain.
Notes
-----
The parameter ``a`` must be > 1. For more theoretical information
concerning this parameter, see Goodman & Weare, 2010, Comm. App. Math.
Comp. Sci., 5, 65, Eq. [9] p70.
The parameter 'rhat_threshold' can be a numpy.array with individual
threshold value for each model parameter.
"""
if verbosity >0:
start_time = time_ini()
print(" MCMC sampler for the NEGFC technique ")
print(sep)
# If required, one create the output folder.
if save:
output_file_tmp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
if output_dir[-1] == '/':
output_dir = output_dir[:-1]
try:
os.makedirs(output_dir)
except OSError as exc:
if exc.errno == 17 and os.path.isdir(output_dir):
# errno.EEXIST == 17 -> File exists
pass
else:
raise
if not isinstance(cube, np.ndarray) or cube.ndim != 3:
raise ValueError('`cube` must be a 3D numpy array')
if cube_ref is not None:
if not isinstance(cube_ref, np.ndarray) or cube_ref.ndim != 3:
raise ValueError('`cube_ref` must be a 3D numpy array')
if weights is not None:
if not len(weights)==cube.shape[0]:
raise TypeError("Weights should have same length as cube axis 0")
norm_weights = weights/np.sum(weights)
else:
norm_weights=weights
if psfn.ndim==3:
if psfn.shape[0] != cube.shape[0]:
msg = "If PSF is 3D, number of frames must match cube length"
raise TypeError(msg)
if 'spe' not in sigma and 'pho' not in sigma:
raise ValueError("sigma not recognized")
## set imlib for rotation and shift
if imlib == 'opencv':
imlib_rot = imlib
elif imlib == 'skimage' or imlib == 'ndimage-interp':
imlib_rot = 'skimage'
elif imlib == 'vip-fft' or imlib == 'ndimage-fourier':
imlib_rot = 'vip-fft'
else:
raise TypeError("Interpolation not recognized.")
if nproc is None:
nproc = cpu_count() // 2 # Hyper-threading doubles the # of cores
# #########################################################################
# Initialization of the variables
# #########################################################################
dim = 3 # There are 3 model parameters: rad, theta, flux
itermin = niteration_min
limit = niteration_limit
supp = niteration_supp
maxgap = check_maxgap
initial_state = np.array(initial_state)
mu_sig = get_mu_and_sigma(cube, angs, ncomp, annulus_width,
aperture_radius, fwhm, initial_state[0],
initial_state[1], cube_ref=cube_ref, wedge=wedge,
svd_mode=svd_mode, scaling=scaling, algo=algo,
delta_rot=delta_rot, imlib=imlib_rot,
interpolation=interpolation, collapse=collapse,
weights=norm_weights, algo_options=algo_options)
# Measure mu and sigma once in the annulus (instead of each MCMC step)
if isinstance(mu_sigma, tuple):
if len(mu_sigma) != 2:
raise TypeError("if a tuple, mu_sigma should have 2 elements")
elif mu_sigma:
mu_sigma = mu_sig
if verbosity >0:
msg = "The mean and stddev in the annulus at the radius of the "
msg+= "companion (excluding the PA area directly adjacent to it)"
msg+=" are {:.2f} and {:.2f} respectively."
print(msg.format(mu_sigma[0],mu_sigma[1]))
else:
mu_sigma = mu_sig[0] # just take mean
if itermin > limit:
itermin = 0
fraction = 0.3
geom = 0
lastcheck = 0
konvergence = np.inf
rhat_count = 0
ac_count = 0
chain = np.empty([nwalkers, 1, dim])
nIterations = limit + supp
rhat = np.zeros(dim)
stop = np.inf
if bounds is None:
# angle subtended by aperture_radius/2 or fwhm at r=initial_state[0]
drot = 360/(2*np.pi*initial_state[0]/(aperture_radius*fwhm/2))
bounds = [(initial_state[0] - annulus_width/2.,
initial_state[0] + annulus_width/2.), # radius
(initial_state[1] - drot, initial_state[1] + drot), # angle
(0.1* initial_state[2], 2 * initial_state[2])] # flux
# size of ball of parameters for MCMC initialization
scal = abs(bounds[0][0]-initial_state[0])/initial_state[0]
for i in range(3):
for j in range(2):
test_scal = abs(bounds[i][j]-initial_state[i])/initial_state[i]
if test_scal < scal:
scal= test_scal
pos = initial_state*(1+np.random.normal(0, scal/7., (nwalkers, 3)))
# divided by 7 to not have any walker initialized out of bounds
if verbosity > 0:
print('Beginning emcee Ensemble sampler...')
sampler = emcee.EnsembleSampler(nwalkers, dim, lnprob, a=a,
args=([bounds, cube, angs, plsc, psfn,
fwhm, annulus_width, ncomp,
aperture_radius, initial_state,
cube_ref, svd_mode, scaling, algo,
delta_rot, fmerit, imlib,
interpolation, collapse,
algo_options, weights, transmission,
mu_sigma, sigma]),
threads=nproc)
if verbosity > 0:
print('emcee Ensemble sampler successful')
start = datetime.datetime.now()
# #########################################################################
# Affine Invariant MCMC run
# #########################################################################
if verbosity > 1:
print('\nStart of the MCMC run ...')
print('Step | Duration/step (sec) | Remaining Estimated Time (sec)')
for k, res in enumerate(sampler.sample(pos, iterations=nIterations)):
elapsed = (datetime.datetime.now()-start).total_seconds()
if verbosity > 1:
if k == 0:
q = 0.5
else:
q = 1
print('{}\t\t{:.5f}\t\t\t{:.5f}'.format(k, elapsed * q,
elapsed * (limit-k-1) * q),
flush=True)
start = datetime.datetime.now()
# ---------------------------------------------------------------------
# Store the state manually in order to handle with dynamical sized chain
# ---------------------------------------------------------------------
# Check if the size of the chain is long enough.
s = chain.shape[1]
if k+1 > s: # if not, one doubles the chain length
empty = np.zeros([nwalkers, 2*s, dim])
chain = np.concatenate((chain, empty), axis=1)
# Store the state of the chain
chain[:, k] = res[0]
# ---------------------------------------------------------------------
# If k meets the criterion, one tests the non-convergence.
# ---------------------------------------------------------------------
criterion = int(np.amin([np.ceil(itermin*(1+fraction)**geom),
lastcheck+np.floor(maxgap)]))
if k == criterion:
if verbosity > 1:
print('\n {} convergence test in progress...'.format(conv_test))
geom += 1
lastcheck = k
if display:
show_walk_plot(chain)
if save and verbosity == 3:
fname = '{d}/{f}_temp_k{k}'.format(d=output_dir,f=output_file_tmp, k=k)
data = {'chain': sampler.chain,
'lnprob': sampler.lnprobability,
'AR': sampler.acceptance_fraction}
with open(fname, 'wb') as fileSave:
pickle.dump(data, fileSave)
# We only test the rhat if we have reached the min # of steps
if (k+1) >= itermin and konvergence == np.inf:
if conv_test == 'gb':
thr0 = int(np.floor(burnin*k))
thr1 = int(np.floor((1-burnin)*k*0.25))
# We calculate the rhat for each model parameter.
for j in range(dim):
part1 = chain[:, thr0:thr0 + thr1, j].reshape(-1)
part2 = chain[:, thr0 + 3 * thr1:thr0 + 4 * thr1, j
].reshape(-1)
series = np.vstack((part1, part2))
rhat[j] = gelman_rubin(series)
if verbosity > 0:
print(' r_hat = {}'.format(rhat))
cond = rhat <= rhat_threshold
print(' r_hat <= threshold = {} \n'.format(cond))
# We test the rhat.
if (rhat <= rhat_threshold).all():
rhat_count += 1
if rhat_count < rhat_count_threshold:
if verbosity > 0:
msg = "Gelman-Rubin test OK {}/{}"
print(msg.format(rhat_count, rhat_count_threshold))
elif rhat_count >= rhat_count_threshold:
if verbosity > 0 :
print('... ==> convergence reached')
konvergence = k
stop = konvergence + supp
else:
rhat_count = 0
elif conv_test == 'ac':
# We calculate the auto-corr test for each model parameter.
if save:
write_fits(output_dir+"/TMP_test_chain{:.0f}.fits".format(k),chain[:,:k])
for j in range(dim):
rhat[j] = autocorr_test(chain[:,:k,j])
thr = 1./ac_c
if verbosity > 0:
print('Auto-corr tau/N = {}'.format(rhat))
print('tau/N <= {} = {} \n'.format(thr, rhat<thr))
if (rhat <= thr).all():
ac_count+=1
if verbosity > 0:
msg = "Auto-correlation test passed for all params!"
msg+= "{}/{}".format(ac_count,ac_count_thr)
print(msg)
if ac_count >= ac_count_thr:
msg='\n ... ==> convergence reached'
print(msg)
stop = k
else:
ac_count = 0
else:
raise ValueError('conv_test value not recognized')
# append the autocorrelation factor to file for easy reading
if save:
with open(output_dir + '/MCMC_results_tau.txt', 'a') as f:
f.write(str(rhat) + '\n')
# We have reached the maximum number of steps for our Markov chain.
if k+1 >= stop:
if verbosity > 0:
print('We break the loop because we have reached convergence')
break
if k == nIterations-1:
if verbosity > 0:
print("We have reached the limit # of steps without convergence")
if save:
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
input_parameters = {j: values[j] for j in args[1:]}
output = {'chain': chain_zero_truncated(chain),
'input_parameters': input_parameters,
'AR': sampler.acceptance_fraction,
'lnprobability': sampler.lnprobability}
if output_file is None:
output_file = 'MCMC_results'
with open(output_dir+'/'+output_file, 'wb') as fileSave:
pickle.dump(output, fileSave)
msg = "\nThe file MCMC_results has been stored in the folder {}"
print(msg.format(output_dir+'/'))
if verbosity > 0:
timing(start_time)
return chain_zero_truncated(chain)
def chain_zero_truncated(chain):
"""
Return the Markov chain with the dimension: walkers x steps* x parameters,
where steps* is the last step before having 0 (not yet constructed chain).
Parameters
----------
chain: numpy.array
The MCMC chain.
Returns
-------
out: numpy.array
The truncated MCMC chain, that is to say, the chain which only contains
relevant information.
"""
try:
idxzero = np.where(chain[0, :, 0] == 0.0)[0][0]
except:
idxzero = chain.shape[1]
return chain[:, 0:idxzero, :]
def show_walk_plot(chain, save=False, output_dir='', **kwargs):
"""
Display or save a figure showing the path of each walker during the MCMC run
Parameters
----------
chain: numpy.array
The Markov chain. The shape of chain must be nwalkers x length x dim.
If a part of the chain is filled with zero values, the method will
discard these steps.
save: boolean, default: False
If True, a pdf file is created.
output_dir: str, optional
The name of the output directory which contains the output files in the
case ``save`` is True.
kwargs:
Additional attributes are passed to the matplotlib plot method.
Returns
-------
Display the figure or create a pdf file named walk_plot.pdf in the working
directory.
"""
temp = np.where(chain[0, :, 0] == 0.0)[0]
if len(temp) != 0:
chain = chain[:, :temp[0], :]
labels = kwargs.pop('labels', ["$r$", r"$\theta$", "$f$"])
fig, axes = plt.subplots(3, 1, sharex=True,
figsize=kwargs.pop('figsize', (8, 6)))
axes[2].set_xlabel(kwargs.pop('xlabel', 'step number'))
axes[2].set_xlim(kwargs.pop('xlim', [0, chain.shape[1]]))
color = kwargs.pop('color', 'k')
alpha = kwargs.pop('alpha', 0.4)
for j in range(3):
axes[j].plot(chain[:, :, j].T, color=color, alpha=alpha, **kwargs)
axes[j].yaxis.set_major_locator(MaxNLocator(5))
axes[j].set_ylabel(labels[j])
fig.tight_layout(h_pad=0)
if save:
plt.savefig(output_dir+'walk_plot.pdf')
plt.close(fig)
else:
plt.show()
def show_corner_plot(chain, burnin=0.5, save=False, output_dir='', **kwargs):
"""
Display or save a figure showing the corner plot (pdfs + correlation plots)
Parameters
----------
chain: numpy.array
The Markov chain. The shape of chain must be nwalkers x length x dim.
If a part of the chain is filled with zero values, the method will
discard these steps.
burnin: float, default: 0
The fraction of a walker chain we want to discard.
save: boolean, default: False
If True, a pdf file is created.
output_dir: str, optional
The name of the output directory which contains the output files in the
case ``save`` is True.
kwargs:
Additional attributes are passed to the corner.corner() method.
Returns
-------
Display the figure or create a pdf file named walk_plot.pdf in the working
directory.
Raises
------
ImportError
"""
try:
temp = np.where(chain[0, :, 0] == 0.0)[0]
if len(temp) != 0:
chain = chain[:, :temp[0], :]
length = chain.shape[1]
indburn = int(np.floor(burnin*(length-1)))
chain = chain[:, indburn:length, :].reshape((-1, 3))
except IndexError:
pass
if chain.shape[0] == 0:
print("It seems the chain is empty. Have you already run the MCMC?")
else:
labels = kwargs.pop('labels', ["$r$", r"$\theta$", "$f$"])
fig = corner.corner(chain, labels=labels, **kwargs)
if save:
plt.savefig(output_dir+'corner_plot.pdf')
plt.close(fig)
else:
plt.show()
def confidence(isamples, cfd=68.27, bins=100, gaussian_fit=False, weights=None,
verbose=True, save=False, output_dir='', force=False,
output_file='confidence.txt', title=None, plsc=None, **kwargs):
r"""
Determine the highly probable value for each model parameter, as well as
the 1-sigma confidence interval.
Parameters
----------
isamples: numpy.array
The independent samples for each model parameter.
cfd: float, optional
The confidence level given in percentage.
bins: int, optional
The number of bins used to sample the posterior distributions.
gaussian_fit: boolean, optional
If True, a gaussian fit is performed in order to determine
(:math:`\mu, \sigma`).
weights : (n, ) numpy ndarray or None, optional
An array of weights for each sample.
verbose: boolean, optional
Display information in the shell.
save: boolean, optional
If "True", a txt file with the results is saved in the output
repository.
output_dir: str, optional
If save is True, this is the full path to a directory where the results
are saved.
force: bool, optional
If set to True, force the confidence interval estimate even if too
many samples fall in a single bin (unreliable CI estimates). If False,
an error message is raised if the percentile of samples falling in a
single bin is larger than cfd, suggesting to increase number of bins.
output_file: str, opt
If save is True, name of the text file in which the results are saved.
title: bool or str, opt
If not None, will print labels and parameter values on top of each
plot. If a string, will print that label in front of the parameter
values.
plsc: float, opt
If save is True, this is used to convert pixels to arcsec when writing
results for r.
Returns
-------
out: tuple
A 2 elements tuple with either:
[gaussian_fit=False] a) the highly probable solutions (dictionary),
b) the respective confidence interval (dict.);
[gaussian_fit=True] a) the center of the best-fit 1d Gaussian
distributions (tuple of 3 floats), and
b) their standard deviation, for each parameter
"""
try:
l = isamples.shape[1]
if l == 1:
isamples = isamples[:,0]
pKey = ['f']
label_file = ['flux']
label = [r'$\Delta f$']
elif l == 3:
pKey = ['r', 'theta', 'f']
label_file = ['r', r'$\theta$', 'flux']
label = [r'$r$', r'$\theta$', r'$f$']
else:
raise TypeError("input shape of isamples not recognized")
except:
l = 1
pKey = ['f']
label_file = ['flux']
label = [r'$\Delta f$']
confidenceInterval = {}
val_max = {}
if cfd == 100:
cfd = 99.9
#########################################
## Determine the confidence interval ##
#########################################
if gaussian_fit:
mu = np.zeros(l)
sigma = np.zeros_like(mu)
if gaussian_fit:
fig, ax = plt.subplots(2, l, figsize=(int(l*4),8))
else:
fig, ax = plt.subplots(1, l, figsize=(int(l*4),4))
for j in range(l):
if l>1:
if gaussian_fit:
n, bin_vertices, _ = ax[0][j].hist(isamples[:,j], bins=bins,
weights=weights,
histtype='step',
edgecolor='gray')
else:
n, bin_vertices, _ = ax[j].hist(isamples[:,j], bins=bins,
weights=weights,
histtype='step',
edgecolor='gray')
else:
if gaussian_fit:
n, bin_vertices, _ = ax[0].hist(isamples[:], bins=bins,
weights=weights,
histtype='step',
edgecolor='gray')
else:
n, bin_vertices, _ = ax.hist(isamples[:], bins=bins,
weights=weights,
histtype='step',
edgecolor='gray')
bins_width = np.mean(np.diff(bin_vertices))
surface_total = np.sum(np.ones_like(n)*bins_width * n)
n_arg_sort = np.argsort(n)[::-1]
test = 0
pourcentage = 0
for k, jj in enumerate(n_arg_sort):
test = test + bins_width*n[int(jj)]
pourcentage = test/surface_total*100
if pourcentage > cfd:
if verbose:
msg = 'percentage for {}: {}%'
print(msg.format(label_file[j], pourcentage))
break
if k ==0:
msg = "WARNING: Percentile reached in a single bin. "
msg += "This may be due to outliers or a small sample."
msg += "Uncertainties will be unreliable. Try one of these:"
msg += "increase bins, or trim outliers, or decrease cfd."
if force:
raise ValueError(msg)
else:
print(msg)
n_arg_min = int(n_arg_sort[:k+1].min())
n_arg_max = int(n_arg_sort[:k+1].max())
if n_arg_min == 0:
n_arg_min += 1
if n_arg_max == bins:
n_arg_max -= 1
val_max[pKey[j]] = bin_vertices[int(n_arg_sort[0])]+bins_width/2.
confidenceInterval[pKey[j]] = np.array([bin_vertices[n_arg_min-1],
bin_vertices[n_arg_max+1]]
- val_max[pKey[j]])
if title is not None:
if isinstance(title, str):
lab = title
else:
lab = pKey[j]
if l>1:
arg = (isamples[:, j] >= bin_vertices[n_arg_min - 1]) * \
(isamples[:, j] <= bin_vertices[n_arg_max + 1])
if gaussian_fit:
ax[0][j].hist(isamples[arg,j], bins=bin_vertices,
facecolor='gray', edgecolor='darkgray',
histtype='stepfilled', alpha=0.5)
ax[0][j].vlines(val_max[pKey[j]], 0, n[int(n_arg_sort[0])],
linestyles='dashed', color='red')
ax[0][j].set_xlabel(label[j])
if j == 0:
ax[0][j].set_ylabel('Counts')
if title is not None:
msg = r"{}: {:.3f} {:.3f} +{:.3f}"
ax[0][j].set_title(msg.format(lab, val_max[pKey[j]],
confidenceInterval[pKey[j]][0],
confidenceInterval[pKey[j]][1]),
fontsize=10)
mu[j], sigma[j] = norm.fit(isamples[:, j])
n_fit, bins_fit = np.histogram(isamples[:, j], bins, density=1,
weights=weights)
ax[1][j].hist(isamples[:, j], bins, density=1, weights=weights,
facecolor='gray', edgecolor='darkgray',
histtype='step')
y = norm.pdf(bins_fit, mu[j], sigma[j])
ax[1][j].plot(bins_fit, y, 'r--', linewidth=2, alpha=0.7)
ax[1][j].set_xlabel(label[j])
if j == 0:
ax[1][j].set_ylabel('Counts')
if title is not None:
msg = r"{}: $\mu$ = {:.4f}, $\sigma$ = {:.4f}"
ax[1][j].set_title(msg.format(lab, mu[j], sigma[j]),
fontsize=10)
else:
ax[j].hist(isamples[arg,j], bins=bin_vertices, facecolor='gray',
edgecolor='darkgray', histtype='stepfilled',
alpha=0.5)
ax[j].vlines(val_max[pKey[j]], 0, n[int(n_arg_sort[0])],
linestyles='dashed', color='red')
ax[j].set_xlabel(label[j])
if j == 0:
ax[j].set_ylabel('Counts')
if title is not None:
msg = r"{}: {:.3f} {:.3f} +{:.3f}"
ax[1].set_title(msg.format(lab, val_max[pKey[j]],
confidenceInterval[pKey[j]][0],
confidenceInterval[pKey[j]][1]),
fontsize=10)
else:
arg = (isamples[:] >= bin_vertices[n_arg_min - 1]) * \
(isamples[:] <= bin_vertices[n_arg_max + 1])
if gaussian_fit:
ax[0].hist(isamples[arg], bins=bin_vertices,
facecolor='gray', edgecolor='darkgray',
histtype='stepfilled', alpha=0.5)
ax[0].vlines(val_max[pKey[j]], 0, n[int(n_arg_sort[0])],
linestyles='dashed', color='red')
ax[0].set_xlabel(label[j])
if j == 0:
ax[0].set_ylabel('Counts')
if title is not None:
msg = r"{}: {:.3f} {:.3f} +{:.3f}"
ax[0].set_title(msg.format(lab, val_max[pKey[j]],
confidenceInterval[pKey[j]][0],
confidenceInterval[pKey[j]][1]),
fontsize=10)
mu[j], sigma[j] = norm.fit(isamples[:])
n_fit, bins_fit = np.histogram(isamples[:], bins, density=1,
weights=weights)
ax[1].hist(isamples[:], bins, density=1, weights=weights,
facecolor='gray', edgecolor='darkgray',
histtype='step')
y = norm.pdf(bins_fit, mu[j], sigma[j])
ax[1].plot(bins_fit, y, 'r--', linewidth=2, alpha=0.7)
ax[1].set_xlabel(label[j])
if j == 0:
ax[1].set_ylabel('Counts')
if title is not None:
msg = r"{}: $\mu$ = {:.4f}, $\sigma$ = {:.4f}"
ax[1].set_title(msg.format(lab, mu[j], sigma[j]),
fontsize=10)
else:
ax.hist(isamples[arg],bins=bin_vertices, facecolor='gray',
edgecolor='darkgray', histtype='stepfilled',
alpha=0.5)
ax.vlines(val_max[pKey[j]], 0, n[int(n_arg_sort[0])],
linestyles='dashed', color='red')
ax.set_xlabel(label[j])
if j == 0:
ax.set_ylabel('Counts')
if title is not None:
msg = r"{}: {:.3f} {:.3f} +{:.3f}"
ax.set_title(msg.format(lab, val_max[pKey[j]],
confidenceInterval[pKey[j]][0],
confidenceInterval[pKey[j]][1]),
fontsize=10)
plt.tight_layout(w_pad=0.1)
if save:
if gaussian_fit:
plt.savefig(output_dir+'confi_hist_flux_r_theta_gaussfit.pdf')
else:
plt.savefig(output_dir+'confi_hist_flux_r_theta.pdf')
if verbose:
print('\n\nConfidence intervals:')
if l>1:
print('r: {} [{},{}]'.format(val_max['r'],
confidenceInterval['r'][0],
confidenceInterval['r'][1]))
print('theta: {} [{},{}]'.format(val_max['theta'],
confidenceInterval['theta'][0],
confidenceInterval['theta'][1]))
print('flux: {} [{},{}]'.format(val_max['f'],
confidenceInterval['f'][0],
confidenceInterval['f'][1]))
if gaussian_fit:
print()
print('Gaussian fit results:')
if l>1:
print('r: {} +-{}'.format(mu[0], sigma[0]))
print('theta: {} +-{}'.format(mu[1], sigma[1]))
print('f: {} +-{}'.format(mu[2], sigma[2]))
else:
print('f: {} +-{}'.format(mu[0], sigma[0]))
##############################################
## Write inference results in a text file ##
##############################################
if save:
with open(output_dir+output_file, "w") as f:
f.write('###########################\n')
f.write('#### INFERENCE TEST ###\n')
f.write('###########################\n')
f.write(' \n')
f.write('Results of the MCMC fit\n')
f.write('----------------------- \n')
f.write(' \n')
f.write('>> Position and flux of the planet (highly probable):\n')
f.write('{} % confidence interval\n'.format(cfd))
f.write(' \n')
for i in range(l):
confidenceMax = confidenceInterval[pKey[i]][1]
confidenceMin = -confidenceInterval[pKey[i]][0]
if i == 2 or l==1:
text = '{}: \t\t\t{:.3f} \t-{:.3f} \t+{:.3f}\n'
else:
text = '{}: \t\t\t{:.3f} \t\t-{:.3f} \t\t+{:.3f}\n'
f.write(text.format(pKey[i], val_max[pKey[i]],
confidenceMin, confidenceMax))
if l>1 and plsc is not None:
f.write(' ')
f.write('Platescale = {} mas\n'.format(plsc*1000))
f.write('r (mas): \t\t{:.2f} \t\t-{:.2f} \t\t+{:.2f}\n'.format(
val_max[pKey[0]]*plsc*1000,
-confidenceInterval[pKey[0]][0]*plsc*1000,
confidenceInterval[pKey[0]][1]*plsc*1000))
if gaussian_fit:
return mu, sigma
else:
return val_max, confidenceInterval
|
vortex-exoplanet/VIP
|
vip_hci/fm/negfc_mcmc.py
|
Python
|
mit
| 57,611
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Hexon.MvcTrig.Sample
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
|
dinowang/MvcTrig
|
Hexon.MvcTrig.Sample/Global.asax.cs
|
C#
|
mit
| 581
|
Nightshade
=========
This is an [Octopress](http://octopress.org/) theme that lies somewhere between [OctoPanel](https://github.com/ConnorAtherton/OctoPanel) and [Greyshade](https://github.com/shashankmehta/greyshade).
## Installation instructions
Open your terminal and type:
1. `$ cd octopress-blog`
2. `$ git clone git://github.com/barisbalic/nightshade.git .themes/nightshade`
3. `$ rake install['nightshade']`
4. `$ rake generate`
|
barisbalic/nightshade
|
README.md
|
Markdown
|
mit
| 440
|
var fs = require("fs");
var glob = require("glob");
var IOUtils = require("./IOUtils");
var DirectiveHandler = require("./DirectiveHandler");
var DIRECTIVE_MATCHER = /<!--#([a-z]+)([ ]+([a-z]+)="(.+?)")* -->/g;
(function() {
"use strict";
var ssi = function(inputDirectory, outputDirectory, matcher) {
this.inputDirectory = inputDirectory;
this.documentRoot = inputDirectory;
this.outputDirectory = outputDirectory;
this.matcher = matcher;
this.ioUtils = new IOUtils(this.documentRoot);
this.directiveHandler = new DirectiveHandler(this.ioUtils);
this.directiveHandler.parser = this;
};
ssi.prototype = {
compile: function() {
//noinspection JSUnresolvedFunction
var files = glob.sync(this.inputDirectory + this.matcher);
for (var i = 0; i < files.length; i++) {
var input = files[i];
var contents = fs.readFileSync(input, {encoding: "utf8"});
var data = this.parse(input, contents);
var output = input.replace(this.inputDirectory, this.outputDirectory);
this.ioUtils.writeFileSync(output, data.contents);
}
},
parse: function(filename, contents, variables) {
var instance = this;
variables = variables || {};
contents = contents.replace(new RegExp(DIRECTIVE_MATCHER), function(directive, directiveName) {
var data = instance.directiveHandler.handleDirective(directive, directiveName, filename, variables);
if (data.error) {
throw data.error;
}
for (var key in data.variables) {
if (data.variables.hasOwnProperty(key)) {
variables[data.variables[key].name] = data.variables[key].value;
}
}
return (data && data.output) || "";
});
return {contents: contents, variables: variables};
}
};
module.exports = ssi;
})();
|
omarsmak/cass-db
|
node_modules/ssi/lib/SSI.js
|
JavaScript
|
mit
| 1,751
|
/*
* The MIT License
*
* Copyright 2020 Intuit Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.intuit.karate.template;
import com.intuit.karate.resource.Resource;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.thymeleaf.templateresource.ITemplateResource;
/**
*
* @author pthomas3
*/
public class KarateTemplateResource implements ITemplateResource {
private final Resource resource;
public KarateTemplateResource(Resource resource) {
this.resource = resource;
}
@Override
public String getDescription() {
return resource.getRelativePath();
}
@Override
public String getBaseName() {
return resource.getRelativePath();
}
@Override
public boolean exists() {
return true;
}
@Override
public Reader reader() throws IOException {
return new InputStreamReader(resource.getStream());
}
@Override
public ITemplateResource relative(String relativeLocation) {
return new KarateTemplateResource(resource.resolve(relativeLocation));
}
}
|
intuit/karate
|
karate-core/src/main/java/com/intuit/karate/template/KarateTemplateResource.java
|
Java
|
mit
| 2,158
|
# GEOMEM
[](https://app.netlify.com/sites/geomem/deploys)
Geomem is a simple application written in JavaScript (Vanilla using ES6
features), HTML and SCSS.
I use this application to set the "I went" locations. You can self host this
application and use it too ! Nobody can control those data.
## Requirements
* git
* yarn
## Installation
* `git clone https://github.com/yoannfleurydev/geomem && cd geomem`
* `yarn`
* `yarn start`
|
yoannfleurydev/geomem
|
README.md
|
Markdown
|
mit
| 546
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30128.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ToPayList.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ToPayList.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
|
tiagodll/dNet.DB
|
ToPayList/Properties/Resources.Designer.cs
|
C#
|
mit
| 2,844
|
using System.Collections.Generic;
namespace KeyCounter {
class Counter
{
public string Name { get; set; }
public int Count { get; set; }
}
/// <summary>
/// Interaction logic for OverlayWindow.xaml
/// </summary>
public partial class OverlayWindow
{
public OverlayWindow() {
InitializeComponent();
List<Counter> cl = new List<Counter>();
for (int i = 0; i < 10; i++) {
cl.Add(new Counter() { Name = "Counter" + i, Count = i*i });
}
//counterItems.ItemsSource = cl;
}
}
}
|
mibbio/Hotkey-Counter
|
KeyCounter/OverlayWindow.xaml.cs
|
C#
|
mit
| 619
|
package main
import (
"fmt"
"github.com/aleasoluciones/serverstats"
)
func main() {
serverStats := serverstats.NewServerStats(serverstats.DefaultPeriodes)
for metric := range serverStats.Metrics {
fmt.Println(metric.Timestamp, fmt.Sprintf("%-15s", metric.Name), metric.Value, metric.Unit)
}
}
|
aleasoluciones/serverstats
|
example/serverstats_cmd.go
|
GO
|
mit
| 304
|
class Collection
def id
3
end
end
|
ndlib/waggle
|
spec/dummy/app/models/collection.rb
|
Ruby
|
mit
| 43
|
package t08_ExamPreparations.e02_17_September_2017;
import java.util.Scanner;
public class p05_Sheriff {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
//first three rows
int dots = (3 * n - 1) / 2;
System.out.print(repeatString(".", dots));
System.out.print("x");
System.out.println(repeatString(".", dots));
//second row
dots = (3 * n - 3) / 2;
System.out.print(repeatString(".", dots));
System.out.print("/x\\");
System.out.println(repeatString(".", dots));
//third row
System.out.print(repeatString(".", dots));
System.out.print("x|x");
System.out.println(repeatString(".", dots));
//middle part
dots = (3 * n - 2 * n - 1) / 2;
int x = n;
for (int i = 0; i < n; i++) {
System.out.print(repeatString(".", dots));
System.out.print(repeatString("x", x));
System.out.print("|");
System.out.print(repeatString("x", x));
System.out.println(repeatString(".", dots));
if(dots == 0)
break;
dots--;
x++;
}
if(n!= 1){
for (int i = 0; i < n; i++) {
dots++;
x--;
System.out.print(repeatString(".", dots));
System.out.print(repeatString("x", x));
System.out.print("|");
System.out.print(repeatString("x", x));
System.out.println(repeatString(".", dots));
if(dots == ((3 * n - 2 * n - 1) / 2))
break;
}
}
//two rows
dots = (3 * n - 1) / 2;
System.out.print(repeatString(".", dots - 1));
System.out.print("/x\\");
System.out.println(repeatString(".", dots - 1));
System.out.print(repeatString(".", dots - 1));
System.out.print("\\x/");
System.out.println(repeatString(".", dots - 1));
//middle part
dots = (3 * n - 2 * n - 1) / 2;
x = n;
for (int i = 0; i < n; i++) {
System.out.print(repeatString(".", dots));
System.out.print(repeatString("x", x));
System.out.print("|");
System.out.print(repeatString("x", x));
System.out.println(repeatString(".", dots));
if(dots == 0)
break;
dots--;
x++;
}
if(n !=1){
for (int i = 0; i < n; i++) {
dots++;
x--;
System.out.print(repeatString(".", dots));
System.out.print(repeatString("x", x));
System.out.print("|");
System.out.print(repeatString("x", x));
System.out.println(repeatString(".", dots));
if(dots == ((3 * n - 2 * n - 1) / 2))
break;
}
}
dots = (3 * n - 1) / 2;
//third row
System.out.print(repeatString(".", dots - 1));
System.out.print("x|x");
System.out.println(repeatString(".", dots - 1));
//second row
System.out.print(repeatString(".", dots - 1));
System.out.print("\\x/");
System.out.println(repeatString(".", dots - 1));
System.out.print(repeatString(".", dots));
System.out.print("x");
System.out.println(repeatString(".", dots));
}
private static String repeatString(String str, int count) {
StringBuilder sb = new StringBuilder(count);
for (int i = 0; i < count; i++) {
sb.append(str);
}
return sb.toString();
}
}
|
Packo0/SoftUniProgrammingBasics
|
src/t08_ExamPreparations/e02_17_September_2017/p05_Sheriff.java
|
Java
|
mit
| 3,792
|
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
// Given a triangle, find the minimum path sum from top to bottom.
// Each step you may move to adjacent numbers on the row below.
// For example, given the following triangle
// [
// [2],
// [3,4],
// [6,5,7],
// [4,1,8,3]
// ]
// The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
// Note:
// Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
// https://leetcode.com/problems/triangle/
namespace LocalLeet
{
public class Q120
{
public int MinimumTotal(int[][] triangle)
{
int[] answer = triangle[triangle.Length - 1]; // last row;
// calculate every row
for (int j = triangle.Length - 2; j >= 0; j--)
{
for (int i = 0; i <= j; i++)
{
answer[i] = triangle[j][i] + Math.Min(answer[i], answer[i + 1]);
}
}
return answer[0];
}
[Fact]
public void Q120_Triangle()
{
TestHelper.Run(input => MinimumTotal(input[0].ToIntArrayArray()).ToString());
}
}
}
|
txchen/localleet
|
csharp/Q120_Triangle.cs
|
C#
|
mit
| 1,260
|
import { DadosVeiculo } from '../../../../browser/src/app/services/veiculo.service';
import { DadosLogin, DadosRegistro, RegistroResultado } from '../../../../browser/src/interfaces/login.interface';
import { BrazucasServer } from '../../../../common/brazucas-server';
import { Jogador } from '../../../../common/database/models/Jogador';
import { environment } from '../../../../common/environment';
import { BrazucasEventos } from '../../interfaces/brazucas-eventos';
import { VoiceChatProvider } from '../../providers/voice-chat.provider';
import { Rpg } from '../../rpg';
import { playerEvent } from '../functions/player';
export class Events {
protected brazucasServer: BrazucasServer;
constructor(brazucasServer: BrazucasServer) {
this.brazucasServer = brazucasServer;
}
public async [BrazucasEventos.AUTENTICAR_JOGADOR](player: PlayerMp, dados: DadosLogin) {
try {
const jogador: Jogador = await this.brazucasServer.autenticarJogador(player.name, dados.senha);
if (jogador) {
player.spawn(environment.posicaoLogin);
await Rpg.playerProvider.update(player, jogador.toJSON());
return {
eventoResposta: 'AutenticacaoResultado',
credenciaisInvalidas: false,
autenticado: true,
};
} else {
return {
eventoResposta: 'AutenticacaoResultado',
credenciaisInvalidas: true,
autenticado: false,
};
}
} catch (err) {
console.error(err.toString());
return {
eventoResposta: 'AutenticacaoResultado',
credenciaisInvalidas: false,
autenticado: false,
};
}
}
public async [BrazucasEventos.REGISTRAR_JOGADOR](player: PlayerMp, dados: DadosRegistro) {
try {
const jogador: Jogador = await this.brazucasServer.registrarJogador(player, dados);
if (jogador) {
player.spawn(environment.posicaoLogin);
playerEvent<RegistroResultado>(player, BrazucasEventos.REGISTRO_RESULTADO, {
erro: false,
jogador: jogador,
registrado: true,
});
} else {
playerEvent<RegistroResultado>(player, BrazucasEventos.REGISTRO_RESULTADO, {
registrado: false,
erro: true,
});
}
} catch (err) {
console.debug(`[REGISTRO] Um erro ocorreu ao criar o jogador ${player.name}`);
console.error(err.toString());
playerEvent<RegistroResultado>(player, BrazucasEventos.REGISTRO_RESULTADO, {
registrado: false,
erro: true,
mensagem: err.toString() || 'Erro interno ao cadastrar',
});
}
}
public async [BrazucasEventos.CRIAR_VEICULO](player: PlayerMp, dados: DadosVeiculo) {
try {
await this.brazucasServer.criarVeiculo(player, dados);
} catch (err) {
console.debug(`[VEÍCULOS] Um erro ocorreu ao criar o veículo`);
console.error(err.toString());
return false;
}
}
public async [BrazucasEventos.HABILITAR_VOICE_CHAT](player: PlayerMp, dados: any) {
console.log(`[VOICE CHAT] Ativando voice chat para ${player.name} com os dados: ${JSON.stringify(dados)}`);
const target = mp.players.at(dados.targetId);
if (!target) {
return {
erro: true,
mensagem: 'Jogador não encontrado',
};
}
VoiceChatProvider.habilitar(player, target);
}
public async [BrazucasEventos.DESABILITAR_VOICE_CHAT](player: PlayerMp, dados: any) {
console.log(`[VOICE CHAT] Desativando voice chat para ${player.name} com os dados: ${JSON.stringify(dados)}`);
const target = mp.players.at(dados.targetId);
if (!target) {
return {
erro: true,
mensagem: 'Jogador não encontrado',
};
}
VoiceChatProvider.desabilitar(player, target);
}
public async [BrazucasEventos.ANIMACAO_VOICE_CHAT](player: PlayerMp) {
console.log(`[VOICE CHAT] Aplicando animação para ${player.name}`);
player.playAnimation('special_ped@baygor@monologue_3@monologue_3e', 'trees_can_talk_4', 1, 0);
}
public async [BrazucasEventos.VISUALIZAR_ANIMACAO](player: PlayerMp, dados: {
pacote: string,
nome: string;
}) {
player.stopAnimation();
player.playAnimation(dados.pacote, dados.nome, 1, 0);
}
}
|
brazucas/ragemp
|
packages/rpg/lib/events/events.ts
|
TypeScript
|
mit
| 4,260
|
<?php
namespace PayPal\Api;
use PayPal\Common\PayPalModel;
use PayPal\Converter\FormatConverter;
use PayPal\Validation\NumericValidator;
/**
* Class Tax
*
* Tax information.
*
* @package PayPal\Api
*
* @property string id
* @property string name
* @property \PayPal\Api\number percent
* @property \PayPal\Api\Currency amount
*/
class Tax extends PayPalModel
{
/**
* The resource ID.
*
* @param string $id
*
* @return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* The resource ID.
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* The tax name. Maximum length is 20 characters.
*
* @param string $name
*
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* The tax name. Maximum length is 20 characters.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* The rate of the specified tax. Valid range is from 0.001 to 99.999.
*
* @param string|double $percent
*
* @return $this
*/
public function setPercent($percent)
{
NumericValidator::validate($percent, "Percent");
$percent = FormatConverter::formatToPrice($percent);
$this->percent = $percent;
return $this;
}
/**
* The rate of the specified tax. Valid range is from 0.001 to 99.999.
*
* @return string
*/
public function getPercent()
{
return $this->percent;
}
/**
* The tax as a monetary amount. Cannot be specified in a request.
*
* @param \PayPal\Api\Currency $amount
*
* @return $this
*/
public function setAmount($amount)
{
$this->amount = $amount;
return $this;
}
/**
* The tax as a monetary amount. Cannot be specified in a request.
*
* @return \PayPal\Api\Currency
*/
public function getAmount()
{
return $this->amount;
}
}
|
COD-Project/unagauchada
|
vendor/paypal/rest-api-sdk-php/lib/PayPal/Api/Tax.php
|
PHP
|
mit
| 2,291
|
namespace MvpDemo
{
partial class FormGeneratorDemo
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.uiGenerator = new MvpFramework.WinForms.Controls.GeneratorControl();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// uiGenerator
//
this.uiGenerator.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.uiGenerator.AutoSize = true;
this.uiGenerator.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.uiGenerator.Location = new System.Drawing.Point(12, 12);
this.uiGenerator.ModelBinder = null;
this.uiGenerator.ModelProperty = null;
this.uiGenerator.Name = "uiGenerator";
this.uiGenerator.Size = new System.Drawing.Size(453, 56);
this.uiGenerator.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(27, 225);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// FormGeneratorDemo
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(477, 262);
this.Controls.Add(this.button1);
this.Controls.Add(this.uiGenerator);
this.Name = "FormGeneratorDemo";
this.Text = "FormGeneratorDemo";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private MvpFramework.WinForms.Controls.GeneratorControl uiGenerator;
private System.Windows.Forms.Button button1;
}
}
|
JohnLambe/JLCSUtils
|
JLCSUtils/MvpDemo/FormGeneratorDemo.Designer.cs
|
C#
|
mit
| 3,069
|
import pygame
import math
class Screen:
'''
Se encarga de controlar lo que ve el jugador en la pantalla.
Parameters
----------
size : List[int]
Tamaño de la pantalla, ``[w, h]``.
Notes
-----
Primero se debe crear una instancia de este objeto, luego, en cada loop del
juego uno debe (en orden):
- Pintar la pantalla con ``fill()`` para tapar el frame anterior.
- Dibujar todos los sprites con ``draw()``.
- Actualizar la pantalla con ``update()``.
Examples
--------
Acá hay un ejemplo de uso::
# crear la pantalla
screen = toledo.graphics.Screen(screen_size)
...
def loop(): # función ejecutada una vez en cada frame
...
# pintar pantalla de negro para tapar frame anterior
screen.fill(toledo.graphics.Color.from_name("black"))
# dibujar todo lo que haga falta
screen.draw(......)
screen.draw(......)
screen.draw(......)
# por último actualizar pantalla
screen.update()
'''
ANCHOR_TOP_LEFT = 0
'''
int : Anclaje al borde superior izquierdo. Ver función ``draw()``.
'''
ANCHOR_CENTER = 1
'''
int : Anclaje al centro. Ver función ``draw()``.
'''
def __init__(self, size):
self._screen = pygame.display.set_mode(size)
def fill(self, color):
'''
Pintar la pantalla completamente de un color.
Parameters
----------
color : toledo.graphics.Color
Color a usar.
'''
self._screen.fill(color.get_tuple())
def draw(self, sprite, rect, angle=0, smooth=False, anchor=None):
'''
Dibujar un sprite en la pantalla.
No se verán los cambios hasta que se llame a la función
``Screen.update()``.
Parameters
----------
sprite : toledo.graphics.Sprite
Sprite a dibujar.
rect : toledo.Rect
Posición en la pantalla en donde dibujar. Se respeta el tamaño dado.
angle : :obj:`float`, optional
Ángulo de rotación en grados, sentido contrario a las agujas del
reloj.
smooth : :obj:`bool`, optional
Si usar o no antialiasing.
anchor : :obj:`int`, optional
Tipo de anclaje a usar, (por ej. si centrado o esquinado). Usar las
constantes definidas. Ej: ``Screen.ANCHOR_CENTER`` o
``Screen.ANCHOR_TOP_LEFT``.
Por defecto es un anclaje top-left.
Examples
--------
Ejemplo de uso::
screen = toledo.graphics.Screen(screen_size)
...
def loop():
...
screen.draw(sprite_ball, rect_ball, angle=angle_ball,
smooth=True, anchor=screen.ANCHOR_TOP_LEFT)
'''
image = sprite.get_pygame_image()
size = [int(rect.w), int(rect.h)]
angle = angle % 360
if size[0] == 0 or size[1] == 0:
return
pos = self._get_pos(rect, angle, anchor)
# el orden importa
image = self._scale_image(image, size, smooth)
image = self._rotate_image(image, angle, smooth)
self._screen.blit(image, pos)
def update(self):
'''
Actualiza lo que se ve en pantalla.
'''
pygame.display.flip()
def _scale_image(self, image, size, smooth):
'''
Escalar imagen al tamaño dado.
Parameters
----------
image : pygame.Surface
Imagen a escalar.
size : List[int]
Tamaño a escalar, ``[w, h]``.
smooth : bool
Si usar o no antialiasing.
Returns
-------
pygame.Surface
Imagen escalada.
'''
# hacer copia para no modificar la lista original
size = size[:]
if size[0] < 0:
size[0] *= -1
image = pygame.transform.flip(image, True, False)
if size[1] < 0:
size[1] *= -1
image = pygame.transform.flip(image, False, True)
if smooth:
return pygame.transform.smoothscale(image, size)
else:
return pygame.transform.scale(image, size)
def _rotate_image(self, image, angle, smooth):
'''
Rotar imagen al ángulo dado.
Parameters
----------
image : pygame.Surface
Imagen a escalar.
angle : float
Ángulo de rotación en grados, sentido contrario a las agujas del
reloj.
smooth : bool
Si usar o no antialiasing.
Returns
-------
pygame.Surface
Imagen rotada.
'''
if smooth:
return pygame.transform.rotozoom(image, angle, 1)
else:
return pygame.transform.rotate(image, angle)
def _get_pos(self, rect, angle, anchor):
'''
Calcular la posición correcta en donde dibujar la textura. ``pygame``
necesita la posición de la esquina superior izquierda.
Implementa el comportamiento de los anchors.
Parameters
----------
rect : toledo.Rect
Posición y tamaño de la imagen dada por el usuario (no es el tamaño
final luego de la rotación).
angle : float
Ángulo de rotación en grados, sentido contrario a las agujas del
reloj.
anchor : int
Tipo de anclaje a usar.
Returns
-------
List[int]
Posición en la cual hay que dibujar la imagen con ``pygame`` para
que quede en la posición correcta. ``[x, y]``.
'''
pos = [None, None]
angle_rads = math.radians(angle)
# calcular tamaño de la imagen ya rotada, siempre positivo. Puede que
# haya una mejor forma pero funciona
rotated_size = [
abs(abs(rect.w) * math.cos(angle_rads)) +
abs(abs(rect.h) * math.sin(angle_rads)),
abs(abs(rect.h) * math.cos(angle_rads)) +
abs(abs(rect.w) * math.sin(angle_rads))
]
if anchor == None:
anchor = self.ANCHOR_TOP_LEFT
if anchor == self.ANCHOR_CENTER:
pos = [rect.x - rotated_size[0] / 2,
rect.y - rotated_size[1] / 2]
elif anchor == self.ANCHOR_TOP_LEFT:
# corrección para imagenes rotadas. También puede que haya una mejor
# forma
if angle > 0 and angle <= 90:
correction = [
0,
abs(abs(rect.w) * math.sin(angle_rads))
]
elif angle > 90 and angle <= 180:
correction = [
abs(abs(rect.w) * math.cos(angle_rads)),
rotated_size[1]
]
elif angle > 180 and angle <= 270:
correction = [
rotated_size[0],
abs(abs(rect.h) * math.cos(angle_rads)),
]
else:
correction = [
abs(abs(rect.h) * math.sin(angle_rads)),
0
]
# cuando el ancho es negativo, el borde izquierdo pasa a ser el que
# originalmente era el derecho
if rect.w < 0:
pos[0] = rect.x - abs(rect.w)
else:
pos[0] = rect.x - correction[0]
# lo mismo para el borde superior
if rect.h < 0:
pos[1] = rect.y - abs(rect.h)
else:
pos[1] = rect.y - correction[1]
else:
print("ERROR")
return pos
|
toboso-team/toledo
|
toledo/graphics/screen.py
|
Python
|
mit
| 7,808
|
<?php
//输出接口数据
function output($data)
{
header("Content-Type:text/html; charset=utf-8");
$r_type = intval($_REQUEST['r_type']);//返回数据格式类型; 0:base64;1;json_encode;2:array
$data['act'] = ACT;
$data['act_2'] = ACT_2;
if ($r_type == 0)
{
echo base64_encode(json_encode($data));
}else if ($r_type == 1)
{
print_r(json_encode($data));
}else if ($r_type == 2)
{
print_r($data);
};
exit;
}
function getMConfig(){
$m_config = $GLOBALS['cache']->get("m_config");
if(true || $m_config===false)
{
$m_config = array();
$sql = "select code,val from ".DB_PREFIX."m_config";
$list = $GLOBALS['db']->getAll($sql);
foreach($list as $item){
$m_config[$item['code']] = $item['val'];
}
$GLOBALS['cache']->set("m_config",$m_config);
}
return $m_config;
}
/**
* 过滤SQL查询串中的注释。该方法只过滤SQL文件中独占一行或一块的那些注释。
*
* @access public
* @param string $sql SQL查询串
* @return string 返回已过滤掉注释的SQL查询串。
*/
function remove_comment($sql)
{
/* 删除SQL行注释,行注释不匹配换行符 */
$sql = preg_replace('/^\s*(?:--|#).*/m', '', $sql);
/* 删除SQL块注释,匹配换行符,且为非贪婪匹配 */
//$sql = preg_replace('/^\s*\/\*(?:.|\n)*\*\//m', '', $sql);
$sql = preg_replace('/^\s*\/\*.*?\*\//ms', '', $sql);
return $sql;
}
function emptyTag($string)
{
if(empty($string))
return "";
$string = strip_tags(trim($string));
$string = preg_replace("|&.+?;|",'',$string);
return $string;
}
function get_abs_img_root($content)
{
return str_replace("./public/",get_domain().APP_ROOT."/../public/",$content);
//return str_replace('/mapi/','/',$str);
}
function get_abs_url_root($content)
{
$content = str_replace("./",get_domain().APP_ROOT."/../",$content);
return $content;
}
function user_check($username_email,$pwd)
{
//$username_email = addslashes($username_email);
//$pwd = addslashes($pwd);
if($username_email&&$pwd)
{
//$sql = "select *,id as uid from ".DB_PREFIX."user where (user_name='".$username_email."' or email = '".$username_email."') and is_delete = 0";
$sql = "select *,id as uid from ".DB_PREFIX."user where (user_name='".$username_email."' or email = '".$username_email."' or mobile = '".$username_email."') and is_delete = 0";
$user_info = $GLOBALS['db']->getRow($sql);
$is_use_pass = false;
if (strlen($pwd) != 32){
if($user_info['user_pwd']==md5($pwd.$user_info['code']) || $user_info['user_pwd']==md5($pwd)){
$is_use_pass = true;
}
}
else{
if($user_info['user_pwd']==$pwd){
$is_use_pass = true;
}
}
if($is_use_pass)
{
es_session::set("user_info",$user_info);
$GLOBALS['user_info'] = $user_info;
return $user_info;
}
else
return null;
}
else
{
return null;
}
}
function user_login($username_email,$pwd)
{
require_once APP_ROOT_PATH."system/libs/user.php";
if(check_ipop_limit(get_client_ip(),"user_dologin",intval(app_conf("SUBMIT_DELAY")))){
$result = do_login_user($username_email,$pwd);
}
else{
//showErr($GLOBALS['lang']['SUBMIT_TOO_FAST'],$ajax,url("shop","user#login"));
$result['status'] = 0;
$result['msg'] = $GLOBALS['lang']['SUBMIT_TOO_FAST'];
return $result;
}
if($result['status'])
{
//$GLOBALS['user_info'] = $result["user"];
return $result;
}
else
{
$GLOBALS['user_info'] = null;
unset($GLOBALS['user_info']);
if($result['data'] == ACCOUNT_NO_EXIST_ERROR)
{
$err = $GLOBALS['lang']['USER_NOT_EXIST'];
}
if($result['data'] == ACCOUNT_PASSWORD_ERROR)
{
$err = $GLOBALS['lang']['PASSWORD_ERROR'];
}
if($result['data'] == ACCOUNT_NO_VERIFY_ERROR)
{
$err = $GLOBALS['lang']['USER_NOT_VERIFY'];
}
$result['msg'] = $err;
return $result;
}
}
?>
|
leoliew/fanwe_p2p
|
mapi/lib/functions.php
|
PHP
|
mit
| 3,974
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>V8 API Reference Guide for node.js v9.0.0 - v9.1.0: v8::Locker Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v9.0.0 - v9.1.0
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1Locker.html">Locker</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-static-methods">Static Public Member Functions</a> |
<a href="classv8_1_1Locker-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">v8::Locker Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a9f41151c92493a27d6724676fc774b51"><td class="memItemLeft" align="right" valign="top">V8_INLINE </td><td class="memItemRight" valign="bottom"><a class="el" href="classv8_1_1Locker.html#a9f41151c92493a27d6724676fc774b51">Locker</a> (<a class="el" href="classv8_1_1Isolate.html">Isolate</a> *isolate)</td></tr>
<tr class="separator:a9f41151c92493a27d6724676fc774b51"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa9afe5a3dc3d28bcfe3f418c3a5a8d1e"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aa9afe5a3dc3d28bcfe3f418c3a5a8d1e"></a>
 </td><td class="memItemRight" valign="bottom"><b>Locker</b> (const <a class="el" href="classv8_1_1Locker.html">Locker</a> &)=delete</td></tr>
<tr class="separator:aa9afe5a3dc3d28bcfe3f418c3a5a8d1e"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad7ef23dade8390e16891ed5cec0e8692"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad7ef23dade8390e16891ed5cec0e8692"></a>
void </td><td class="memItemRight" valign="bottom"><b>operator=</b> (const <a class="el" href="classv8_1_1Locker.html">Locker</a> &)=delete</td></tr>
<tr class="separator:ad7ef23dade8390e16891ed5cec0e8692"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-methods"></a>
Static Public Member Functions</h2></td></tr>
<tr class="memitem:a3ae563ffdd9e8b5a0100f0ae756b3a6a"><td class="memItemLeft" align="right" valign="top">static bool </td><td class="memItemRight" valign="bottom"><a class="el" href="classv8_1_1Locker.html#a3ae563ffdd9e8b5a0100f0ae756b3a6a">IsLocked</a> (<a class="el" href="classv8_1_1Isolate.html">Isolate</a> *isolate)</td></tr>
<tr class="separator:a3ae563ffdd9e8b5a0100f0ae756b3a6a"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a19d2b640f2f9b3dd0ec3a6c09a0442ed"><td class="memItemLeft" align="right" valign="top">static bool </td><td class="memItemRight" valign="bottom"><a class="el" href="classv8_1_1Locker.html#a19d2b640f2f9b3dd0ec3a6c09a0442ed">IsActive</a> ()</td></tr>
<tr class="separator:a19d2b640f2f9b3dd0ec3a6c09a0442ed"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Constructor & Destructor Documentation</h2>
<a class="anchor" id="a9f41151c92493a27d6724676fc774b51"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">V8_INLINE v8::Locker::Locker </td>
<td>(</td>
<td class="paramtype"><a class="el" href="classv8_1_1Isolate.html">Isolate</a> * </td>
<td class="paramname"><em>isolate</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">explicit</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Initialize <a class="el" href="classv8_1_1Locker.html">Locker</a> for a given <a class="el" href="classv8_1_1Isolate.html">Isolate</a>. </p>
</div>
</div>
<h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="a19d2b640f2f9b3dd0ec3a6c09a0442ed"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static bool v8::Locker::IsActive </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Returns whether <a class="el" href="classv8_1_1Locker.html">v8::Locker</a> is being used by this <a class="el" href="classv8_1_1V8.html">V8</a> instance. </p>
</div>
</div>
<a class="anchor" id="a3ae563ffdd9e8b5a0100f0ae756b3a6a"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static bool v8::Locker::IsLocked </td>
<td>(</td>
<td class="paramtype"><a class="el" href="classv8_1_1Isolate.html">Isolate</a> * </td>
<td class="paramname"><em>isolate</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Returns whether or not the locker for a given isolate, is locked by the current thread. </p>
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>deps/v8/include/<a class="el" href="v8_8h_source.html">v8.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
|
v8-dox/v8-dox.github.io
|
c087502/html/classv8_1_1Locker.html
|
HTML
|
mit
| 9,653
|
-- boundary3.test
--
-- db eval {
-- SELECT t2.a FROM t1 JOIN t2 USING(a)
-- WHERE t1.rowid <= -36028797018963968 ORDER BY t2.a
-- }
SELECT t2.a FROM t1 JOIN t2 USING(a)
WHERE t1.rowid <= -36028797018963968 ORDER BY t2.a
|
bkiers/sqlite-parser
|
src/test/resources/boundary3.test_506.sql
|
SQL
|
mit
| 230
|
/*
Copyright (C) 2001, 2008 United States Government as represented by
the Administrator of the National Aeronautics and Space Administration.
All Rights Reserved.
*/
package gov.nasa.worldwind.applications.gio.ebrim;
import gov.nasa.worldwind.applications.gio.xml.ElementParser;
import gov.nasa.worldwind.util.Logging;
/**
* @author dcollins
* @version $Id$
*/
public class TelephoneNumberParser extends ElementParser implements TelephoneNumber
{
private String areaCode;
private String countryCode;
private String extension;
private String number;
private String phoneType;
public static final String ELEMENT_NAME = "TelephoneNumber";
private static final String AREA_CODE_ATTRIBUTE_NAME = "areaCode";
private static final String COUNTRY_CODE_ATTRIBUTE_NAME = "countryCode";
private static final String EXTENSION_ATTRIBUTE_NAME = "extension";
private static final String NUMBER_ATTRIBUTE_NAME = "number";
private static final String PHONE_TYPE_ATTRIBUTE_NAME = "phoneType";
public TelephoneNumberParser(String elementName, org.xml.sax.Attributes attributes)
{
super(elementName, attributes);
if (attributes == null)
{
String message = Logging.getMessage("nullValue.AttributesIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
for (int i = 0; i < attributes.getLength(); i++)
{
String attribName = attributes.getLocalName(i);
if (AREA_CODE_ATTRIBUTE_NAME.equalsIgnoreCase(attribName))
this.areaCode = attributes.getValue(i);
else if (COUNTRY_CODE_ATTRIBUTE_NAME.equalsIgnoreCase(attribName))
this.countryCode = attributes.getValue(i);
else if (EXTENSION_ATTRIBUTE_NAME.equalsIgnoreCase(attribName))
this.extension = attributes.getValue(i);
else if (NUMBER_ATTRIBUTE_NAME.equalsIgnoreCase(attribName))
this.number = attributes.getValue(i);
else if (PHONE_TYPE_ATTRIBUTE_NAME.equalsIgnoreCase(attribName))
this.phoneType = attributes.getValue(i);
}
}
public String getAreaCode()
{
return this.areaCode;
}
public void setAreaCode(String areaCode)
{
this.areaCode = areaCode;
}
public String getCountryCode()
{
return this.countryCode;
}
public void setCountryCode(String countryCode)
{
this.countryCode = countryCode;
}
public String getExtension()
{
return this.extension;
}
public void setExtension(String extension)
{
this.extension = extension;
}
public String getNumber()
{
return this.number;
}
public void setNumber(String number)
{
this.number = number;
}
public String getPhoneType()
{
return this.phoneType;
}
public void setPhoneType(String phoneType)
{
this.phoneType = phoneType;
}
}
|
caadxyz/Macro-Thinking-Micro-action
|
src/gov/nasa/worldwind/applications/gio/ebrim/TelephoneNumberParser.java
|
Java
|
mit
| 3,053
|
//
// Header.h
// ZgChess
//
// Created by 谢伟健 on 15-2-15.
// Copyright (c) 2015年 wk. All rights reserved.
//
// Github: https://github.com/WelkinXie/FiveInARow
//
#ifndef ZgChess_Header_h
#define ZgChess_Header_h
#define rgba(r, g, b, a) [SKColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define BLACKCHESS @"stone_black"
#define WHITECHESS @"stone_white"
#define CHESSBOARD @"chessboard"
#define BLACKREADY @"black"
#define WHITEREADY @"white"
#define LOCATION @"location"
#define DISTANCE @"distance"
#define WIN @"You Win"
#define LOSE @"You Lose"
#define READY @"Ready"
#define ALREADY @""
#define START @"Start"
//#define RETRACT @"regret"
#define RESTART @"restart"
#define PLAY @"play"
#define WHITERETRACT @"whiteRetract"
#define BLACKRETRACT @"blackRetract"
#endif
|
WelkinXie/FiveInARow
|
ZGChess/Header.h
|
C
|
mit
| 817
|
<?php
return [
/*
* basic stack
*/
'stack/error-stack',
'stack/session-stack',
'stack/cs-rf-stack',
'stack/view-stack',
/*
* handlers and releases
*/
'stack/url-mapper-handler',
];
|
asaokamei/Pile
|
app/config/stacks.php
|
PHP
|
mit
| 229
|
// Copyright 2011-2018 Nicholas J. Kain <njkain at gmail dot com>
// SPDX-License-Identifier: MIT
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <errno.h>
#include <limits.h>
#include "nk/stb_sprintf.h"
#include "nk/log.h"
#include "nk/io.h"
#include "leasefile.h"
#include "ndhc.h"
#include "scriptd.h"
static int leasefilefd = -1;
static void get_leasefile_path(char *leasefile, size_t dlen, char *ifname)
{
int splen = stbsp_snprintf(leasefile, dlen, "%s/LEASE-%s",
state_dir, ifname);
if (splen < 0 || (size_t)splen > dlen)
suicide("%s: (%s) snprintf failed; return=%d",
client_config.interface, __func__, splen);
}
void open_leasefile(void)
{
char leasefile[PATH_MAX];
get_leasefile_path(leasefile, sizeof leasefile, client_config.interface);
leasefilefd = open(leasefile, O_WRONLY|O_TRUNC|O_CREAT, 0644);
if (leasefilefd < 0)
suicide("%s: (%s) Failed to create lease file '%s': %s",
client_config.interface, __func__, leasefile, strerror(errno));
}
static void do_write_leasefile(struct in_addr ipnum)
{
char ip[INET_ADDRSTRLEN];
char out[INET_ADDRSTRLEN*2];
if (leasefilefd < 0) {
log_line("%s: (%s) leasefile fd < 0; no leasefile will be written",
client_config.interface, __func__);
return;
}
inet_ntop(AF_INET, &ipnum, ip, sizeof ip);
ssize_t olen = stbsp_snprintf(out, sizeof out, "%s\n", ip);
if (olen < 0 || (size_t)olen > sizeof ip) {
log_line("%s: (%s) snprintf failed; return=%zd",
client_config.interface, __func__, olen);
return;
}
if (safe_ftruncate(leasefilefd, 0)) {
log_line("%s: (%s) Failed to truncate lease file: %s",
client_config.interface, __func__, strerror(errno));
return;
}
if (lseek(leasefilefd, 0, SEEK_SET) == (off_t)-1) {
log_line("%s: (%s) Failed to seek to start of lease file: %s",
client_config.interface, __func__, strerror(errno));
return;
}
size_t outlen = strlen(out);
ssize_t ret = safe_write(leasefilefd, out, outlen);
if (ret < 0 || (size_t)ret != outlen)
log_line("%s: (%s) Failed to write ip to lease file.",
client_config.interface, __func__);
else
fsync(leasefilefd);
}
void write_leasefile(struct in_addr ipnum)
{
do_write_leasefile(ipnum);
request_scriptd_run();
if (client_config.enable_s6_notify) {
static char buf[] = "\n";
safe_write(client_config.s6_notify_fd, buf, 1);
close(client_config.s6_notify_fd);
client_config.enable_s6_notify = false;
}
}
|
niklata/ndhc
|
leasefile.c
|
C
|
mit
| 2,842
|
# Count Between
# I worked on this challenge [by myself, with: ].
# count_between is a method with three arguments:
# 1. An array of integers
# 2. An integer lower bound
# 3. An integer upper bound
#
# It returns the number of integers in the array between the lower and upper bounds,
# including (potentially) those bounds.
#
# If +array+ is empty the method should return 0
# Your Solution Below
def count_between(list_of_integers, lower_bound, upper_bound)
return 0 if list_of_integers.length == 0
count = 0
list_of_integers.each do |x|
count += 1 if (x >= lower_bound && x <= upper_bound)
end
count
end
|
edella2/phase-0
|
week-4/count-between/my_solution.rb
|
Ruby
|
mit
| 626
|
{
"posts": [
{
"url": "/entertainment/bts/2018/01/03/BTSM.1514981921.A.0CF.html",
"title": "180103 [V] RM's Hello 2018!",
"image": "http://v.phinf.naver.net/20180103_182/1514986072229SeS1m_JPEG/upload_KakaoTalk_20180103_222559691.jpg?type=a720_play",
"push": "83",
"boo": "0",
"date": "2018-01-03 20:18:38 +0800",
"boardName": "BTS",
"boardLink": "/category/bts"
} ,
{
"url": "/entertainment/koreanpop/2018/01/03/KoreanPopM.1514948532.A.4EC.html",
"title": "JBJ - True Color Album Trailer",
"image": "https://i.ytimg.com/vi/lGgc92vOzD8/hqdefault.jpg",
"push": "43",
"boo": "0",
"date": "2018-01-03 11:02:09 +0800",
"boardName": "韓樂",
"boardLink": "/category/koreanpop"
} ,
{
"url": "/entertainment/koreanpop/2018/01/01/KoreanPopM.1514818904.A.A43.html",
"title": "INFINITE - Tell Me M/V Teaser (Short)",
"image": "https://i.ytimg.com/vi/S9TdkoI7-mA/maxresdefault.jpg",
"push": "100",
"boo": "0",
"date": "2018-01-01 23:01:41 +0800",
"boardName": "韓樂",
"boardLink": "/category/koreanpop"
} ,
{
"url": "/entertainment/bts/2018/01/01/BTSM.1514736128.A.A2D.html",
"title": "180101 防彈BOMB Happy New Year 2018",
"image": "https://i.ytimg.com/vi/47tC_G1DJ7M/maxresdefault.jpg",
"push": "55",
"boo": "0",
"date": "2018-01-01 00:02:05 +0800",
"boardName": "BTS",
"boardLink": "/category/bts"
} ,
{
"url": "/entertainment/bts/2017/12/31/BTSM.1514734051.A.FF7.html",
"title": "171231-180101《2017 MBC 歌謠大祭典》",
"image": "https://i.ytimg.com/vi/V6gzgV1fBxg/maxresdefault.jpg",
"push": "100",
"boo": "0",
"date": "2017-12-31 23:27:28 +0800",
"boardName": "BTS",
"boardLink": "/category/bts"
} ,
{
"url": "/entertainment/koreanpop/2017/12/31/KoreanPopM.1514710903.A.FD2.html",
"title": "DAY6 - 努力看看吧 Live Video",
"image": "https://i.ytimg.com/vi/5-ysnvQpk6w/hqdefault.jpg",
"push": "21",
"boo": "0",
"date": "2017-12-31 17:01:41 +0800",
"boardName": "韓樂",
"boardLink": "/category/koreanpop"
}
]
}
|
sunnyKiwi/JustCopy
|
tag/cr/json/index.html
|
HTML
|
mit
| 2,851
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V1::NewLeaders', type: :request do
let(:user) { nil } # set this in subtests
let(:auth_headers) { { 'Authorization': "Bearer #{user.auth_token}" } }
# set these in subtests
let(:params) { {} }
let(:headers) { {} }
let(:method) { :get }
let(:url) { '' }
let(:setup) {} # override this to do any setup you'd usually do in before
before do
setup
send(method, url, params: params, headers: headers)
end
describe 'GET /v1/new_leaders/:id' do
let(:leader) { create(:new_leader) }
let(:method) { :get }
let(:url) { "/v1/new_leaders/#{leader.id}" }
it 'requires authentication' do
expect(response.status).to eq(401)
end
context 'when authenticated' do
let(:user) { create(:user_authed) }
let(:headers) { auth_headers }
let(:full_fields) do
%w[
id
created_at
updated_at
name
email
birthday
expected_graduation
gender
ethnicity
phone_number
address
latitude
longitude
parsed_address
parsed_city
parsed_state
parsed_state_code
parsed_postal_code
parsed_country
parsed_country_code
personal_website
github_url
linkedin_url
facebook_url
twitter_url
]
end
let(:limited_fields) do
%w[
id
name
]
end
it 'requires you to have relationship with leader' do
expect(response.status).to eq(403)
end
context 'as co-lead' do
let(:setup) do
colead = create(:new_leader, user: user)
leader.new_clubs << create(:new_club)
leader.new_clubs.first.new_leaders << colead
end
it 'shows basic info' do
expect(response.status).to eq(200)
expect(json).to include(*limited_fields)
expect(json).to_not include(*(full_fields - limited_fields))
end
end
context 'as leader themselves' do
let(:user) { create(:user_authed, new_leader: leader) }
let(:headers) { auth_headers }
it 'shows full info' do
expect(response.status).to eq(200)
expect(json).to include(*full_fields)
end
end
context 'as admin' do
let(:user) { create(:user_admin_authed) }
it 'shows full info' do
expect(response.status).to eq(200)
expect(json).to include(*full_fields)
end
end
end
end
describe 'PATCH /v1/new_leaders/:id' do
let(:leader) { create(:new_leader) }
let(:params) do
{
name: 'Larry King',
email: 'larry@king.com',
birthday: '1940-06-21',
expected_graduation: '2019-10-10',
gender: :male,
ethnicity: :white,
phone_number: '444-444-4444',
address: '123 Test Avenue, NYC',
personal_website: 'https://larry.king',
github_url: 'https://github.com/larryking',
linkedin_url: 'https://linkedin.com/u/larryking',
facebook_url: 'https://facebook.com/larry',
twitter_url: 'https://twitter.com/larryking'
}
end
let(:method) { :patch }
let(:url) { "/v1/new_leaders/#{leader.id}" }
it 'requires authentication' do
expect(response.status).to eq(401)
end
context 'when authenticated' do
let(:user) { create(:user_authed) }
let(:headers) { auth_headers }
it "requires you to be the leader's user" do
expect(response.status).to eq(403)
end
context "as leader's user" do
let(:setup) { leader.update_attributes(user: user) }
it 'succeeds' do
expect(response.status).to eq(200)
expect(json).to include(
'name' => 'Larry King',
'email' => 'larry@king.com',
'birthday' => '1940-06-21',
'expected_graduation' => '2019-10-10',
'gender' => 'male',
'ethnicity' => 'white',
'phone_number' => '444-444-4444',
'address' => '123 Test Avenue, NYC',
'personal_website' => 'https://larry.king',
'github_url' => 'https://github.com/larryking',
'linkedin_url' => 'https://linkedin.com/u/larryking',
'facebook_url' => 'https://facebook.com/larry',
'twitter_url' => 'https://twitter.com/larryking'
)
end
context 'with invalid params' do
let(:params) do
{
name: nil
}
end
it 'fails gracefully' do
expect(response.status).to eq(422)
expect(json['errors']).to include('name')
end
end
end
context 'as admin' do
let(:user) { create(:user_admin_authed) }
it 'succeeds' do
expect(response.status).to eq(200)
end
end
end
end
end
|
hackclub/api
|
spec/requests/v1/new_leaders_spec.rb
|
Ruby
|
mit
| 5,053
|
<?php
// Define namespace
namespace Sonic\Controller;
// Start Index Class
class Index extends \Sonic\Controller
{
public function index ()
{
}
}
|
andyburton/Sonic-Framework-Project
|
classes/Sonic/Controller/Index.php
|
PHP
|
mit
| 156
|
# log
Codeshare Application Logger
# Usage
```js
import log from '@codeshare/log'
log.fatal('message', {/*...*/})
log.error('message', {/*...*/})
log.warn('message', {/*...*/})
log.info('message', {/*...*/})
log.debug('message', {/*...*/})
log.trace('message', {/*...*/})
```
```js
log.logRequest({/*...*/})
```
```js
await log.onFinish()
```
|
Codeshare/log
|
README.md
|
Markdown
|
mit
| 347
|
function changeOfBaseQuestion(randomStream, params)
{
var number = randomStream.nextIntRange(240)+15;
var baseArray = [ {base: "decimal", value: number.toString(10), radix: 10}, {base: "hexadecimal", value: number.toString(16), radix: 16}, {base: "binary", value: number.toString(2), radix: 2} ];
randomStream.shuffle(baseArray);
this.a = baseArray[0];
this.b = baseArray[1];
//Array of {String, bool} pairs: the string representation of a number in a particular base
//and a flag indicating whether or not it is the correct answer.
this.answerChoices = [ {value: this.b.value, flag: true},
{value: (randomStream.nextIntRange(240)+15).toString(this.b.radix), flag: false},
{value: (randomStream.nextIntRange(240)+15).toString(this.b.radix), flag: false},
{value: (randomStream.nextIntRange(240)+15).toString(this.b.radix), flag: false} ]
randomStream.shuffle(this.answerChoices);
//Find the correct answer
this.correctIndex = 0;
for(var i=0; i<this.answerChoices.length; i++)
{
if(this.answerChoices[i].flag == true)
this.correctIndex = i;
}
this.formatQuestion = function(format) {
switch (format) {
case "HTML": return this.formatQuestionHTML();
}
return "unknown format";
};
this.formatQuestionHTML = function () {
var questionText = "<p>Convert " + this.a.value + " from " + this.a.base + " to " + this.b.base + ".</p>";
questionText += "<p><strong>a) </strong>"
+ this.answerChoices[0].value + "<br><strong>b) </strong>"
+ this.answerChoices[1].value + "<br><strong>c) </strong>"
+ this.answerChoices[2].value + "<br><strong>d) </strong>"
+ this.answerChoices[3].value + "</p>";
return questionText;
};
this.formatAnswer = function(format) {
switch (format) {
case "HTML": return this.formatAnswerHTML();
}
return "unknown format"; // TODO: consider exception
};
this.formatAnswerHTML = function () {
var text = String.fromCharCode(this.correctIndex + 97); //0 = 'a', 1 = 'b', 2 = 'c', etc...
return text;
};
};
|
pconrad/AwesomeExams
|
js/questionsDev/changeOfBase.js
|
JavaScript
|
mit
| 2,286
|
// http://codingbat.com/prob/p117334
public String stringSplosion(String str) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < str.length(); ++i) {
output.append(str.substring(0, i+1));
}
return output.toString();
}
|
dvt32/cpp-journey
|
Java/CodingBat/stringSplosion.java
|
Java
|
mit
| 246
|
#ifndef __NEURAL_NETWORK__H
#define __NEURAL_NETWORK__H
#include <string>
#include <fstream>
#include <cassert>
#include "layer.h"
#include "input_layer.h"
#include "hidden_layer.h"
#include "output_layer.h"
#include "weight_matrix.h"
#include "helper.h"
class NeuralNetwork {
private:
int n_outputs;
InputLayer input_layer;
std::vector<HiddenLayer> hidden_layers;
OutputLayer output_layer;
std::vector<WeightMatrix> weight_matrices;
double batch_size = 10000;
double step_size = 1e-3;
double threshold = 1e-3;
int iteration = 0;
public:
NeuralNetwork(int n_outputs);
void addInputLayer(int size);
void addHiddenLayer(int size);
void addOutputLayer();
double getIterationNumber() const;
double getBatchSize() const;
double getStepSize() const;
double getThreshold() const;
void setStepSize(double step_size);
void setBatchSize(double batch_size);
void setThreshold(double threshold);
std::vector<double> computeOutput(std::vector<double> input);
void backpropagate(std::vector<double> correct_output);
void train(std::vector<std::vector<double> > inputs,
std::vector<std::vector<double> > labels,
int save_period = -1,
std::string save_filename = "");
void test(std::vector<std::vector<double> > inputs,
std::vector<std::vector<double> > labels);
void save(std::string filename) const;
void load(std::string filename);
};
#endif
|
echentw/neural-network
|
nn/include/neural_network.h
|
C
|
mit
| 1,449
|
/*******************************************************************************
* The MIT License (MIT)
* Copyright (c) 2015 University of Twente
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
package hmi.physics;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import hmi.physics.controller.ControllerParameterException;
import hmi.physics.controller.ControllerParameterNotFoundException;
import hmi.physics.controller.PhysicalController;
import hmi.physics.controller.UniversalJointController;
import org.junit.Before;
import org.junit.Test;
/**
* Unit test cases for the hinge controller
* @author welberge
*/
public class UniversalJointControllerTest
{
private UniversalJointController universalJointController;
private static final float DAMPER_VALUEX = 10;
private static final float SPRING_VALUEX = 20;
private static final float DAMPER_VALUEY = 11;
private static final float SPRING_VALUEY = 21;
private static final float ANGLEX = 3;
private static final int AXISX = 2;
private static final float ANGLEY = 2;
private static final int AXISY = 1;
private static final String JOINT = "r_elbow";
private static final double PARAM_PRECISION = 0.001;
PhysicalHumanoid mockPhysicalHumanoid = mock(PhysicalHumanoid.class);
@Before
public void setup() throws ControllerParameterException
{
universalJointController = new UniversalJointController();
universalJointController.setDampers(DAMPER_VALUEX, DAMPER_VALUEY);
universalJointController.setSprings(SPRING_VALUEX, SPRING_VALUEY);
universalJointController.setParameterValue("joint", JOINT);
universalJointController.setParameterValue("anglex", ANGLEX);
universalJointController.setParameterValue("axisx", AXISX);
universalJointController.setParameterValue("angley", ANGLEY);
universalJointController.setParameterValue("axisy", AXISY);
}
@Test
public void testGetAngle() throws ControllerParameterNotFoundException
{
assertEquals(ANGLEX, universalJointController.getFloatParameterValue("anglex"), PARAM_PRECISION);
assertEquals(ANGLEY, universalJointController.getFloatParameterValue("angley"), PARAM_PRECISION);
}
@Test
public void testCopy() throws ControllerParameterException
{
PhysicalController hjcCopy = universalJointController.copy(mockPhysicalHumanoid);
assertEquals(DAMPER_VALUEX, Float.parseFloat(hjcCopy.getParameterValue("dsx")), PARAM_PRECISION);
assertEquals(SPRING_VALUEX, Float.parseFloat(hjcCopy.getParameterValue("ksx")), PARAM_PRECISION);
assertEquals(DAMPER_VALUEY, Float.parseFloat(hjcCopy.getParameterValue("dsy")), PARAM_PRECISION);
assertEquals(SPRING_VALUEY, Float.parseFloat(hjcCopy.getParameterValue("ksy")), PARAM_PRECISION);
assertEquals(ANGLEX, Float.parseFloat(hjcCopy.getParameterValue("anglex")), PARAM_PRECISION);
assertEquals(AXISX, Integer.parseInt(hjcCopy.getParameterValue("axisx")));
assertEquals(ANGLEY, Float.parseFloat(hjcCopy.getParameterValue("angley")), PARAM_PRECISION);
assertEquals(AXISY, Integer.parseInt(hjcCopy.getParameterValue("axisy")));
assertEquals(JOINT, hjcCopy.getParameterValue("joint"));
}
}
|
jankolkmeier/HmiCore
|
HmiPhysics/test/src/hmi/physics/UniversalJointControllerTest.java
|
Java
|
mit
| 4,513
|
class CreateDataFiles < ActiveRecord::Migration
def self.up
create_table :data_files do |t|
t.references :experiment
t.string :data_file_name
t.string :data_content_type
t.integer :data_file_size
t.datetime :data_updated_at
t.text :description
t.boolean :has_concentrations
t.string :has_concentration_units
t.string :mapping_errors
t.references :data_file_type
t.timestamps
end
end
def self.down
drop_table :data_files
end
end
|
vekelly09/metaboflo
|
db/migrate/20081002221651_create_data_files.rb
|
Ruby
|
mit
| 516
|
package com.unalsoft.elitefle.presentation.controller;
import com.unalsoft.elitefle.businesslogic.facade.FacadeFactory;
import com.unalsoft.elitefle.entity.xml.*;
import com.unalsoft.elitefle.vo.ActivityVo;
import com.unalsoft.elitefle.vo.SequenceVo;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Juan
*/
@ManagedBean(name = "systematizationActivityBean2")
@ViewScoped
public class SystematizationActivityBean2 implements Serializable {
private final String[] colorRef = {"black", "red", "lime ", "blue", "purple", "deeppink", "goldenrod"};
private final String[] colorCoRef = {"black", "orange", "greenyellow", "SkyBlue", "orchid", "hotpink", "gold"};
private final String R3 = "r3";
private final String R2 = "r2";
private final String R1 = "r1";
private ActivityVo activity;
private Integer idSequence;
private DocumentTexte text;
private Referent referent1;
private Referent referent2;
private List<Coreferent> coreferent1;
private List<Coreferent> coreferent2;
private List<Coreferent> coreferent3;
private Set<String> coreferentColors;
private String lastColor = "black";
private int rightAnswers;
public void preRenderView() throws Exception {
if (getIdSequence() != null) {
SequenceVo sequence = FacadeFactory.getInstance().getSequenceFacade().find(getIdSequence());
activity = FacadeFactory.getInstance().getActivityFacade().find(sequence.getIdSystematizationActivity());
if (text == null) {
text = Parser.parseXML(activity.getUrl());
if (text != null) {
initElements();
} else {
throw new Exception("File not found");
}
}
} else {
throw new Exception("ActivityId is required");
}
}
private void initElements() {
coreferent1 = new ArrayList<Coreferent>();
coreferent2 = new ArrayList<Coreferent>();
coreferent3 = new ArrayList<Coreferent>();
lastColor = "black";
HashSet<String> coreferentColorsSet = new HashSet<String>(colorCoRef.length);
coreferentColors = new HashSet<String>(colorCoRef.length);
this.rightAnswers = 0;
List<ElementXML> elements = getTitleElems();
List<ElementXML> sousTitreOrParagraphe = text.getContenu().getSousTitreOrParagraphe();
for (ElementXML elementXML : sousTitreOrParagraphe) {
if (elementXML.isSousTitre()) {
elements.addAll(getSubtitleElems(elementXML));
}
if (elementXML.isParagraphe()) {
elements.addAll(getParagraphElems(elementXML));
}
}
for (ElementXML elementXML : elements) {
if (elementXML.isReferent()) {
String idn = ((Referent) elementXML).getIdn();
if (idn.equals(R1)) {
setReferent1((Referent) elementXML);
} else if (idn.equals(R2)) {
setReferent2((Referent) elementXML);
} else if (idn.equals(R3)) {
rightAnswers += 1;
}
} else if (elementXML.isCoreferent()) {
String chaine = (String) ((Coreferent) elementXML).getChaine();
if (chaine.equals(R1)) {
coreferent1.add((Coreferent) elementXML);
coreferentColorsSet.add(getCoRefColor(chaine, ((Coreferent) elementXML).getIdn()));
} else if (chaine.equals(R2)) {
coreferent2.add((Coreferent) elementXML);
coreferentColorsSet.add(getCoRefColor(chaine, ((Coreferent) elementXML).getIdn()));
} else if (chaine.equals(R3)) {
coreferent3.add((Coreferent) elementXML);
coreferentColorsSet.add(getCoRefColor(chaine, ((Coreferent) elementXML).getIdn()));
}
}
}
for (String color : coreferentColorsSet) {
coreferentColors.add(color);
}
}
public List<ElementXML> getTitleElems() {
List<ElementXML> elems = new ArrayList<ElementXML>();
if (text != null && text.getContenu().getTitre() != null) {
List<Phrase> phrases = text.getContenu().getTitre().getPhrase();
for (Phrase phrase : phrases) {
addPhraseElems(phrase, elems);
}
}
return elems;
}
private void addPhraseElems(Phrase phrase, List<ElementXML> elems) {
List<ElementXML> propOrElement = phrase.getPropOrElement();
for (ElementXML elementXML : propOrElement) {
if (elementXML.isProp()) {
List<ElementXML> propElems = getPropElems(elementXML);
elems.addAll(propElems);
} else if (elementXML.isElem()) {
elems.add(elementXML);
}
}
}
private List<ElementXML> getPropElems(ElementXML prop) {
List<ElementXML> elems = new ArrayList<ElementXML>();
if (prop != null) {
List<ElementXML> propElems = ((Prop) prop).getReferentOrCoreferentOrElementOrProp();
for (ElementXML elementXML : propElems) {
if (elementXML.isProp()) {
List<ElementXML> subPropElems = getPropElems(elementXML);
elems.addAll(subPropElems);
} else {
elems.add(elementXML);
}
}
}
return elems;
}
public List<ElementXML> getSubtitleElems(ElementXML subtitle) {
List<ElementXML> elems = new ArrayList<ElementXML>();
if (subtitle != null) {
List<Phrase> phrases = ((SousTitre) subtitle).getPhrase();
for (Phrase phrase : phrases) {
addPhraseElems(phrase, elems);
}
}
return elems;
}
public List<ElementXML> getParagraphElems(ElementXML paragraph) {
List<ElementXML> elems = new ArrayList<ElementXML>();
if (paragraph != null) {
List<ElementXML> phraseOrElement = ((Paragraphe) paragraph).getPhraseOrElement();
for (ElementXML elementXML : phraseOrElement) {
if (elementXML.isElem()) {
elems.add(elementXML);
} else {
addPhraseElems((Phrase) elementXML, elems);
}
}
}
return elems;
}
public String getElementsFromReferent(ElementXML element) {
String elements = new String();
List<Element> elems = null;
if (element.isReferent()) {
elems = ((Referent) element).getElement();
} else if (element.isCoreferent()) {
elems = ((Coreferent) element).getElement();
}
for (Element el : elems) {
elements = elements.concat(el.getvalue() + " ");
}
return elements;
}
public String getRefColor(String idn) {
String[] split = idn.split("r");
int id = Integer.parseInt(split[1]);
if (id > 3) {
id = 0;
}
return colorRef[id];
}
public String getCoRefColor(String ref, String idn) {
String[] split = ref.split("r");
int id = Integer.parseInt(split[1]);
if (id > 3) {
id = 0;
}
return colorCoRef[id];
}
/**
* Get a list of coreferents depending if ref is R1, R2 or R3
*
* @param idn a list, null if idn not valid
* @return
*/
public List<Coreferent> getCoreferentsByIdn(String idn) {
List<Coreferent> ret = null;
if (idn.equals(R1)) {
ret = coreferent1;
} else if (idn.equals(R2)) {
ret = coreferent2;
} else if (idn.equals(R3)) {
ret = coreferent3;
}
return ret;
}
/**
* Look if the chaine is R1, R2 or R3
*
* @param chaine
* @return
*/
public boolean isRightCoreferent(String chaine) {
return chaine.equals(R1) || chaine.equals(R2) || chaine.equals(R3);
}
/**
* Encodes the passed String as UTF-8 using an algorithm that's compatible
* with JavaScript's encodeURIComponent function. Returns null if the String
* is null.
*
* @param s
* @return
*/
public static String encodeAsURI(String s) {
String res = null;
try {
res = URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(SystematizationActivityBean2.class.getName()).log(Level.SEVERE, null, ex);
res = s;
}
return res;
}
public ActivityVo getActivity() {
return activity;
}
public void setActivity(ActivityVo activity) {
this.activity = activity;
}
public Integer getIdSequence() {
return idSequence;
}
public void setIdSequence(Integer idSequence) {
this.idSequence = idSequence;
}
public DocumentTexte getText() {
return text;
}
public void setText(DocumentTexte text) {
this.text = text;
}
public Referent getReferent1() {
return referent1;
}
public void setReferent1(Referent referent1) {
this.referent1 = referent1;
}
public Referent getReferent2() {
return referent2;
}
public void setReferent2(Referent referent2) {
this.referent2 = referent2;
}
public List<Coreferent> getCoreferent1() {
return coreferent1;
}
public void setCoreferent1(List<Coreferent> coreferent1) {
this.coreferent1 = coreferent1;
}
public List<Coreferent> getCoreferent2() {
return coreferent2;
}
public void setCoreferent2(List<Coreferent> coreferent2) {
this.coreferent2 = coreferent2;
}
public List<Coreferent> getCoreferent3() {
return coreferent3;
}
public void setCoreferent3(List<Coreferent> coreferent3) {
this.coreferent3 = coreferent3;
}
public Set<String> getCoreferentColors() {
return coreferentColors;
}
public void setCoreferentColors(Set<String> coreferentColors) {
this.coreferentColors = coreferentColors;
}
public String getLastColor() {
return lastColor;
}
public void setLastColor(String lastColor) {
this.lastColor = lastColor;
}
public String getR3() {
return R3;
}
public String getR2() {
return R2;
}
public String getR1() {
return R1;
}
public int getRightAnswers() {
return rightAnswers;
}
public String lastColor() {
return lastColor;
}
public String encodeString(String s) {
String result = null;
try {
result = URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(SystematizationActivityBean2.class.getName()).log(Level.SEVERE, null, ex);
result = s;
}
return result;
}
public List randomizeCollection(List l) {
Collections.shuffle(l);
return l;
}
}
|
UnalSoft/elite-fle
|
src/main/java/com/unalsoft/elitefle/presentation/controller/SystematizationActivityBean2.java
|
Java
|
mit
| 11,623
|
//
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: android/libcore/luni/src/main/java/java/io/LineNumberReader.java
//
#ifndef _JavaIoLineNumberReader_H_
#define _JavaIoLineNumberReader_H_
#include "J2ObjC_header.h"
#include "java/io/BufferedReader.h"
@class IOSCharArray;
@class JavaIoReader;
/*!
@brief Wraps an existing <code>Reader</code> and counts the line terminators encountered
while reading the data.
The line number starts at 0 and is incremented any
time <code>'\r'</code>, <code>'\n'</code> or <code>"\r\n"</code> is read. The class has an
internal buffer for its data. The size of the buffer defaults to 8 KB.
*/
@interface JavaIoLineNumberReader : JavaIoBufferedReader
#pragma mark Public
/*!
@brief Constructs a new LineNumberReader on the Reader <code>in</code>.
The internal
buffer gets the default size (8 KB).
@param inArg
the Reader that is buffered.
*/
- (instancetype)initWithJavaIoReader:(JavaIoReader *)inArg;
/*!
@brief Constructs a new LineNumberReader on the Reader <code>in</code>.
The size of
the internal buffer is specified by the parameter <code>size</code>.
@param inArg
the Reader that is buffered.
@param size
the size of the buffer to allocate.
@throws IllegalArgumentException
if <code>size <= 0</code>.
*/
- (instancetype)initWithJavaIoReader:(JavaIoReader *)inArg
withInt:(jint)size;
/*!
@brief Returns the current line number for this reader.
Numbering starts at 0.
@return the current line number.
*/
- (jint)getLineNumber;
/*!
@brief Sets a mark position in this reader.
The parameter <code>readlimit</code>
indicates how many characters can be read before the mark is invalidated.
Sending <code>reset()</code> will reposition this reader back to the marked
position, provided that <code>readlimit</code> has not been surpassed. The
line number associated with this marked position is also stored so that
it can be restored when <code>reset()</code> is called.
@param readlimit
the number of characters that can be read from this stream
before the mark is invalidated.
@throws IOException
if an error occurs while setting the mark in this reader.
*/
- (void)markWithInt:(jint)readlimit;
/*!
@brief Reads a single character from the source reader and returns it as an
integer with the two higher-order bytes set to 0.
Returns -1 if the end
of the source reader has been reached.
<p>
The line number count is incremented if a line terminator is encountered.
Recognized line terminator sequences are <code>'\r'</code>, <code>'\n'</code> and
<code>"\r\n"</code>. Line terminator sequences are always translated into
<code>'\n'</code>.
@return the character read or -1 if the end of the source reader has been
reached.
@throws IOException
if the reader is closed or another IOException occurs.
*/
- (jint)read;
/*!
@brief Reads at most <code>count</code> characters from the source reader and stores
them in the character array <code>buffer</code> starting at <code>offset</code>.
Returns the number of characters actually read or -1 if no characters
have been read and the end of this reader has been reached.
<p>
The line number count is incremented if a line terminator is encountered.
Recognized line terminator sequences are <code>'\r'</code>, <code>'\n'</code> and
<code>"\r\n"</code>.
@param buffer
the array in which to store the characters read.
@param offset
the initial position in <code>buffer</code> to store the characters
read from this reader.
@param count
the maximum number of characters to store in <code>buffer</code>.
@return the number of characters actually read or -1 if the end of the
source reader has been reached while reading.
@throws IOException
if this reader is closed or another IOException occurs.
*/
- (jint)readWithCharArray:(IOSCharArray *)buffer
withInt:(jint)offset
withInt:(jint)count;
/*!
@brief Returns the next line of text available from this reader.
A line is
represented by 0 or more characters followed by <code>'\r'</code>,
<code>'\n'</code>, <code>"\r\n"</code> or the end of the stream. The returned
string does not include the newline sequence.
@return the contents of the line or <code>null</code> if no characters have
been read before the end of the stream has been reached.
@throws IOException
if this reader is closed or another IOException occurs.
*/
- (NSString *)readLine;
/*!
@brief Resets this reader to the last marked location.
It also resets the line
count to what is was when this reader was marked. This implementation
resets the source reader.
@throws IOException
if this reader is already closed, no mark has been set or the
mark is no longer valid because more than <code>readlimit</code>
bytes have been read since setting the mark.
*/
- (void)reset;
/*!
@brief Sets the line number of this reader to the specified <code>lineNumber</code>.
Note that this may have side effects on the line number associated with
the last marked position.
@param lineNumber
the new line number value.
*/
- (void)setLineNumberWithInt:(jint)lineNumber;
/*!
@brief Skips <code>charCount</code> characters in this reader.
Subsequent calls to
<code>read</code> will not return these characters unless <code>reset</code>
is used. This implementation skips <code>charCount</code> number of characters in
the source reader and increments the line number count whenever line
terminator sequences are skipped.
@return the number of characters actually skipped.
@throws IllegalArgumentException
if <code>charCount < 0</code>.
@throws IOException
if this reader is closed or another IOException occurs.
*/
- (jlong)skipWithLong:(jlong)charCount;
@end
J2OBJC_EMPTY_STATIC_INIT(JavaIoLineNumberReader)
FOUNDATION_EXPORT void JavaIoLineNumberReader_initWithJavaIoReader_(JavaIoLineNumberReader *self, JavaIoReader *inArg);
FOUNDATION_EXPORT JavaIoLineNumberReader *new_JavaIoLineNumberReader_initWithJavaIoReader_(JavaIoReader *inArg) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT void JavaIoLineNumberReader_initWithJavaIoReader_withInt_(JavaIoLineNumberReader *self, JavaIoReader *inArg, jint size);
FOUNDATION_EXPORT JavaIoLineNumberReader *new_JavaIoLineNumberReader_initWithJavaIoReader_withInt_(JavaIoReader *inArg, jint size) NS_RETURNS_RETAINED;
J2OBJC_TYPE_LITERAL_HEADER(JavaIoLineNumberReader)
#endif // _JavaIoLineNumberReader_H_
|
benf1977/j2objc-serialization-example
|
j2objc/include/java/io/LineNumberReader.h
|
C
|
mit
| 6,426
|
import numpy as np
class Site(object):
"""A class for general single site
Use this class to create a single site object. The site comes with identity
operator for a given dimension. To build specific site, additional operators
need be add with add_operator method.
"""
def __init__(self, dim):
"""Creates an empty site of dimension dim.
Parameters
----------
dim : an int
Size of the Hilbert space for single site. The dimension must be at
least 1. A site of dim = 1 is trival which represents the vaccum
operators : a dictionary of string and numpy array (with ndim = 2).
Operators for the site.
"""
super(Site, self).__init__()
self.dim = dim
self.states = {}
self.operators = { "id" : np.eye(self.dim, self.dim) }
def add_operator(self, operator_name):
"""Adds an operator to the site with zero matrix.
Parameters
----------
operator_name : string
The operator name.
"""
self.operators[str(operator_name)] = np.zeros((self.dim, self.dim))
def add_state(self, state_name):
"""Adds an state to the site with zero list.
Parameters
----------
operator_name : string
The operator name.
"""
self.states[str(state_name)] = np.zeros(self.dim)
class SpinlessFermionSite(Site):
"""A site for spinless fermion models.
Use this class for spinless fermion sites. The Hilbert space is ordered
such as:
- the first state is empty site
- the second state is occupied site.
Notes
-----
Postcondition : The site has already built-in the operators for
c, c_dag, n.
"""
def __init__(self):
"""Creates the spin one-half site.
Notes
-----
Postcond : the dimension is set to 2
"""
super(SpinlessFermionSite, self).__init__(2)
# add the operators
self.add_operator("c")
self.add_operator("c_dag")
self.add_operator("n")
# for clarity
c = self.operators["c"]
c_dag = self.operators["c_dag"]
n = self.operators["n"]
# set the matrix elements different from zero to the right values
c[0, 1] = 1
c_dag[1, 0] = 1
n[1, 1] = 1
# add the states
self.add_state("empty")
self.add_state("occupied")
# for clarity
state_empty = self.states["empty"]
state_occupied = self.states["occupied"]
# set the list elements different from zero to the right values
state_empty[0] = 1.0
state_occupied[1] = 1.0
class SpinOneHalfSite(Site):
"""A site for spin 1/2 models.
Use this class for spin one-half sites. The Hilbert space is ordered
such as the first state is the spin down, and the second state is the
spin up.
Notes
-----
Postcondition : The site has already built-in the spin operators for
s_x, s_y, s_z, s_p, s_m.
"""
def __init__(self):
"""Creates the spin one-half site.
Notes
-----
Postcond : the dimension is set to 2
"""
super(SpinOneHalfSite, self).__init__(2)
# add the operators
self.add_operator("s_x")
self.add_operator("s_y")
self.add_operator("s_z")
self.add_operator("s_p")
self.add_operator("s_m")
# for clarity
s_x = self.operators["s_x"]
s_y = self.operators["s_y"]
s_y = s_y.astype(np.complex)
s_z = self.operators["s_z"]
s_p = self.operators["s_p"]
s_m = self.operators["s_m"]
# set the matrix elements different from zero to the right values
s_x[0, 1] = 0.5
s_x[1, 0] = 0.5
s_y[0, 1] = 1j*(-0.5)
s_y[1, 0] = 1j*0.5
s_z[0, 0] = -0.5
s_z[1, 1] = 0.5
s_p[1, 0] = 1.0
s_m[0, 1] = 1.0
# add the states
self.add_state("spin_up")
self.add_state("spin_down")
self.add_state("empty")
self.add_state("occupied")
# for clarity
state_up = self.states["spin_up"]
state_down = self.states["spin_down"]
state_empty = self.states["empty"]
state_occupied = self.states["occupied"]
# set the list elements different from zero to the right values
state_up[1] = 1.0
state_down[0] = 1.0
state_occupied[1] = 1.0
state_empty[0] = 1.0
class ElectronicSite(Site):
"""A site for electronic models
You use this site for models where the single sites are electron
sites. The Hilbert space is ordered such as:
- the first state, labelled 0, is the empty site,
- the second, labelled 1, is spin down,
- the third, labelled 2, is spin up, and
- the fourth, labelled 3, is double occupancy.
Notes
-----
Postcond: The site has already built-in the spin operators for:
- c_up : destroys an spin up electron,
- c_up_dag, creates an spin up electron,
- c_down, destroys an spin down electron,
- c_down_dag, creates an spin down electron,
- s_z, component z of spin,
- s_p, raises the component z of spin,
- s_m, lowers the component z of spin,
- n_up, number of electrons with spin up,
- n_down, number of electrons with spin down,
- n, number of electrons, i.e. n_up+n_down, and
- u, number of double occupancies, i.e. n_up*n_down.
"""
def __init__(self):
super(ElectronicSite, self).__init__(4)
# add the operators
self.add_operator("c_up")
self.add_operator("c_up_dag")
self.add_operator("c_down")
self.add_operator("c_down_dag")
self.add_operator("s_z")
self.add_operator("n_up")
self.add_operator("n_down")
self.add_operator("n")
self.add_operator("u")
# for clarity
c_up = self.operators["c_up"]
c_up_dag = self.operators["c_up_dag"]
c_down = self.operators["c_down"]
c_down_dag = self.operators["c_down_dag"]
s_z = self.operators["s_z"]
n_up = self.operators["n_up"]
n_down = self.operators["n_down"]
n = self.operators["n"]
u = self.operators["u"]
# set the matrix elements different from zero to the right values
c_up[0,2] = 1.0
c_up[1,3] = 1.0
c_up_dag[2,0] = 1.0
c_up_dag[3,1] = 1.0
c_down[0,1] = 1.0
c_down[2,3] = 1.0
c_down_dag[1,0] = 1.0
c_down_dag[3,2] = 1.0
s_z[1,1] = -1.0
s_z[2,2] = 1.0
n_up[2,2] = 1.0
n_up[3,3] = 1.0
n_down[1,1] = 1.0
n_down[3,3] = 1.0
n[1,1] = 1.0
n[2,2] = 1.0
n[3,3] = 2.0
u[3,3] = 1.0
# add the states
self.add_state("empty")
self.add_state("spin_down")
self.add_state("spin_up")
self.add_state("double")
# for clarity
state_empty = self.states["empty"]
state_down = self.states["spin_down"]
state_up = self.states["spin_up"]
state_double = self.states["double"]
# set the list elements different from zero to the right values
state_empty[0] = 1.0
state_down[1] = 1.0
state_up[2] = 1.0
state_double[3] = 1.0
|
fhqgfss/MoHa
|
moha/modelsystem/sites.py
|
Python
|
mit
| 7,169
|
'use strict';
var flight;
function coerceToInt(number) {
if (number === 'NA') {
return null;
}
var int = parseInt(number);
if (isNaN(int)) {
return null;
} else {
return int;
}
}
// http://www.epochconverter.com/
// http://momentjs.com
var beginningOf2001 = moment('2001-01-01');
var beginningOf2002 = moment('2002-01-01');
var months = [beginningOf2001];
var weeks = [beginningOf2001];
for (var i = 1; i <= 11; i++) {
var nextMonth = beginningOf2001.clone().add(i, 'months');
months.push(nextMonth);
}
const monthNames = months.map(month => month.format('MMMM'));
// https://developer.mozilla.org/en/docs/Web/HTML/Element/select
const timeRangeMonthDisplay = document.querySelector('#time-range-month');
monthNames.forEach((name, index) => {
const option = document.createElement('option');
option.setAttribute('value', index);
option.appendChild(document.createTextNode(name));
timeRangeMonthDisplay.appendChild(option);
});
timeRangeMonthDisplay.addEventListener('change', event => {
const selectedMonth = event.target.value;
if (selectedMonth != -1) {
handleRangeChangeMonth(selectedMonth);
}
});
for (var i = 1; i <= 51; i++) {
var nextWeek = beginningOf2001.clone().add(i, 'weeks');
if ( nextWeek.isAfter(beginningOf2002) ) {
break;
}
weeks.push(nextWeek);
}
const weekNames = weeks.map(week => week.format('Wo'));
const timeRangeWeekDisplay = document.querySelector('#time-range-week');
weekNames.forEach((name, index) => {
const option = document.createElement('option');
option.setAttribute('value', index);
option.appendChild(document.createTextNode(name));
timeRangeWeekDisplay.appendChild(option);
});
timeRangeWeekDisplay.addEventListener('change', event => {
const selectedWeek = event.target.value;
if (selectedWeek != -1) {
handleRangeChangeWeek(selectedWeek);
}
});
var dayInMS = +moment.duration(1, 'day');
var weekInMS = +moment.duration(1, 'week');
var beginningOfSeptember = +months[8];
var beginningOfOctober = +months[9];
// var endOf2001 = 1009839600000;
// var allOf2001 = endOf2001 - beginningOf2001;
// var beginningOfFebruary = beginningOf2001 + 31 * dayInMS;
// var beginningOfMarch = beginningOfFebruary + 28 * dayInMS;
// var beginningOfApril = beginningOfMarch + 31 * dayInMS;
// var beginningOfMai = beginningOfApril + 30 * dayInMS;
// var beginningOfMonths = [beginningOf2001, beginningOfFebruary, beginningOfMarch, beginningOfApril];
var createQuery = function (fields, from, to) {
// reduced data
from = from || beginningOfSeptember + 1 * weekInMS;
to = to || beginningOfSeptember + 2 * weekInMS;
// from = from || beginningOfSeptember;
// to = to || beginningOfOctober;
// set index.max_result_window in elasticsearch.yml to 1000000 to allow for large result sets
return {
"size": 500000,
"query": {
"filtered": {
"query": {
"query_string": {
"query": "Cancelled: false",
"analyze_wildcard": true
}
},
"filter": {
"bool": {
"must": [
{
"range": {
"@timestamp": {
"gte": from,
"lte": to,
"format": "epoch_millis"
}
}
}
],
"must_not": []
}
}
}
},
"aggs": {},
"fields": fields
};
}
function unwrap(hit, fields) {
const unwrapped = {};
fields.forEach((field) => {
unwrapped[field] = hit.fields[field][0]
});
return unwrapped;
}
function handleRangeChangeMonth(monthIndex) {
const month = months[monthIndex];
document.querySelector('#time-range-name').innerHTML = monthNames[monthIndex];
const from = +month;
const to = +month.clone().add(1, 'month');
load((cf) => render(cf, from, to, 31), from, to);
}
function handleRangeChangeWeek(weekIndex) {
const week = weeks[weekIndex];
document.querySelector('#time-range-name').innerHTML = `${weekNames[weekIndex]} week of`;
const from = +week;
const to = +week.clone().add(1, 'week');
load((cf) => render(cf, from, to, 7), from, to);
}
function load(callback, from, to) {
signalLoadingStart();
const fields = ["Year", "Month", "DayofMonth", "Origin", "Dest", "UniqueCarrier"];
const query = createQuery(fields, from, to);
// be sure to enable CORS in elasticsearch
// https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-http.html
// fetch('http://localhost:9200/expo2009_airline/_search', {
fetch('http://localhost:9200/expo2009_pandas/_search', {
method: 'POST',
//mode: 'no-cors', // we need cors, otherwise we get no response back
body: JSON.stringify(query),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then((response) => {
return response.json();
}).catch((ex) => {
console.error('parsing failed', ex);
}).then(data => handleData(data, fields, callback));
}
function handleData(data, fields, callback) {
console.log('Loading done');
console.log(new Date());
//console.log(data);
console.log(data.hits.total);
console.log(data.hits.hits[0]);
const flights = data.hits.hits.map((hit) => unwrap(hit, fields));
//console.log(flights);
console.log(flights[0]);
d3.json("helper_data/airports_by_state.json", function (airportsArray) {
// make airports a map using airport code as key
var airports = {};
airportsArray.forEach(function (airport) {
airports[airport.airport] = airport;
});
// FCA missing in data set
// https://en.wikipedia.org/wiki/Glacier_Park_International_Airport
// https://en.wikipedia.org/wiki/List_of_U.S._state_abbreviations
var fca = {
airport: 'FCA',
name: 'Glacier Park International Airport',
state: 'MT'
};
airports[fca.airport] = fca;
// MQT missing in data set
// https://en.wikipedia.org/wiki/Sawyer_International_Airport
var mqt = {
airport: 'MQT',
name: 'Sawyer International Airport',
state: 'MI'
};
airports[mqt.airport] = mqt;
console.log('Adding state information');
// add state of origin and departure using airport code
flights.forEach(function (flight) {
if (airports[flight.Origin]) {
flight.stateOrigin = airports[flight.Origin].state;
} else {
flight.stateOrigin = 'N/A';
console.warn('Missing airport code', flight.Origin);
}
if (airports[flight.Dest]) {
flight.stateDest = airports[flight.Dest].state;
} else {
flight.stateDest = 'N/A';
console.warn('Missing airport code', flight.Dest);
}
});
console.log('Done');
console.log('Processed flight:');
console.log(flights[0]);
flight = crossfilter(flights);
console.log('Conversion done');
console.log(new Date());
callback && callback(flight);
});
}
|
DJCordhose/big-data-visualization
|
code/flights-from-es.js
|
JavaScript
|
mit
| 7,716
|
var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
var sass = require('gulp-sass');
var compass = require('gulp-compass');
var watch = require('gulp-watch');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
// Load all gulp plugins automatically
// and attach them to the `plugins` object
var plugins = require('gulp-load-plugins')();
// Temporary solution until gulp 4
// https://github.com/gulpjs/gulp/issues/355
var runSequence = require('run-sequence');
var pkg = require('./package.json');
var dirs = pkg['h5bp-configs'].directories;
// ---------------------------------------------------------------------
// | Helper tasks |
// ---------------------------------------------------------------------
gulp.task('archive:create_archive_dir', function () {
fs.mkdirSync(path.resolve(dirs.archive), '0755');
});
gulp.task('archive:zip', function (done) {
var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip');
var archiver = require('archiver')('zip');
var files = require('glob').sync('**/*.*', {
'cwd': dirs.dist,
'dot': true // include hidden files
});
var output = fs.createWriteStream(archiveName);
archiver.on('error', function (error) {
done();
throw error;
});
output.on('close', done);
files.forEach(function (file) {
var filePath = path.resolve(dirs.dist, file);
// `archiver.bulk` does not maintain the file
// permissions, so we need to add files individually
archiver.append(fs.createReadStream(filePath), {
'name': file,
'mode': fs.statSync(filePath).mode
});
});
archiver.pipe(output);
archiver.finalize();
});
gulp.task('clean', function (done) {
require('del')([
dirs.archive,
dirs.dist
]).then(function () {
done();
});
});
gulp.task('copy', [
'copy:.htaccess',
'copy:index.html',
'copy:jquery',
'copy:license',
'copy:normalize',
'copy:image',
'copy:rangeslider',
'copy:misc'
]);
gulp.task('copy:.htaccess', function () {
return gulp.src('node_modules/apache-server-configs/dist/.htaccess')
.pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument'))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:rangeslider', function () {
return gulp.src(['node_modules/rangeslider.js/dist/rangeslider.min.js'])
.pipe(gulp.dest(dirs.dist + '/vendor'));
});
gulp.task('copy:index.html', function () {
return gulp.src(dirs.app + '/index.html')
.pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:jquery', function () {
return gulp.src(['node_modules/jquery/dist/jquery.min.js'])
.pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js'))
.pipe(gulp.dest(dirs.dist + '/js/vendor'));
});
gulp.task('copy:license', function () {
return gulp.src('LICENSE.txt')
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:image', function () {
return gulp.src(dirs.app + '/img/**/*')
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:misc', function () {
return gulp.src([
// Copy all files
dirs.app + '/**/*',
// Exclude the following files
// (other tasks will handle the copying of these files)
'!' + dirs.app + '/css/main.css',
'!' + dirs.app + '/index.html',
'!' + dirs.app + '/scss/**/*',
'!' + dirs.app + '/js/**/*'
], {
// Include hidden files by default
dot: true
}).pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:normalize', function () {
return gulp.src('node_modules/normalize.css/normalize.css')
.pipe(gulp.dest(dirs.dist + '/css'));
});
//WE'RE JUST NOT GONNA LINT -- SORRY
gulp.task('lint:js', function () {
return gulp.src([
'gulpfile.js',
dirs.app + '/js/*.js',
dirs.test + '/*.js'
]).pipe(plugins.jscs())
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter('jshint-stylish'))
.pipe(plugins.jshint.reporter('fail'));
});
gulp.task('jsprep', function () {
gutil.log(gutil.colors.grey('preparing JS for production'));
return gulp.src(dirs.app + '/js/**/*.js')
.pipe(concat('production.min.js'))
.pipe(uglify({mangle: true, compress: true}))
.pipe(gulp.dest(dirs.dist + '/js'))
});
gulp.task('compassify', function () {
gutil.log(gutil.colors.grey('running compass compile'));
return gulp.src(dirs.app + '/scss/**/*.scss')
.pipe(compass({
config_file: dirs.app + '/config.rb',
sass: dirs.app + '/scss',
css: dirs.dist + '/css'
}))
//ERROR LOGGING
.on('error', function(error) {
gutil.log(gutil.colors.red('ERROR --', error));
this.emit('end');
})
.pipe(plugins.autoprefixer({
browsers: ['last 2 versions', 'ie >= 8', '> 1%'],
cascade: false
}))
.pipe(gulp.dest(dirs.dist + '/css'))
.pipe(browserSync.stream());
});
// ---------------------------------------------------------------------
// | Main tasks |
// ---------------------------------------------------------------------
gulp.task('archive', function (done) {
runSequence(
'build',
'archive:create_archive_dir',
'archive:zip',
done);
});
gulp.task('build', function (done) {
runSequence(
['clean'],
'compassify',
'jsprep',
'copy',
done);
});
gulp.task('serve', function () {
browserSync.init({
server: {
baseDir: "dist"
}
});
//gulp.watch(dirs.app + '/scss/**/*.scss', ['sassify']);
gulp.watch(dirs.app + '/scss/**/*.scss', ['compassify']);
//WATCH EVERYTHING ELSE
gulp.watch(dirs.app + '/js/**', ['jsprep']);
gulp.watch(dirs.app + '/index.html', ['copy']);
gulp.watch(dirs.app + '/img/**/*', ['copy']);
gulp.watch(dirs.dist + '/index.html').on('change', browserSync.reload);
gulp.watch(dirs.dist + '/js/**').on('change', browserSync.reload);
});
gulp.task('default', ['build']);
|
celsowhite/hsss_landing
|
gulpfile.js
|
JavaScript
|
mit
| 6,441
|
<?php
/**
* Pure-PHP X.509 Parser
*
* PHP version 5
*
* Encode and decode X.509 certificates.
*
* The extensions are from {@link http://tools.ietf.org/html/rfc5280 RFC5280} and
* {@link http://web.archive.org/web/19961027104704/http://www3.netscape.com/eng/security/cert-exts.html Netscape Certificate Extensions}.
*
* Note that loading an X.509 certificate and resaving it may invalidate the signature. The reason being that the signature is based on a
* portion of the certificate that contains optional parameters with default values. ie. if the parameter isn't there the default value is
* used. Problem is, if the parameter is there and it just so happens to have the default value there are two ways that that parameter can
* be encoded. It can be encoded explicitly or left out all together. This would effect the signature value and thus may invalidate the
* the certificate all together unless the certificate is re-signed.
*
* @category File
* @package X509
* @author Jim Wigginton <terrafrost@php.net>
* @copyright 2012 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
*/
namespace Msulistijo\PhpseclibBundle\File;
use Msulistijo\PhpseclibBundle\Crypt\Hash;
use Msulistijo\PhpseclibBundle\Crypt\RSA;
use Msulistijo\PhpseclibBundle\Crypt\Random;
use Msulistijo\PhpseclibBundle\File\ASN1;
use Msulistijo\PhpseclibBundle\File\ASN1\Element;
use Msulistijo\PhpseclibBundle\Math\BigInteger;
use Msulistijo\PhpseclibBundle\Exception\UnsupportedAlgorithmException;
/**
* Pure-PHP X.509 Parser
*
* @package X509
* @author Jim Wigginton <terrafrost@php.net>
* @access public
*/
class X509
{
/**
* Flag to only accept signatures signed by certificate authorities
*
* Not really used anymore but retained all the same to suppress E_NOTICEs from old installs
*
* @access public
*/
const VALIDATE_SIGNATURE_BY_CA = 1;
/**#@+
* @access public
* @see \phpseclib\File\X509::getDN()
*/
/**
* Return internal array representation
*/
const DN_ARRAY = 0;
/**
* Return string
*/
const DN_STRING = 1;
/**
* Return ASN.1 name string
*/
const DN_ASN1 = 2;
/**
* Return OpenSSL compatible array
*/
const DN_OPENSSL = 3;
/**
* Return canonical ASN.1 RDNs string
*/
const DN_CANON = 4;
/**
* Return name hash for file indexing
*/
const DN_HASH = 5;
/**#@-*/
/**#@+
* @access public
* @see \phpseclib\File\X509::saveX509()
* @see \phpseclib\File\X509::saveCSR()
* @see \phpseclib\File\X509::saveCRL()
*/
/**
* Save as PEM
*
* ie. a base64-encoded PEM with a header and a footer
*/
const FORMAT_PEM = 0;
/**
* Save as DER
*/
const FORMAT_DER = 1;
/**
* Save as a SPKAC
*
* Only works on CSRs. Not currently supported.
*/
const FORMAT_SPKAC = 2;
/**
* Auto-detect the format
*
* Used only by the load*() functions
*/
const FORMAT_AUTO_DETECT = 3;
/**#@-*/
/**
* Attribute value disposition.
* If disposition is >= 0, this is the index of the target value.
*/
const ATTR_ALL = -1; // All attribute values (array).
const ATTR_APPEND = -2; // Add a value.
const ATTR_REPLACE = -3; // Clear first, then add a value.
/**
* ASN.1 syntax for X.509 certificates
*
* @var array
* @access private
*/
var $Certificate;
/**#@+
* ASN.1 syntax for various extensions
*
* @access private
*/
var $DirectoryString;
var $PKCS9String;
var $AttributeValue;
var $Extensions;
var $KeyUsage;
var $ExtKeyUsageSyntax;
var $BasicConstraints;
var $KeyIdentifier;
var $CRLDistributionPoints;
var $AuthorityKeyIdentifier;
var $CertificatePolicies;
var $AuthorityInfoAccessSyntax;
var $SubjectAltName;
var $PrivateKeyUsagePeriod;
var $IssuerAltName;
var $PolicyMappings;
var $NameConstraints;
var $CPSuri;
var $UserNotice;
var $netscape_cert_type;
var $netscape_comment;
var $netscape_ca_policy_url;
var $Name;
var $RelativeDistinguishedName;
var $CRLNumber;
var $CRLReason;
var $IssuingDistributionPoint;
var $InvalidityDate;
var $CertificateIssuer;
var $HoldInstructionCode;
var $SignedPublicKeyAndChallenge;
/**#@-*/
/**
* ASN.1 syntax for Certificate Signing Requests (RFC2986)
*
* @var array
* @access private
*/
var $CertificationRequest;
/**
* ASN.1 syntax for Certificate Revocation Lists (RFC5280)
*
* @var array
* @access private
*/
var $CertificateList;
/**
* Distinguished Name
*
* @var array
* @access private
*/
var $dn;
/**
* Public key
*
* @var string
* @access private
*/
var $publicKey;
/**
* Private key
*
* @var string
* @access private
*/
var $privateKey;
/**
* Object identifiers for X.509 certificates
*
* @var array
* @access private
* @link http://en.wikipedia.org/wiki/Object_identifier
*/
var $oids;
/**
* The certificate authorities
*
* @var array
* @access private
*/
var $CAs;
/**
* The currently loaded certificate
*
* @var array
* @access private
*/
var $currentCert;
/**
* The signature subject
*
* There's no guarantee \phpseclib\File\X509 is going to reencode an X.509 cert in the same way it was originally
* encoded so we take save the portion of the original cert that the signature would have made for.
*
* @var string
* @access private
*/
var $signatureSubject;
/**
* Certificate Start Date
*
* @var string
* @access private
*/
var $startDate;
/**
* Certificate End Date
*
* @var string
* @access private
*/
var $endDate;
/**
* Serial Number
*
* @var string
* @access private
*/
var $serialNumber;
/**
* Key Identifier
*
* See {@link http://tools.ietf.org/html/rfc5280#section-4.2.1.1 RFC5280#section-4.2.1.1} and
* {@link http://tools.ietf.org/html/rfc5280#section-4.2.1.2 RFC5280#section-4.2.1.2}.
*
* @var string
* @access private
*/
var $currentKeyIdentifier;
/**
* CA Flag
*
* @var bool
* @access private
*/
var $caFlag = false;
/**
* SPKAC Challenge
*
* @var string
* @access private
*/
var $challenge;
/**
* Default Constructor.
*
* @return \phpseclib\File\X509
* @access public
*/
function __construct()
{
// Explicitly Tagged Module, 1988 Syntax
// http://tools.ietf.org/html/rfc5280#appendix-A.1
$this->DirectoryString = array(
'type' => ASN1::TYPE_CHOICE,
'children' => array(
'teletexString' => array('type' => ASN1::TYPE_TELETEX_STRING),
'printableString' => array('type' => ASN1::TYPE_PRINTABLE_STRING),
'universalString' => array('type' => ASN1::TYPE_UNIVERSAL_STRING),
'utf8String' => array('type' => ASN1::TYPE_UTF8_STRING),
'bmpString' => array('type' => ASN1::TYPE_BMP_STRING)
)
);
$this->PKCS9String = array(
'type' => ASN1::TYPE_CHOICE,
'children' => array(
'ia5String' => array('type' => ASN1::TYPE_IA5_STRING),
'directoryString' => $this->DirectoryString
)
);
$this->AttributeValue = array('type' => ASN1::TYPE_ANY);
$AttributeType = array('type' => ASN1::TYPE_OBJECT_IDENTIFIER);
$AttributeTypeAndValue = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'type' => $AttributeType,
'value'=> $this->AttributeValue
)
);
/*
In practice, RDNs containing multiple name-value pairs (called "multivalued RDNs") are rare,
but they can be useful at times when either there is no unique attribute in the entry or you
want to ensure that the entry's DN contains some useful identifying information.
- https://www.opends.org/wiki/page/DefinitionRelativeDistinguishedName
*/
$this->RelativeDistinguishedName = array(
'type' => ASN1::TYPE_SET,
'min' => 1,
'max' => -1,
'children' => $AttributeTypeAndValue
);
// http://tools.ietf.org/html/rfc5280#section-4.1.2.4
$RDNSequence = array(
'type' => ASN1::TYPE_SEQUENCE,
// RDNSequence does not define a min or a max, which means it doesn't have one
'min' => 0,
'max' => -1,
'children' => $this->RelativeDistinguishedName
);
$this->Name = array(
'type' => ASN1::TYPE_CHOICE,
'children' => array(
'rdnSequence' => $RDNSequence
)
);
// http://tools.ietf.org/html/rfc5280#section-4.1.1.2
$AlgorithmIdentifier = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'algorithm' => array('type' => ASN1::TYPE_OBJECT_IDENTIFIER),
'parameters' => array(
'type' => ASN1::TYPE_ANY,
'optional' => true
)
)
);
/*
A certificate using system MUST reject the certificate if it encounters
a critical extension it does not recognize; however, a non-critical
extension may be ignored if it is not recognized.
http://tools.ietf.org/html/rfc5280#section-4.2
*/
$Extension = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'extnId' => array('type' => ASN1::TYPE_OBJECT_IDENTIFIER),
'critical' => array(
'type' => ASN1::TYPE_BOOLEAN,
'optional' => true,
'default' => false
),
'extnValue' => array('type' => ASN1::TYPE_OCTET_STRING)
)
);
$this->Extensions = array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 1,
// technically, it's MAX, but we'll assume anything < 0 is MAX
'max' => -1,
// if 'children' isn't an array then 'min' and 'max' must be defined
'children' => $Extension
);
$SubjectPublicKeyInfo = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'algorithm' => $AlgorithmIdentifier,
'subjectPublicKey' => array('type' => ASN1::TYPE_BIT_STRING)
)
);
$UniqueIdentifier = array('type' => ASN1::TYPE_BIT_STRING);
$Time = array(
'type' => ASN1::TYPE_CHOICE,
'children' => array(
'utcTime' => array('type' => ASN1::TYPE_UTC_TIME),
'generalTime' => array('type' => ASN1::TYPE_GENERALIZED_TIME)
)
);
// http://tools.ietf.org/html/rfc5280#section-4.1.2.5
$Validity = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'notBefore' => $Time,
'notAfter' => $Time
)
);
$CertificateSerialNumber = array('type' => ASN1::TYPE_INTEGER);
$Version = array(
'type' => ASN1::TYPE_INTEGER,
'mapping' => array('v1', 'v2', 'v3')
);
// assert($TBSCertificate['children']['signature'] == $Certificate['children']['signatureAlgorithm'])
$TBSCertificate = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
// technically, default implies optional, but we'll define it as being optional, none-the-less, just to
// reenforce that fact
'version' => array(
'constant' => 0,
'optional' => true,
'explicit' => true,
'default' => 'v1'
) + $Version,
'serialNumber' => $CertificateSerialNumber,
'signature' => $AlgorithmIdentifier,
'issuer' => $this->Name,
'validity' => $Validity,
'subject' => $this->Name,
'subjectPublicKeyInfo' => $SubjectPublicKeyInfo,
// implicit means that the T in the TLV structure is to be rewritten, regardless of the type
'issuerUniqueID' => array(
'constant' => 1,
'optional' => true,
'implicit' => true
) + $UniqueIdentifier,
'subjectUniqueID' => array(
'constant' => 2,
'optional' => true,
'implicit' => true
) + $UniqueIdentifier,
// <http://tools.ietf.org/html/rfc2459#page-74> doesn't use the EXPLICIT keyword but if
// it's not IMPLICIT, it's EXPLICIT
'extensions' => array(
'constant' => 3,
'optional' => true,
'explicit' => true
) + $this->Extensions
)
);
$this->Certificate = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'tbsCertificate' => $TBSCertificate,
'signatureAlgorithm' => $AlgorithmIdentifier,
'signature' => array('type' => ASN1::TYPE_BIT_STRING)
)
);
$this->KeyUsage = array(
'type' => ASN1::TYPE_BIT_STRING,
'mapping' => array(
'digitalSignature',
'nonRepudiation',
'keyEncipherment',
'dataEncipherment',
'keyAgreement',
'keyCertSign',
'cRLSign',
'encipherOnly',
'decipherOnly'
)
);
$this->BasicConstraints = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'cA' => array(
'type' => ASN1::TYPE_BOOLEAN,
'optional' => true,
'default' => false
),
'pathLenConstraint' => array(
'type' => ASN1::TYPE_INTEGER,
'optional' => true
)
)
);
$this->KeyIdentifier = array('type' => ASN1::TYPE_OCTET_STRING);
$OrganizationalUnitNames = array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 1,
'max' => 4, // ub-organizational-units
'children' => array('type' => ASN1::TYPE_PRINTABLE_STRING)
);
$PersonalName = array(
'type' => ASN1::TYPE_SET,
'children' => array(
'surname' => array(
'type' => ASN1::TYPE_PRINTABLE_STRING,
'constant' => 0,
'optional' => true,
'implicit' => true
),
'given-name' => array(
'type' => ASN1::TYPE_PRINTABLE_STRING,
'constant' => 1,
'optional' => true,
'implicit' => true
),
'initials' => array(
'type' => ASN1::TYPE_PRINTABLE_STRING,
'constant' => 2,
'optional' => true,
'implicit' => true
),
'generation-qualifier' => array(
'type' => ASN1::TYPE_PRINTABLE_STRING,
'constant' => 3,
'optional' => true,
'implicit' => true
)
)
);
$NumericUserIdentifier = array('type' => ASN1::TYPE_NUMERIC_STRING);
$OrganizationName = array('type' => ASN1::TYPE_PRINTABLE_STRING);
$PrivateDomainName = array(
'type' => ASN1::TYPE_CHOICE,
'children' => array(
'numeric' => array('type' => ASN1::TYPE_NUMERIC_STRING),
'printable' => array('type' => ASN1::TYPE_PRINTABLE_STRING)
)
);
$TerminalIdentifier = array('type' => ASN1::TYPE_PRINTABLE_STRING);
$NetworkAddress = array('type' => ASN1::TYPE_NUMERIC_STRING);
$AdministrationDomainName = array(
'type' => ASN1::TYPE_CHOICE,
// if class isn't present it's assumed to be \phpseclib\File\ASN1::CLASS_UNIVERSAL or
// (if constant is present) \phpseclib\File\ASN1::CLASS_CONTEXT_SPECIFIC
'class' => ASN1::CLASS_APPLICATION,
'cast' => 2,
'children' => array(
'numeric' => array('type' => ASN1::TYPE_NUMERIC_STRING),
'printable' => array('type' => ASN1::TYPE_PRINTABLE_STRING)
)
);
$CountryName = array(
'type' => ASN1::TYPE_CHOICE,
// if class isn't present it's assumed to be \phpseclib\File\ASN1::CLASS_UNIVERSAL or
// (if constant is present) \phpseclib\File\ASN1::CLASS_CONTEXT_SPECIFIC
'class' => ASN1::CLASS_APPLICATION,
'cast' => 1,
'children' => array(
'x121-dcc-code' => array('type' => ASN1::TYPE_NUMERIC_STRING),
'iso-3166-alpha2-code' => array('type' => ASN1::TYPE_PRINTABLE_STRING)
)
);
$AnotherName = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'type-id' => array('type' => ASN1::TYPE_OBJECT_IDENTIFIER),
'value' => array(
'type' => ASN1::TYPE_ANY,
'constant' => 0,
'optional' => true,
'explicit' => true
)
)
);
$ExtensionAttribute = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'extension-attribute-type' => array(
'type' => ASN1::TYPE_PRINTABLE_STRING,
'constant' => 0,
'optional' => true,
'implicit' => true
),
'extension-attribute-value' => array(
'type' => ASN1::TYPE_ANY,
'constant' => 1,
'optional' => true,
'explicit' => true
)
)
);
$ExtensionAttributes = array(
'type' => ASN1::TYPE_SET,
'min' => 1,
'max' => 256, // ub-extension-attributes
'children' => $ExtensionAttribute
);
$BuiltInDomainDefinedAttribute = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'type' => array('type' => ASN1::TYPE_PRINTABLE_STRING),
'value' => array('type' => ASN1::TYPE_PRINTABLE_STRING)
)
);
$BuiltInDomainDefinedAttributes = array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 1,
'max' => 4, // ub-domain-defined-attributes
'children' => $BuiltInDomainDefinedAttribute
);
$BuiltInStandardAttributes = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'country-name' => array('optional' => true) + $CountryName,
'administration-domain-name' => array('optional' => true) + $AdministrationDomainName,
'network-address' => array(
'constant' => 0,
'optional' => true,
'implicit' => true
) + $NetworkAddress,
'terminal-identifier' => array(
'constant' => 1,
'optional' => true,
'implicit' => true
) + $TerminalIdentifier,
'private-domain-name' => array(
'constant' => 2,
'optional' => true,
'explicit' => true
) + $PrivateDomainName,
'organization-name' => array(
'constant' => 3,
'optional' => true,
'implicit' => true
) + $OrganizationName,
'numeric-user-identifier' => array(
'constant' => 4,
'optional' => true,
'implicit' => true
) + $NumericUserIdentifier,
'personal-name' => array(
'constant' => 5,
'optional' => true,
'implicit' => true
) + $PersonalName,
'organizational-unit-names' => array(
'constant' => 6,
'optional' => true,
'implicit' => true
) + $OrganizationalUnitNames
)
);
$ORAddress = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'built-in-standard-attributes' => $BuiltInStandardAttributes,
'built-in-domain-defined-attributes' => array('optional' => true) + $BuiltInDomainDefinedAttributes,
'extension-attributes' => array('optional' => true) + $ExtensionAttributes
)
);
$EDIPartyName = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'nameAssigner' => array(
'constant' => 0,
'optional' => true,
'implicit' => true
) + $this->DirectoryString,
// partyName is technically required but \phpseclib\File\ASN1 doesn't currently support non-optional constants and
// setting it to optional gets the job done in any event.
'partyName' => array(
'constant' => 1,
'optional' => true,
'implicit' => true
) + $this->DirectoryString
)
);
$GeneralName = array(
'type' => ASN1::TYPE_CHOICE,
'children' => array(
'otherName' => array(
'constant' => 0,
'optional' => true,
'implicit' => true
) + $AnotherName,
'rfc822Name' => array(
'type' => ASN1::TYPE_IA5_STRING,
'constant' => 1,
'optional' => true,
'implicit' => true
),
'dNSName' => array(
'type' => ASN1::TYPE_IA5_STRING,
'constant' => 2,
'optional' => true,
'implicit' => true
),
'x400Address' => array(
'constant' => 3,
'optional' => true,
'implicit' => true
) + $ORAddress,
'directoryName' => array(
'constant' => 4,
'optional' => true,
'explicit' => true
) + $this->Name,
'ediPartyName' => array(
'constant' => 5,
'optional' => true,
'implicit' => true
) + $EDIPartyName,
'uniformResourceIdentifier' => array(
'type' => ASN1::TYPE_IA5_STRING,
'constant' => 6,
'optional' => true,
'implicit' => true
),
'iPAddress' => array(
'type' => ASN1::TYPE_OCTET_STRING,
'constant' => 7,
'optional' => true,
'implicit' => true
),
'registeredID' => array(
'type' => ASN1::TYPE_OBJECT_IDENTIFIER,
'constant' => 8,
'optional' => true,
'implicit' => true
)
)
);
$GeneralNames = array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 1,
'max' => -1,
'children' => $GeneralName
);
$this->IssuerAltName = $GeneralNames;
$ReasonFlags = array(
'type' => ASN1::TYPE_BIT_STRING,
'mapping' => array(
'unused',
'keyCompromise',
'cACompromise',
'affiliationChanged',
'superseded',
'cessationOfOperation',
'certificateHold',
'privilegeWithdrawn',
'aACompromise'
)
);
$DistributionPointName = array(
'type' => ASN1::TYPE_CHOICE,
'children' => array(
'fullName' => array(
'constant' => 0,
'optional' => true,
'implicit' => true
) + $GeneralNames,
'nameRelativeToCRLIssuer' => array(
'constant' => 1,
'optional' => true,
'implicit' => true
) + $this->RelativeDistinguishedName
)
);
$DistributionPoint = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'distributionPoint' => array(
'constant' => 0,
'optional' => true,
'explicit' => true
) + $DistributionPointName,
'reasons' => array(
'constant' => 1,
'optional' => true,
'implicit' => true
) + $ReasonFlags,
'cRLIssuer' => array(
'constant' => 2,
'optional' => true,
'implicit' => true
) + $GeneralNames
)
);
$this->CRLDistributionPoints = array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 1,
'max' => -1,
'children' => $DistributionPoint
);
$this->AuthorityKeyIdentifier = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'keyIdentifier' => array(
'constant' => 0,
'optional' => true,
'implicit' => true
) + $this->KeyIdentifier,
'authorityCertIssuer' => array(
'constant' => 1,
'optional' => true,
'implicit' => true
) + $GeneralNames,
'authorityCertSerialNumber' => array(
'constant' => 2,
'optional' => true,
'implicit' => true
) + $CertificateSerialNumber
)
);
$PolicyQualifierId = array('type' => ASN1::TYPE_OBJECT_IDENTIFIER);
$PolicyQualifierInfo = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'policyQualifierId' => $PolicyQualifierId,
'qualifier' => array('type' => ASN1::TYPE_ANY)
)
);
$CertPolicyId = array('type' => ASN1::TYPE_OBJECT_IDENTIFIER);
$PolicyInformation = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'policyIdentifier' => $CertPolicyId,
'policyQualifiers' => array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 0,
'max' => -1,
'optional' => true,
'children' => $PolicyQualifierInfo
)
)
);
$this->CertificatePolicies = array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 1,
'max' => -1,
'children' => $PolicyInformation
);
$this->PolicyMappings = array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 1,
'max' => -1,
'children' => array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'issuerDomainPolicy' => $CertPolicyId,
'subjectDomainPolicy' => $CertPolicyId
)
)
);
$KeyPurposeId = array('type' => ASN1::TYPE_OBJECT_IDENTIFIER);
$this->ExtKeyUsageSyntax = array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 1,
'max' => -1,
'children' => $KeyPurposeId
);
$AccessDescription = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'accessMethod' => array('type' => ASN1::TYPE_OBJECT_IDENTIFIER),
'accessLocation' => $GeneralName
)
);
$this->AuthorityInfoAccessSyntax = array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 1,
'max' => -1,
'children' => $AccessDescription
);
$this->SubjectAltName = $GeneralNames;
$this->PrivateKeyUsagePeriod = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'notBefore' => array(
'constant' => 0,
'optional' => true,
'implicit' => true,
'type' => ASN1::TYPE_GENERALIZED_TIME),
'notAfter' => array(
'constant' => 1,
'optional' => true,
'implicit' => true,
'type' => ASN1::TYPE_GENERALIZED_TIME)
)
);
$BaseDistance = array('type' => ASN1::TYPE_INTEGER);
$GeneralSubtree = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'base' => $GeneralName,
'minimum' => array(
'constant' => 0,
'optional' => true,
'implicit' => true,
'default' => new BigInteger(0)
) + $BaseDistance,
'maximum' => array(
'constant' => 1,
'optional' => true,
'implicit' => true,
) + $BaseDistance
)
);
$GeneralSubtrees = array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 1,
'max' => -1,
'children' => $GeneralSubtree
);
$this->NameConstraints = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'permittedSubtrees' => array(
'constant' => 0,
'optional' => true,
'implicit' => true
) + $GeneralSubtrees,
'excludedSubtrees' => array(
'constant' => 1,
'optional' => true,
'implicit' => true
) + $GeneralSubtrees
)
);
$this->CPSuri = array('type' => ASN1::TYPE_IA5_STRING);
$DisplayText = array(
'type' => ASN1::TYPE_CHOICE,
'children' => array(
'ia5String' => array('type' => ASN1::TYPE_IA5_STRING),
'visibleString' => array('type' => ASN1::TYPE_VISIBLE_STRING),
'bmpString' => array('type' => ASN1::TYPE_BMP_STRING),
'utf8String' => array('type' => ASN1::TYPE_UTF8_STRING)
)
);
$NoticeReference = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'organization' => $DisplayText,
'noticeNumbers' => array(
'type' => ASN1::TYPE_SEQUENCE,
'min' => 1,
'max' => 200,
'children' => array('type' => ASN1::TYPE_INTEGER)
)
)
);
$this->UserNotice = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'noticeRef' => array(
'optional' => true,
'implicit' => true
) + $NoticeReference,
'explicitText' => array(
'optional' => true,
'implicit' => true
) + $DisplayText
)
);
// mapping is from <http://www.mozilla.org/projects/security/pki/nss/tech-notes/tn3.html>
$this->netscape_cert_type = array(
'type' => ASN1::TYPE_BIT_STRING,
'mapping' => array(
'SSLClient',
'SSLServer',
'Email',
'ObjectSigning',
'Reserved',
'SSLCA',
'EmailCA',
'ObjectSigningCA'
)
);
$this->netscape_comment = array('type' => ASN1::TYPE_IA5_STRING);
$this->netscape_ca_policy_url = array('type' => ASN1::TYPE_IA5_STRING);
// attribute is used in RFC2986 but we're using the RFC5280 definition
$Attribute = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'type' => $AttributeType,
'value'=> array(
'type' => ASN1::TYPE_SET,
'min' => 1,
'max' => -1,
'children' => $this->AttributeValue
)
)
);
// adapted from <http://tools.ietf.org/html/rfc2986>
$Attributes = array(
'type' => ASN1::TYPE_SET,
'min' => 1,
'max' => -1,
'children' => $Attribute
);
$CertificationRequestInfo = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'version' => array(
'type' => ASN1::TYPE_INTEGER,
'mapping' => array('v1')
),
'subject' => $this->Name,
'subjectPKInfo' => $SubjectPublicKeyInfo,
'attributes' => array(
'constant' => 0,
'optional' => true,
'implicit' => true
) + $Attributes,
)
);
$this->CertificationRequest = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'certificationRequestInfo' => $CertificationRequestInfo,
'signatureAlgorithm' => $AlgorithmIdentifier,
'signature' => array('type' => ASN1::TYPE_BIT_STRING)
)
);
$RevokedCertificate = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'userCertificate' => $CertificateSerialNumber,
'revocationDate' => $Time,
'crlEntryExtensions' => array(
'optional' => true
) + $this->Extensions
)
);
$TBSCertList = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'version' => array(
'optional' => true,
'default' => 'v1'
) + $Version,
'signature' => $AlgorithmIdentifier,
'issuer' => $this->Name,
'thisUpdate' => $Time,
'nextUpdate' => array(
'optional' => true
) + $Time,
'revokedCertificates' => array(
'type' => ASN1::TYPE_SEQUENCE,
'optional' => true,
'min' => 0,
'max' => -1,
'children' => $RevokedCertificate
),
'crlExtensions' => array(
'constant' => 0,
'optional' => true,
'explicit' => true
) + $this->Extensions
)
);
$this->CertificateList = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'tbsCertList' => $TBSCertList,
'signatureAlgorithm' => $AlgorithmIdentifier,
'signature' => array('type' => ASN1::TYPE_BIT_STRING)
)
);
$this->CRLNumber = array('type' => ASN1::TYPE_INTEGER);
$this->CRLReason = array('type' => ASN1::TYPE_ENUMERATED,
'mapping' => array(
'unspecified',
'keyCompromise',
'cACompromise',
'affiliationChanged',
'superseded',
'cessationOfOperation',
'certificateHold',
// Value 7 is not used.
8 => 'removeFromCRL',
'privilegeWithdrawn',
'aACompromise'
)
);
$this->IssuingDistributionPoint = array('type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'distributionPoint' => array(
'constant' => 0,
'optional' => true,
'explicit' => true
) + $DistributionPointName,
'onlyContainsUserCerts' => array(
'type' => ASN1::TYPE_BOOLEAN,
'constant' => 1,
'optional' => true,
'default' => false,
'implicit' => true
),
'onlyContainsCACerts' => array(
'type' => ASN1::TYPE_BOOLEAN,
'constant' => 2,
'optional' => true,
'default' => false,
'implicit' => true
),
'onlySomeReasons' => array(
'constant' => 3,
'optional' => true,
'implicit' => true
) + $ReasonFlags,
'indirectCRL' => array(
'type' => ASN1::TYPE_BOOLEAN,
'constant' => 4,
'optional' => true,
'default' => false,
'implicit' => true
),
'onlyContainsAttributeCerts' => array(
'type' => ASN1::TYPE_BOOLEAN,
'constant' => 5,
'optional' => true,
'default' => false,
'implicit' => true
)
)
);
$this->InvalidityDate = array('type' => ASN1::TYPE_GENERALIZED_TIME);
$this->CertificateIssuer = $GeneralNames;
$this->HoldInstructionCode = array('type' => ASN1::TYPE_OBJECT_IDENTIFIER);
$PublicKeyAndChallenge = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'spki' => $SubjectPublicKeyInfo,
'challenge' => array('type' => ASN1::TYPE_IA5_STRING)
)
);
$this->SignedPublicKeyAndChallenge = array(
'type' => ASN1::TYPE_SEQUENCE,
'children' => array(
'publicKeyAndChallenge' => $PublicKeyAndChallenge,
'signatureAlgorithm' => $AlgorithmIdentifier,
'signature' => array('type' => ASN1::TYPE_BIT_STRING)
)
);
// OIDs from RFC5280 and those RFCs mentioned in RFC5280#section-4.1.1.2
$this->oids = array(
'1.3.6.1.5.5.7' => 'id-pkix',
'1.3.6.1.5.5.7.1' => 'id-pe',
'1.3.6.1.5.5.7.2' => 'id-qt',
'1.3.6.1.5.5.7.3' => 'id-kp',
'1.3.6.1.5.5.7.48' => 'id-ad',
'1.3.6.1.5.5.7.2.1' => 'id-qt-cps',
'1.3.6.1.5.5.7.2.2' => 'id-qt-unotice',
'1.3.6.1.5.5.7.48.1' =>'id-ad-ocsp',
'1.3.6.1.5.5.7.48.2' => 'id-ad-caIssuers',
'1.3.6.1.5.5.7.48.3' => 'id-ad-timeStamping',
'1.3.6.1.5.5.7.48.5' => 'id-ad-caRepository',
'2.5.4' => 'id-at',
'2.5.4.41' => 'id-at-name',
'2.5.4.4' => 'id-at-surname',
'2.5.4.42' => 'id-at-givenName',
'2.5.4.43' => 'id-at-initials',
'2.5.4.44' => 'id-at-generationQualifier',
'2.5.4.3' => 'id-at-commonName',
'2.5.4.7' => 'id-at-localityName',
'2.5.4.8' => 'id-at-stateOrProvinceName',
'2.5.4.10' => 'id-at-organizationName',
'2.5.4.11' => 'id-at-organizationalUnitName',
'2.5.4.12' => 'id-at-title',
'2.5.4.13' => 'id-at-description',
'2.5.4.46' => 'id-at-dnQualifier',
'2.5.4.6' => 'id-at-countryName',
'2.5.4.5' => 'id-at-serialNumber',
'2.5.4.65' => 'id-at-pseudonym',
'2.5.4.17' => 'id-at-postalCode',
'2.5.4.9' => 'id-at-streetAddress',
'2.5.4.45' => 'id-at-uniqueIdentifier',
'2.5.4.72' => 'id-at-role',
'0.9.2342.19200300.100.1.25' => 'id-domainComponent',
'1.2.840.113549.1.9' => 'pkcs-9',
'1.2.840.113549.1.9.1' => 'pkcs-9-at-emailAddress',
'2.5.29' => 'id-ce',
'2.5.29.35' => 'id-ce-authorityKeyIdentifier',
'2.5.29.14' => 'id-ce-subjectKeyIdentifier',
'2.5.29.15' => 'id-ce-keyUsage',
'2.5.29.16' => 'id-ce-privateKeyUsagePeriod',
'2.5.29.32' => 'id-ce-certificatePolicies',
'2.5.29.32.0' => 'anyPolicy',
'2.5.29.33' => 'id-ce-policyMappings',
'2.5.29.17' => 'id-ce-subjectAltName',
'2.5.29.18' => 'id-ce-issuerAltName',
'2.5.29.9' => 'id-ce-subjectDirectoryAttributes',
'2.5.29.19' => 'id-ce-basicConstraints',
'2.5.29.30' => 'id-ce-nameConstraints',
'2.5.29.36' => 'id-ce-policyConstraints',
'2.5.29.31' => 'id-ce-cRLDistributionPoints',
'2.5.29.37' => 'id-ce-extKeyUsage',
'2.5.29.37.0' => 'anyExtendedKeyUsage',
'1.3.6.1.5.5.7.3.1' => 'id-kp-serverAuth',
'1.3.6.1.5.5.7.3.2' => 'id-kp-clientAuth',
'1.3.6.1.5.5.7.3.3' => 'id-kp-codeSigning',
'1.3.6.1.5.5.7.3.4' => 'id-kp-emailProtection',
'1.3.6.1.5.5.7.3.8' => 'id-kp-timeStamping',
'1.3.6.1.5.5.7.3.9' => 'id-kp-OCSPSigning',
'2.5.29.54' => 'id-ce-inhibitAnyPolicy',
'2.5.29.46' => 'id-ce-freshestCRL',
'1.3.6.1.5.5.7.1.1' => 'id-pe-authorityInfoAccess',
'1.3.6.1.5.5.7.1.11' => 'id-pe-subjectInfoAccess',
'2.5.29.20' => 'id-ce-cRLNumber',
'2.5.29.28' => 'id-ce-issuingDistributionPoint',
'2.5.29.27' => 'id-ce-deltaCRLIndicator',
'2.5.29.21' => 'id-ce-cRLReasons',
'2.5.29.29' => 'id-ce-certificateIssuer',
'2.5.29.23' => 'id-ce-holdInstructionCode',
'1.2.840.10040.2' => 'holdInstruction',
'1.2.840.10040.2.1' => 'id-holdinstruction-none',
'1.2.840.10040.2.2' => 'id-holdinstruction-callissuer',
'1.2.840.10040.2.3' => 'id-holdinstruction-reject',
'2.5.29.24' => 'id-ce-invalidityDate',
'1.2.840.113549.2.2' => 'md2',
'1.2.840.113549.2.5' => 'md5',
'1.3.14.3.2.26' => 'id-sha1',
'1.2.840.10040.4.1' => 'id-dsa',
'1.2.840.10040.4.3' => 'id-dsa-with-sha1',
'1.2.840.113549.1.1' => 'pkcs-1',
'1.2.840.113549.1.1.1' => 'rsaEncryption',
'1.2.840.113549.1.1.2' => 'md2WithRSAEncryption',
'1.2.840.113549.1.1.4' => 'md5WithRSAEncryption',
'1.2.840.113549.1.1.5' => 'sha1WithRSAEncryption',
'1.2.840.10046.2.1' => 'dhpublicnumber',
'2.16.840.1.101.2.1.1.22' => 'id-keyExchangeAlgorithm',
'1.2.840.10045' => 'ansi-X9-62',
'1.2.840.10045.4' => 'id-ecSigType',
'1.2.840.10045.4.1' => 'ecdsa-with-SHA1',
'1.2.840.10045.1' => 'id-fieldType',
'1.2.840.10045.1.1' => 'prime-field',
'1.2.840.10045.1.2' => 'characteristic-two-field',
'1.2.840.10045.1.2.3' => 'id-characteristic-two-basis',
'1.2.840.10045.1.2.3.1' => 'gnBasis',
'1.2.840.10045.1.2.3.2' => 'tpBasis',
'1.2.840.10045.1.2.3.3' => 'ppBasis',
'1.2.840.10045.2' => 'id-publicKeyType',
'1.2.840.10045.2.1' => 'id-ecPublicKey',
'1.2.840.10045.3' => 'ellipticCurve',
'1.2.840.10045.3.0' => 'c-TwoCurve',
'1.2.840.10045.3.0.1' => 'c2pnb163v1',
'1.2.840.10045.3.0.2' => 'c2pnb163v2',
'1.2.840.10045.3.0.3' => 'c2pnb163v3',
'1.2.840.10045.3.0.4' => 'c2pnb176w1',
'1.2.840.10045.3.0.5' => 'c2pnb191v1',
'1.2.840.10045.3.0.6' => 'c2pnb191v2',
'1.2.840.10045.3.0.7' => 'c2pnb191v3',
'1.2.840.10045.3.0.8' => 'c2pnb191v4',
'1.2.840.10045.3.0.9' => 'c2pnb191v5',
'1.2.840.10045.3.0.10' => 'c2pnb208w1',
'1.2.840.10045.3.0.11' => 'c2pnb239v1',
'1.2.840.10045.3.0.12' => 'c2pnb239v2',
'1.2.840.10045.3.0.13' => 'c2pnb239v3',
'1.2.840.10045.3.0.14' => 'c2pnb239v4',
'1.2.840.10045.3.0.15' => 'c2pnb239v5',
'1.2.840.10045.3.0.16' => 'c2pnb272w1',
'1.2.840.10045.3.0.17' => 'c2pnb304w1',
'1.2.840.10045.3.0.18' => 'c2pnb359v1',
'1.2.840.10045.3.0.19' => 'c2pnb368w1',
'1.2.840.10045.3.0.20' => 'c2pnb431r1',
'1.2.840.10045.3.1' => 'primeCurve',
'1.2.840.10045.3.1.1' => 'prime192v1',
'1.2.840.10045.3.1.2' => 'prime192v2',
'1.2.840.10045.3.1.3' => 'prime192v3',
'1.2.840.10045.3.1.4' => 'prime239v1',
'1.2.840.10045.3.1.5' => 'prime239v2',
'1.2.840.10045.3.1.6' => 'prime239v3',
'1.2.840.10045.3.1.7' => 'prime256v1',
'1.2.840.113549.1.1.7' => 'id-RSAES-OAEP',
'1.2.840.113549.1.1.9' => 'id-pSpecified',
'1.2.840.113549.1.1.10' => 'id-RSASSA-PSS',
'1.2.840.113549.1.1.8' => 'id-mgf1',
'1.2.840.113549.1.1.14' => 'sha224WithRSAEncryption',
'1.2.840.113549.1.1.11' => 'sha256WithRSAEncryption',
'1.2.840.113549.1.1.12' => 'sha384WithRSAEncryption',
'1.2.840.113549.1.1.13' => 'sha512WithRSAEncryption',
'2.16.840.1.101.3.4.2.4' => 'id-sha224',
'2.16.840.1.101.3.4.2.1' => 'id-sha256',
'2.16.840.1.101.3.4.2.2' => 'id-sha384',
'2.16.840.1.101.3.4.2.3' => 'id-sha512',
'1.2.643.2.2.4' => 'id-GostR3411-94-with-GostR3410-94',
'1.2.643.2.2.3' => 'id-GostR3411-94-with-GostR3410-2001',
'1.2.643.2.2.20' => 'id-GostR3410-2001',
'1.2.643.2.2.19' => 'id-GostR3410-94',
// Netscape Object Identifiers from "Netscape Certificate Extensions"
'2.16.840.1.113730' => 'netscape',
'2.16.840.1.113730.1' => 'netscape-cert-extension',
'2.16.840.1.113730.1.1' => 'netscape-cert-type',
'2.16.840.1.113730.1.13' => 'netscape-comment',
'2.16.840.1.113730.1.8' => 'netscape-ca-policy-url',
// the following are X.509 extensions not supported by phpseclib
'1.3.6.1.5.5.7.1.12' => 'id-pe-logotype',
'1.2.840.113533.7.65.0' => 'entrustVersInfo',
'2.16.840.1.113733.1.6.9' => 'verisignPrivate',
// for Certificate Signing Requests
// see http://tools.ietf.org/html/rfc2985
'1.2.840.113549.1.9.2' => 'pkcs-9-at-unstructuredName', // PKCS #9 unstructured name
'1.2.840.113549.1.9.7' => 'pkcs-9-at-challengePassword', // Challenge password for certificate revocations
'1.2.840.113549.1.9.14' => 'pkcs-9-at-extensionRequest' // Certificate extension request
);
}
/**
* Load X.509 certificate
*
* Returns an associative array describing the X.509 cert or a false if the cert failed to load
*
* @param string $cert
* @param int $mode
* @access public
* @return mixed
*/
function loadX509($cert, $mode = self::FORMAT_AUTO_DETECT)
{
if (is_array($cert) && isset($cert['tbsCertificate'])) {
unset($this->currentCert);
unset($this->currentKeyIdentifier);
$this->dn = $cert['tbsCertificate']['subject'];
if (!isset($this->dn)) {
return false;
}
$this->currentCert = $cert;
$currentKeyIdentifier = $this->getExtension('id-ce-subjectKeyIdentifier');
$this->currentKeyIdentifier = is_string($currentKeyIdentifier) ? $currentKeyIdentifier : null;
unset($this->signatureSubject);
return $cert;
}
$asn1 = new ASN1();
if ($mode != self::FORMAT_DER) {
$newcert = $this->_extractBER($cert);
if ($mode == self::FORMAT_PEM && $cert == $newcert) {
return false;
}
$cert = $newcert;
}
if ($cert === false) {
$this->currentCert = false;
return false;
}
$asn1->loadOIDs($this->oids);
$decoded = $asn1->decodeBER($cert);
if (!empty($decoded)) {
$x509 = $asn1->asn1map($decoded[0], $this->Certificate);
}
if (!isset($x509) || $x509 === false) {
$this->currentCert = false;
return false;
}
$this->signatureSubject = substr($cert, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']);
$this->_mapInExtensions($x509, 'tbsCertificate/extensions', $asn1);
$key = &$x509['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'];
$key = $this->_reformatKey($x509['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'], $key);
$this->currentCert = $x509;
$this->dn = $x509['tbsCertificate']['subject'];
$currentKeyIdentifier = $this->getExtension('id-ce-subjectKeyIdentifier');
$this->currentKeyIdentifier = is_string($currentKeyIdentifier) ? $currentKeyIdentifier : null;
return $x509;
}
/**
* Save X.509 certificate
*
* @param array $cert
* @param int $format optional
* @access public
* @return string
*/
function saveX509($cert, $format = self::FORMAT_PEM)
{
if (!is_array($cert) || !isset($cert['tbsCertificate'])) {
return false;
}
switch (true) {
// "case !$a: case !$b: break; default: whatever();" is the same thing as "if ($a && $b) whatever()"
case !($algorithm = $this->_subArray($cert, 'tbsCertificate/subjectPublicKeyInfo/algorithm/algorithm')):
case is_object($cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']):
break;
default:
switch ($algorithm) {
case 'rsaEncryption':
$cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']
= base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'])));
/* "[For RSA keys] the parameters field MUST have ASN.1 type NULL for this algorithm identifier."
-- https://tools.ietf.org/html/rfc3279#section-2.3.1
given that and the fact that RSA keys appear ot be the only key type for which the parameters field can be blank,
it seems like perhaps the ASN.1 description ought not say the parameters field is OPTIONAL, but whatever.
*/
$cert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['parameters'] = null;
// https://tools.ietf.org/html/rfc3279#section-2.2.1
$cert['signatureAlgorithm']['parameters'] = null;
$cert['tbsCertificate']['signature']['parameters'] = null;
}
}
$asn1 = new ASN1();
$asn1->loadOIDs($this->oids);
$filters = array();
$type_utf8_string = array('type' => ASN1::TYPE_UTF8_STRING);
$filters['tbsCertificate']['signature']['parameters'] = $type_utf8_string;
$filters['tbsCertificate']['signature']['issuer']['rdnSequence']['value'] = $type_utf8_string;
$filters['tbsCertificate']['issuer']['rdnSequence']['value'] = $type_utf8_string;
$filters['tbsCertificate']['subject']['rdnSequence']['value'] = $type_utf8_string;
$filters['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['parameters'] = $type_utf8_string;
$filters['signatureAlgorithm']['parameters'] = $type_utf8_string;
$filters['authorityCertIssuer']['directoryName']['rdnSequence']['value'] = $type_utf8_string;
//$filters['policyQualifiers']['qualifier'] = $type_utf8_string;
$filters['distributionPoint']['fullName']['directoryName']['rdnSequence']['value'] = $type_utf8_string;
$filters['directoryName']['rdnSequence']['value'] = $type_utf8_string;
/* in the case of policyQualifiers/qualifier, the type has to be \phpseclib\File\ASN1::TYPE_IA5_STRING.
\phpseclib\File\ASN1::TYPE_PRINTABLE_STRING will cause OpenSSL's X.509 parser to spit out random
characters.
*/
$filters['policyQualifiers']['qualifier']
= array('type' => ASN1::TYPE_IA5_STRING);
$asn1->loadFilters($filters);
$this->_mapOutExtensions($cert, 'tbsCertificate/extensions', $asn1);
$cert = $asn1->encodeDER($cert, $this->Certificate);
switch ($format) {
case self::FORMAT_DER:
return $cert;
// case self::FORMAT_PEM:
default:
return "-----BEGIN CERTIFICATE-----\r\n" . chunk_split(base64_encode($cert), 64) . '-----END CERTIFICATE-----';
}
}
/**
* Map extension values from octet string to extension-specific internal
* format.
*
* @param array ref $root
* @param string $path
* @param object $asn1
* @access private
*/
function _mapInExtensions(&$root, $path, $asn1)
{
$extensions = &$this->_subArray($root, $path);
if (is_array($extensions)) {
for ($i = 0; $i < count($extensions); $i++) {
$id = $extensions[$i]['extnId'];
$value = &$extensions[$i]['extnValue'];
$value = base64_decode($value);
$decoded = $asn1->decodeBER($value);
/* [extnValue] contains the DER encoding of an ASN.1 value
corresponding to the extension type identified by extnID */
$map = $this->_getMapping($id);
if (!is_bool($map)) {
$mapped = $asn1->asn1map($decoded[0], $map, array('iPAddress' => array($this, '_decodeIP')));
$value = $mapped === false ? $decoded[0] : $mapped;
if ($id == 'id-ce-certificatePolicies') {
for ($j = 0; $j < count($value); $j++) {
if (!isset($value[$j]['policyQualifiers'])) {
continue;
}
for ($k = 0; $k < count($value[$j]['policyQualifiers']); $k++) {
$subid = $value[$j]['policyQualifiers'][$k]['policyQualifierId'];
$map = $this->_getMapping($subid);
$subvalue = &$value[$j]['policyQualifiers'][$k]['qualifier'];
if ($map !== false) {
$decoded = $asn1->decodeBER($subvalue);
$mapped = $asn1->asn1map($decoded[0], $map);
$subvalue = $mapped === false ? $decoded[0] : $mapped;
}
}
}
}
} else {
$value = base64_encode($value);
}
}
}
}
/**
* Map extension values from extension-specific internal format to
* octet string.
*
* @param array ref $root
* @param string $path
* @param object $asn1
* @access private
*/
function _mapOutExtensions(&$root, $path, $asn1)
{
$extensions = &$this->_subArray($root, $path);
if (is_array($extensions)) {
$size = count($extensions);
for ($i = 0; $i < $size; $i++) {
if ($extensions[$i] instanceof Element) {
continue;
}
$id = $extensions[$i]['extnId'];
$value = &$extensions[$i]['extnValue'];
switch ($id) {
case 'id-ce-certificatePolicies':
for ($j = 0; $j < count($value); $j++) {
if (!isset($value[$j]['policyQualifiers'])) {
continue;
}
for ($k = 0; $k < count($value[$j]['policyQualifiers']); $k++) {
$subid = $value[$j]['policyQualifiers'][$k]['policyQualifierId'];
$map = $this->_getMapping($subid);
$subvalue = &$value[$j]['policyQualifiers'][$k]['qualifier'];
if ($map !== false) {
// by default \phpseclib\File\ASN1 will try to render qualifier as a \phpseclib\File\ASN1::TYPE_IA5_STRING since it's
// actual type is \phpseclib\File\ASN1::TYPE_ANY
$subvalue = new Element($asn1->encodeDER($subvalue, $map));
}
}
}
break;
case 'id-ce-authorityKeyIdentifier': // use 00 as the serial number instead of an empty string
if (isset($value['authorityCertSerialNumber'])) {
if ($value['authorityCertSerialNumber']->toBytes() == '') {
$temp = chr((ASN1::CLASS_CONTEXT_SPECIFIC << 6) | 2) . "\1\0";
$value['authorityCertSerialNumber'] = new Element($temp);
}
}
}
/* [extnValue] contains the DER encoding of an ASN.1 value
corresponding to the extension type identified by extnID */
$map = $this->_getMapping($id);
if (is_bool($map)) {
if (!$map) {
//user_error($id . ' is not a currently supported extension');
unset($extensions[$i]);
}
} else {
$temp = $asn1->encodeDER($value, $map, array('iPAddress' => array($this, '_encodeIP')));
$value = base64_encode($temp);
}
}
}
}
/**
* Map attribute values from ANY type to attribute-specific internal
* format.
*
* @param array ref $root
* @param string $path
* @param object $asn1
* @access private
*/
function _mapInAttributes(&$root, $path, $asn1)
{
$attributes = &$this->_subArray($root, $path);
if (is_array($attributes)) {
for ($i = 0; $i < count($attributes); $i++) {
$id = $attributes[$i]['type'];
/* $value contains the DER encoding of an ASN.1 value
corresponding to the attribute type identified by type */
$map = $this->_getMapping($id);
if (is_array($attributes[$i]['value'])) {
$values = &$attributes[$i]['value'];
for ($j = 0; $j < count($values); $j++) {
$value = $asn1->encodeDER($values[$j], $this->AttributeValue);
$decoded = $asn1->decodeBER($value);
if (!is_bool($map)) {
$mapped = $asn1->asn1map($decoded[0], $map);
if ($mapped !== false) {
$values[$j] = $mapped;
}
if ($id == 'pkcs-9-at-extensionRequest') {
$this->_mapInExtensions($values, $j, $asn1);
}
} elseif ($map) {
$values[$j] = base64_encode($value);
}
}
}
}
}
}
/**
* Map attribute values from attribute-specific internal format to
* ANY type.
*
* @param array ref $root
* @param string $path
* @param object $asn1
* @access private
*/
function _mapOutAttributes(&$root, $path, $asn1)
{
$attributes = &$this->_subArray($root, $path);
if (is_array($attributes)) {
$size = count($attributes);
for ($i = 0; $i < $size; $i++) {
/* [value] contains the DER encoding of an ASN.1 value
corresponding to the attribute type identified by type */
$id = $attributes[$i]['type'];
$map = $this->_getMapping($id);
if ($map === false) {
//user_error($id . ' is not a currently supported attribute', E_USER_NOTICE);
unset($attributes[$i]);
} elseif (is_array($attributes[$i]['value'])) {
$values = &$attributes[$i]['value'];
for ($j = 0; $j < count($values); $j++) {
switch ($id) {
case 'pkcs-9-at-extensionRequest':
$this->_mapOutExtensions($values, $j, $asn1);
break;
}
if (!is_bool($map)) {
$temp = $asn1->encodeDER($values[$j], $map);
$decoded = $asn1->decodeBER($temp);
$values[$j] = $asn1->asn1map($decoded[0], $this->AttributeValue);
}
}
}
}
}
}
/**
* Associate an extension ID to an extension mapping
*
* @param string $extnId
* @access private
* @return mixed
*/
function _getMapping($extnId)
{
if (!is_string($extnId)) { // eg. if it's a \phpseclib\File\ASN1\Element object
return true;
}
switch ($extnId) {
case 'id-ce-keyUsage':
return $this->KeyUsage;
case 'id-ce-basicConstraints':
return $this->BasicConstraints;
case 'id-ce-subjectKeyIdentifier':
return $this->KeyIdentifier;
case 'id-ce-cRLDistributionPoints':
return $this->CRLDistributionPoints;
case 'id-ce-authorityKeyIdentifier':
return $this->AuthorityKeyIdentifier;
case 'id-ce-certificatePolicies':
return $this->CertificatePolicies;
case 'id-ce-extKeyUsage':
return $this->ExtKeyUsageSyntax;
case 'id-pe-authorityInfoAccess':
return $this->AuthorityInfoAccessSyntax;
case 'id-ce-subjectAltName':
return $this->SubjectAltName;
case 'id-ce-privateKeyUsagePeriod':
return $this->PrivateKeyUsagePeriod;
case 'id-ce-issuerAltName':
return $this->IssuerAltName;
case 'id-ce-policyMappings':
return $this->PolicyMappings;
case 'id-ce-nameConstraints':
return $this->NameConstraints;
case 'netscape-cert-type':
return $this->netscape_cert_type;
case 'netscape-comment':
return $this->netscape_comment;
case 'netscape-ca-policy-url':
return $this->netscape_ca_policy_url;
// since id-qt-cps isn't a constructed type it will have already been decoded as a string by the time it gets
// back around to asn1map() and we don't want it decoded again.
//case 'id-qt-cps':
// return $this->CPSuri;
case 'id-qt-unotice':
return $this->UserNotice;
// the following OIDs are unsupported but we don't want them to give notices when calling saveX509().
case 'id-pe-logotype': // http://www.ietf.org/rfc/rfc3709.txt
case 'entrustVersInfo':
// http://support.microsoft.com/kb/287547
case '1.3.6.1.4.1.311.20.2': // szOID_ENROLL_CERTTYPE_EXTENSION
case '1.3.6.1.4.1.311.21.1': // szOID_CERTSRV_CA_VERSION
// "SET Secure Electronic Transaction Specification"
// http://www.maithean.com/docs/set_bk3.pdf
case '2.23.42.7.0': // id-set-hashedRootKey
return true;
// CSR attributes
case 'pkcs-9-at-unstructuredName':
return $this->PKCS9String;
case 'pkcs-9-at-challengePassword':
return $this->DirectoryString;
case 'pkcs-9-at-extensionRequest':
return $this->Extensions;
// CRL extensions.
case 'id-ce-cRLNumber':
return $this->CRLNumber;
case 'id-ce-deltaCRLIndicator':
return $this->CRLNumber;
case 'id-ce-issuingDistributionPoint':
return $this->IssuingDistributionPoint;
case 'id-ce-freshestCRL':
return $this->CRLDistributionPoints;
case 'id-ce-cRLReasons':
return $this->CRLReason;
case 'id-ce-invalidityDate':
return $this->InvalidityDate;
case 'id-ce-certificateIssuer':
return $this->CertificateIssuer;
case 'id-ce-holdInstructionCode':
return $this->HoldInstructionCode;
}
return false;
}
/**
* Load an X.509 certificate as a certificate authority
*
* @param string $cert
* @access public
* @return bool
*/
function loadCA($cert)
{
$olddn = $this->dn;
$oldcert = $this->currentCert;
$oldsigsubj = $this->signatureSubject;
$oldkeyid = $this->currentKeyIdentifier;
$cert = $this->loadX509($cert);
if (!$cert) {
$this->dn = $olddn;
$this->currentCert = $oldcert;
$this->signatureSubject = $oldsigsubj;
$this->currentKeyIdentifier = $oldkeyid;
return false;
}
/* From RFC5280 "PKIX Certificate and CRL Profile":
If the keyUsage extension is present, then the subject public key
MUST NOT be used to verify signatures on certificates or CRLs unless
the corresponding keyCertSign or cRLSign bit is set. */
//$keyUsage = $this->getExtension('id-ce-keyUsage');
//if ($keyUsage && !in_array('keyCertSign', $keyUsage)) {
// return false;
//}
/* From RFC5280 "PKIX Certificate and CRL Profile":
The cA boolean indicates whether the certified public key may be used
to verify certificate signatures. If the cA boolean is not asserted,
then the keyCertSign bit in the key usage extension MUST NOT be
asserted. If the basic constraints extension is not present in a
version 3 certificate, or the extension is present but the cA boolean
is not asserted, then the certified public key MUST NOT be used to
verify certificate signatures. */
//$basicConstraints = $this->getExtension('id-ce-basicConstraints');
//if (!$basicConstraints || !$basicConstraints['cA']) {
// return false;
//}
$this->CAs[] = $cert;
$this->dn = $olddn;
$this->currentCert = $oldcert;
$this->signatureSubject = $oldsigsubj;
return true;
}
/**
* Validate an X.509 certificate against a URL
*
* From RFC2818 "HTTP over TLS":
*
* Matching is performed using the matching rules specified by
* [RFC2459]. If more than one identity of a given type is present in
* the certificate (e.g., more than one dNSName name, a match in any one
* of the set is considered acceptable.) Names may contain the wildcard
* character * which is considered to match any single domain name
* component or component fragment. E.g., *.a.com matches foo.a.com but
* not bar.foo.a.com. f*.com matches foo.com but not bar.com.
*
* @param string $url
* @access public
* @return bool
*/
function validateURL($url)
{
if (!is_array($this->currentCert) || !isset($this->currentCert['tbsCertificate'])) {
return false;
}
$components = parse_url($url);
if (!isset($components['host'])) {
return false;
}
if ($names = $this->getExtension('id-ce-subjectAltName')) {
foreach ($names as $key => $value) {
$value = str_replace(array('.', '*'), array('\.', '[^.]*'), $value);
switch ($key) {
case 'dNSName':
/* From RFC2818 "HTTP over TLS":
If a subjectAltName extension of type dNSName is present, that MUST
be used as the identity. Otherwise, the (most specific) Common Name
field in the Subject field of the certificate MUST be used. Although
the use of the Common Name is existing practice, it is deprecated and
Certification Authorities are encouraged to use the dNSName instead. */
if (preg_match('#^' . $value . '$#', $components['host'])) {
return true;
}
break;
case 'iPAddress':
/* From RFC2818 "HTTP over TLS":
In some cases, the URI is specified as an IP address rather than a
hostname. In this case, the iPAddress subjectAltName must be present
in the certificate and must exactly match the IP in the URI. */
if (preg_match('#(?:\d{1-3}\.){4}#', $components['host'] . '.') && preg_match('#^' . $value . '$#', $components['host'])) {
return true;
}
}
}
return false;
}
if ($value = $this->getDNProp('id-at-commonName')) {
$value = str_replace(array('.', '*'), array('\.', '[^.]*'), $value[0]);
return preg_match('#^' . $value . '$#', $components['host']);
}
return false;
}
/**
* Validate a date
*
* If $date isn't defined it is assumed to be the current date.
*
* @param int $date optional
* @access public
*/
function validateDate($date = null)
{
if (!is_array($this->currentCert) || !isset($this->currentCert['tbsCertificate'])) {
return false;
}
if (!isset($date)) {
$date = time();
}
$notBefore = $this->currentCert['tbsCertificate']['validity']['notBefore'];
$notBefore = isset($notBefore['generalTime']) ? $notBefore['generalTime'] : $notBefore['utcTime'];
$notAfter = $this->currentCert['tbsCertificate']['validity']['notAfter'];
$notAfter = isset($notAfter['generalTime']) ? $notAfter['generalTime'] : $notAfter['utcTime'];
switch (true) {
case $date < @strtotime($notBefore):
case $date > @strtotime($notAfter):
return false;
}
return true;
}
/**
* Validate a signature
*
* Works on X.509 certs, CSR's and CRL's.
* Returns true if the signature is verified, false if it is not correct or null on error
*
* By default returns false for self-signed certs. Call validateSignature(false) to make this support
* self-signed.
*
* The behavior of this function is inspired by {@link http://php.net/openssl-verify openssl_verify}.
*
* @param bool $caonly optional
* @access public
* @return mixed
*/
function validateSignature($caonly = true)
{
if (!is_array($this->currentCert) || !isset($this->signatureSubject)) {
return null;
}
/* TODO:
"emailAddress attribute values are not case-sensitive (e.g., "subscriber@example.com" is the same as "SUBSCRIBER@EXAMPLE.COM")."
-- http://tools.ietf.org/html/rfc5280#section-4.1.2.6
implement pathLenConstraint in the id-ce-basicConstraints extension */
switch (true) {
case isset($this->currentCert['tbsCertificate']):
// self-signed cert
if ($this->currentCert['tbsCertificate']['issuer'] === $this->currentCert['tbsCertificate']['subject']) {
$authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier');
$subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier');
switch (true) {
case !is_array($authorityKey):
case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID:
$signingCert = $this->currentCert; // working cert
}
}
if (!empty($this->CAs)) {
for ($i = 0; $i < count($this->CAs); $i++) {
// even if the cert is a self-signed one we still want to see if it's a CA;
// if not, we'll conditionally return an error
$ca = $this->CAs[$i];
if ($this->currentCert['tbsCertificate']['issuer'] === $ca['tbsCertificate']['subject']) {
$authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier');
$subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca);
switch (true) {
case !is_array($authorityKey):
case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID:
$signingCert = $ca; // working cert
break 2;
}
}
}
if (count($this->CAs) == $i && $caonly) {
return false;
}
} elseif (!isset($signingCert) || $caonly) {
return false;
}
return $this->_validateSignature(
$signingCert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'],
$signingCert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'],
$this->currentCert['signatureAlgorithm']['algorithm'],
substr(base64_decode($this->currentCert['signature']), 1),
$this->signatureSubject
);
case isset($this->currentCert['certificationRequestInfo']):
return $this->_validateSignature(
$this->currentCert['certificationRequestInfo']['subjectPKInfo']['algorithm']['algorithm'],
$this->currentCert['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'],
$this->currentCert['signatureAlgorithm']['algorithm'],
substr(base64_decode($this->currentCert['signature']), 1),
$this->signatureSubject
);
case isset($this->currentCert['publicKeyAndChallenge']):
return $this->_validateSignature(
$this->currentCert['publicKeyAndChallenge']['spki']['algorithm']['algorithm'],
$this->currentCert['publicKeyAndChallenge']['spki']['subjectPublicKey'],
$this->currentCert['signatureAlgorithm']['algorithm'],
substr(base64_decode($this->currentCert['signature']), 1),
$this->signatureSubject
);
case isset($this->currentCert['tbsCertList']):
if (!empty($this->CAs)) {
for ($i = 0; $i < count($this->CAs); $i++) {
$ca = $this->CAs[$i];
if ($this->currentCert['tbsCertList']['issuer'] === $ca['tbsCertificate']['subject']) {
$authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier');
$subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca);
switch (true) {
case !is_array($authorityKey):
case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID:
$signingCert = $ca; // working cert
break 2;
}
}
}
}
if (!isset($signingCert)) {
return false;
}
return $this->_validateSignature(
$signingCert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'],
$signingCert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'],
$this->currentCert['signatureAlgorithm']['algorithm'],
substr(base64_decode($this->currentCert['signature']), 1),
$this->signatureSubject
);
default:
return false;
}
}
/**
* Validates a signature
*
* Returns true if the signature is verified and false if it is not correct.
* If the algorithms are unsupposed an exception is thrown.
*
* @param string $publicKeyAlgorithm
* @param string $publicKey
* @param string $signatureAlgorithm
* @param string $signature
* @param string $signatureSubject
* @access private
* @throws \phpseclib\Exception\UnsupportedAlgorithmException if the algorithm is unsupported
* @return bool
*/
function _validateSignature($publicKeyAlgorithm, $publicKey, $signatureAlgorithm, $signature, $signatureSubject)
{
switch ($publicKeyAlgorithm) {
case 'rsaEncryption':
$rsa = new RSA();
$rsa->load($publicKey);
switch ($signatureAlgorithm) {
case 'md2WithRSAEncryption':
case 'md5WithRSAEncryption':
case 'sha1WithRSAEncryption':
case 'sha224WithRSAEncryption':
case 'sha256WithRSAEncryption':
case 'sha384WithRSAEncryption':
case 'sha512WithRSAEncryption':
$rsa->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm));
$rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);
if (!@$rsa->verify($signatureSubject, $signature)) {
return false;
}
break;
default:
throw new UnsupportedAlgorithmException('Signature algorithm unsupported');
}
break;
default:
throw new UnsupportedAlgorithmException('Public key algorithm unsupported');
}
return true;
}
/**
* Reformat public keys
*
* Reformats a public key to a format supported by phpseclib (if applicable)
*
* @param string $algorithm
* @param string $key
* @access private
* @return string
*/
function _reformatKey($algorithm, $key)
{
switch ($algorithm) {
case 'rsaEncryption':
return
"-----BEGIN RSA PUBLIC KEY-----\r\n" .
// subjectPublicKey is stored as a bit string in X.509 certs. the first byte of a bit string represents how many bits
// in the last byte should be ignored. the following only supports non-zero stuff but as none of the X.509 certs Firefox
// uses as a cert authority actually use a non-zero bit I think it's safe to assume that none do.
chunk_split(base64_encode(substr(base64_decode($key), 1)), 64) .
'-----END RSA PUBLIC KEY-----';
default:
return $key;
}
}
/**
* Decodes an IP address
*
* Takes in a base64 encoded "blob" and returns a human readable IP address
*
* @param string $ip
* @access private
* @return string
*/
function _decodeIP($ip)
{
$ip = base64_decode($ip);
list(, $ip) = unpack('N', $ip);
return long2ip($ip);
}
/**
* Encodes an IP address
*
* Takes a human readable IP address into a base64-encoded "blob"
*
* @param string $ip
* @access private
* @return string
*/
function _encodeIP($ip)
{
return base64_encode(pack('N', ip2long($ip)));
}
/**
* "Normalizes" a Distinguished Name property
*
* @param string $propName
* @access private
* @return mixed
*/
function _translateDNProp($propName)
{
switch (strtolower($propName)) {
case 'id-at-countryname':
case 'countryname':
case 'c':
return 'id-at-countryName';
case 'id-at-organizationname':
case 'organizationname':
case 'o':
return 'id-at-organizationName';
case 'id-at-dnqualifier':
case 'dnqualifier':
return 'id-at-dnQualifier';
case 'id-at-commonname':
case 'commonname':
case 'cn':
return 'id-at-commonName';
case 'id-at-stateorprovincename':
case 'stateorprovincename':
case 'state':
case 'province':
case 'provincename':
case 'st':
return 'id-at-stateOrProvinceName';
case 'id-at-localityname':
case 'localityname':
case 'l':
return 'id-at-localityName';
case 'id-emailaddress':
case 'emailaddress':
return 'pkcs-9-at-emailAddress';
case 'id-at-serialnumber':
case 'serialnumber':
return 'id-at-serialNumber';
case 'id-at-postalcode':
case 'postalcode':
return 'id-at-postalCode';
case 'id-at-streetaddress':
case 'streetaddress':
return 'id-at-streetAddress';
case 'id-at-name':
case 'name':
return 'id-at-name';
case 'id-at-givenname':
case 'givenname':
return 'id-at-givenName';
case 'id-at-surname':
case 'surname':
case 'sn':
return 'id-at-surname';
case 'id-at-initials':
case 'initials':
return 'id-at-initials';
case 'id-at-generationqualifier':
case 'generationqualifier':
return 'id-at-generationQualifier';
case 'id-at-organizationalunitname':
case 'organizationalunitname':
case 'ou':
return 'id-at-organizationalUnitName';
case 'id-at-pseudonym':
case 'pseudonym':
return 'id-at-pseudonym';
case 'id-at-title':
case 'title':
return 'id-at-title';
case 'id-at-description':
case 'description':
return 'id-at-description';
case 'id-at-role':
case 'role':
return 'id-at-role';
case 'id-at-uniqueidentifier':
case 'uniqueidentifier':
case 'x500uniqueidentifier':
return 'id-at-uniqueIdentifier';
default:
return false;
}
}
/**
* Set a Distinguished Name property
*
* @param string $propName
* @param mixed $propValue
* @param string $type optional
* @access public
* @return bool
*/
function setDNProp($propName, $propValue, $type = 'utf8String')
{
if (empty($this->dn)) {
$this->dn = array('rdnSequence' => array());
}
if (($propName = $this->_translateDNProp($propName)) === false) {
return false;
}
foreach ((array) $propValue as $v) {
if (!is_array($v) && isset($type)) {
$v = array($type => $v);
}
$this->dn['rdnSequence'][] = array(
array(
'type' => $propName,
'value'=> $v
)
);
}
return true;
}
/**
* Remove Distinguished Name properties
*
* @param string $propName
* @access public
*/
function removeDNProp($propName)
{
if (empty($this->dn)) {
return;
}
if (($propName = $this->_translateDNProp($propName)) === false) {
return;
}
$dn = &$this->dn['rdnSequence'];
$size = count($dn);
for ($i = 0; $i < $size; $i++) {
if ($dn[$i][0]['type'] == $propName) {
unset($dn[$i]);
}
}
$dn = array_values($dn);
}
/**
* Get Distinguished Name properties
*
* @param string $propName
* @param array $dn optional
* @param bool $withType optional
* @return mixed
* @access public
*/
function getDNProp($propName, $dn = null, $withType = false)
{
if (!isset($dn)) {
$dn = $this->dn;
}
if (empty($dn)) {
return false;
}
if (($propName = $this->_translateDNProp($propName)) === false) {
return false;
}
$dn = $dn['rdnSequence'];
$result = array();
$asn1 = new ASN1();
for ($i = 0; $i < count($dn); $i++) {
if ($dn[$i][0]['type'] == $propName) {
$v = $dn[$i][0]['value'];
if (!$withType && is_array($v)) {
foreach ($v as $type => $s) {
$type = array_search($type, $asn1->ANYmap, true);
if ($type !== false && isset($asn1->stringTypeSize[$type])) {
$s = $asn1->convert($s, $type);
if ($s !== false) {
$v = $s;
break;
}
}
}
if (is_array($v)) {
$v = array_pop($v); // Always strip data type.
}
}
$result[] = $v;
}
}
return $result;
}
/**
* Set a Distinguished Name
*
* @param mixed $dn
* @param bool $merge optional
* @param string $type optional
* @access public
* @return bool
*/
function setDN($dn, $merge = false, $type = 'utf8String')
{
if (!$merge) {
$this->dn = null;
}
if (is_array($dn)) {
if (isset($dn['rdnSequence'])) {
$this->dn = $dn; // No merge here.
return true;
}
// handles stuff generated by openssl_x509_parse()
foreach ($dn as $prop => $value) {
if (!$this->setDNProp($prop, $value, $type)) {
return false;
}
}
return true;
}
// handles everything else
$results = preg_split('#((?:^|, *|/)(?:C=|O=|OU=|CN=|L=|ST=|SN=|postalCode=|streetAddress=|emailAddress=|serialNumber=|organizationalUnitName=|title=|description=|role=|x500UniqueIdentifier=))#', $dn, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 1; $i < count($results); $i+=2) {
$prop = trim($results[$i], ', =/');
$value = $results[$i + 1];
if (!$this->setDNProp($prop, $value, $type)) {
return false;
}
}
return true;
}
/**
* Get the Distinguished Name for a certificates subject
*
* @param mixed $format optional
* @param array $dn optional
* @access public
* @return bool
*/
function getDN($format = self::DN_ARRAY, $dn = null)
{
if (!isset($dn)) {
$dn = isset($this->currentCert['tbsCertList']) ? $this->currentCert['tbsCertList']['issuer'] : $this->dn;
}
switch ((int) $format) {
case self::DN_ARRAY:
return $dn;
case self::DN_ASN1:
$asn1 = new ASN1();
$asn1->loadOIDs($this->oids);
$filters = array();
$filters['rdnSequence']['value'] = array('type' => ASN1::TYPE_UTF8_STRING);
$asn1->loadFilters($filters);
return $asn1->encodeDER($dn, $this->Name);
case self::DN_OPENSSL:
$dn = $this->getDN(self::DN_STRING, $dn);
if ($dn === false) {
return false;
}
$attrs = preg_split('#((?:^|, *|/)[a-z][a-z0-9]*=)#i', $dn, -1, PREG_SPLIT_DELIM_CAPTURE);
$dn = array();
for ($i = 1; $i < count($attrs); $i += 2) {
$prop = trim($attrs[$i], ', =/');
$value = $attrs[$i + 1];
if (!isset($dn[$prop])) {
$dn[$prop] = $value;
} else {
$dn[$prop] = array_merge((array) $dn[$prop], array($value));
}
}
return $dn;
case self::DN_CANON:
// No SEQUENCE around RDNs and all string values normalized as
// trimmed lowercase UTF-8 with all spacing as one blank.
$asn1 = new ASN1();
$asn1->loadOIDs($this->oids);
$filters = array();
$filters['value'] = array('type' => ASN1::TYPE_UTF8_STRING);
$asn1->loadFilters($filters);
$result = '';
foreach ($dn['rdnSequence'] as $rdn) {
foreach ($rdn as $i => $attr) {
$attr = &$rdn[$i];
if (is_array($attr['value'])) {
foreach ($attr['value'] as $type => $v) {
$type = array_search($type, $asn1->ANYmap, true);
if ($type !== false && isset($asn1->stringTypeSize[$type])) {
$v = $asn1->convert($v, $type);
if ($v !== false) {
$v = preg_replace('/\s+/', ' ', $v);
$attr['value'] = strtolower(trim($v));
break;
}
}
}
}
}
$result .= $asn1->encodeDER($rdn, $this->RelativeDistinguishedName);
}
return $result;
case self::DN_HASH:
$dn = $this->getDN(self::DN_CANON, $dn);
$hash = new Hash('sha1');
$hash = $hash->hash($dn);
extract(unpack('Vhash', $hash));
return strtolower(bin2hex(pack('N', $hash)));
}
// Default is to return a string.
$start = true;
$output = '';
$asn1 = new ASN1();
foreach ($dn['rdnSequence'] as $field) {
$prop = $field[0]['type'];
$value = $field[0]['value'];
$delim = ', ';
switch ($prop) {
case 'id-at-countryName':
$desc = 'C=';
break;
case 'id-at-stateOrProvinceName':
$desc = 'ST=';
break;
case 'id-at-organizationName':
$desc = 'O=';
break;
case 'id-at-organizationalUnitName':
$desc = 'OU=';
break;
case 'id-at-commonName':
$desc = 'CN=';
break;
case 'id-at-localityName':
$desc = 'L=';
break;
case 'id-at-surname':
$desc = 'SN=';
break;
case 'id-at-uniqueIdentifier':
$delim = '/';
$desc = 'x500UniqueIdentifier=';
break;
default:
$delim = '/';
$desc = preg_replace('#.+-([^-]+)$#', '$1', $prop) . '=';
}
if (!$start) {
$output.= $delim;
}
if (is_array($value)) {
foreach ($value as $type => $v) {
$type = array_search($type, $asn1->ANYmap, true);
if ($type !== false && isset($asn1->stringTypeSize[$type])) {
$v = $asn1->convert($v, $type);
if ($v !== false) {
$value = $v;
break;
}
}
}
if (is_array($value)) {
$value = array_pop($value); // Always strip data type.
}
}
$output.= $desc . $value;
$start = false;
}
return $output;
}
/**
* Get the Distinguished Name for a certificate/crl issuer
*
* @param int $format optional
* @access public
* @return mixed
*/
function getIssuerDN($format = self::DN_ARRAY)
{
switch (true) {
case !isset($this->currentCert) || !is_array($this->currentCert):
break;
case isset($this->currentCert['tbsCertificate']):
return $this->getDN($format, $this->currentCert['tbsCertificate']['issuer']);
case isset($this->currentCert['tbsCertList']):
return $this->getDN($format, $this->currentCert['tbsCertList']['issuer']);
}
return false;
}
/**
* Get the Distinguished Name for a certificate/csr subject
* Alias of getDN()
*
* @param int $format optional
* @access public
* @return mixed
*/
function getSubjectDN($format = self::DN_ARRAY)
{
switch (true) {
case !empty($this->dn):
return $this->getDN($format);
case !isset($this->currentCert) || !is_array($this->currentCert):
break;
case isset($this->currentCert['tbsCertificate']):
return $this->getDN($format, $this->currentCert['tbsCertificate']['subject']);
case isset($this->currentCert['certificationRequestInfo']):
return $this->getDN($format, $this->currentCert['certificationRequestInfo']['subject']);
}
return false;
}
/**
* Get an individual Distinguished Name property for a certificate/crl issuer
*
* @param string $propName
* @param bool $withType optional
* @access public
* @return mixed
*/
function getIssuerDNProp($propName, $withType = false)
{
switch (true) {
case !isset($this->currentCert) || !is_array($this->currentCert):
break;
case isset($this->currentCert['tbsCertificate']):
return $this->getDNProp($propName, $this->currentCert['tbsCertificate']['issuer'], $withType);
case isset($this->currentCert['tbsCertList']):
return $this->getDNProp($propName, $this->currentCert['tbsCertList']['issuer'], $withType);
}
return false;
}
/**
* Get an individual Distinguished Name property for a certificate/csr subject
*
* @param string $propName
* @param bool $withType optional
* @access public
* @return mixed
*/
function getSubjectDNProp($propName, $withType = false)
{
switch (true) {
case !empty($this->dn):
return $this->getDNProp($propName, null, $withType);
case !isset($this->currentCert) || !is_array($this->currentCert):
break;
case isset($this->currentCert['tbsCertificate']):
return $this->getDNProp($propName, $this->currentCert['tbsCertificate']['subject'], $withType);
case isset($this->currentCert['certificationRequestInfo']):
return $this->getDNProp($propName, $this->currentCert['certificationRequestInfo']['subject'], $withType);
}
return false;
}
/**
* Get the certificate chain for the current cert
*
* @access public
* @return mixed
*/
function getChain()
{
$chain = array($this->currentCert);
if (!is_array($this->currentCert) || !isset($this->currentCert['tbsCertificate'])) {
return false;
}
if (empty($this->CAs)) {
return $chain;
}
while (true) {
$currentCert = $chain[count($chain) - 1];
for ($i = 0; $i < count($this->CAs); $i++) {
$ca = $this->CAs[$i];
if ($currentCert['tbsCertificate']['issuer'] === $ca['tbsCertificate']['subject']) {
$authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier', $currentCert);
$subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca);
switch (true) {
case !is_array($authorityKey):
case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID:
if ($currentCert === $ca) {
break 3;
}
$chain[] = $ca;
break 2;
}
}
}
if ($i == count($this->CAs)) {
break;
}
}
foreach ($chain as $key => $value) {
$chain[$key] = new X509();
$chain[$key]->loadX509($value);
}
return $chain;
}
/**
* Set public key
*
* Key needs to be a \phpseclib\Crypt\RSA object
*
* @param object $key
* @access public
* @return bool
*/
function setPublicKey($key)
{
$key->setPublicKey();
$this->publicKey = $key;
}
/**
* Set private key
*
* Key needs to be a \phpseclib\Crypt\RSA object
*
* @param object $key
* @access public
*/
function setPrivateKey($key)
{
$this->privateKey = $key;
}
/**
* Set challenge
*
* Used for SPKAC CSR's
*
* @param string $challenge
* @access public
*/
function setChallenge($challenge)
{
$this->challenge = $challenge;
}
/**
* Gets the public key
*
* Returns a \phpseclib\Crypt\RSA object or a false.
*
* @access public
* @return mixed
*/
function getPublicKey()
{
if (isset($this->publicKey)) {
return $this->publicKey;
}
if (isset($this->currentCert) && is_array($this->currentCert)) {
foreach (array('tbsCertificate/subjectPublicKeyInfo', 'certificationRequestInfo/subjectPKInfo') as $path) {
$keyinfo = $this->_subArray($this->currentCert, $path);
if (!empty($keyinfo)) {
break;
}
}
}
if (empty($keyinfo)) {
return false;
}
$key = $keyinfo['subjectPublicKey'];
switch ($keyinfo['algorithm']['algorithm']) {
case 'rsaEncryption':
$publicKey = new RSA();
$publicKey->load($key);
$publicKey->setPublicKey();
break;
default:
return false;
}
return $publicKey;
}
/**
* Load a Certificate Signing Request
*
* @param string $csr
* @access public
* @return mixed
*/
function loadCSR($csr, $mode = self::FORMAT_AUTO_DETECT)
{
if (is_array($csr) && isset($csr['certificationRequestInfo'])) {
unset($this->currentCert);
unset($this->currentKeyIdentifier);
unset($this->signatureSubject);
$this->dn = $csr['certificationRequestInfo']['subject'];
if (!isset($this->dn)) {
return false;
}
$this->currentCert = $csr;
return $csr;
}
// see http://tools.ietf.org/html/rfc2986
$asn1 = new ASN1();
if ($mode != self::FORMAT_DER) {
$newcsr = $this->_extractBER($csr);
if ($mode == self::FORMAT_PEM && $csr == $newcsr) {
return false;
}
$csr = $newcsr;
}
$orig = $csr;
if ($csr === false) {
$this->currentCert = false;
return false;
}
$asn1->loadOIDs($this->oids);
$decoded = $asn1->decodeBER($csr);
if (empty($decoded)) {
$this->currentCert = false;
return false;
}
$csr = $asn1->asn1map($decoded[0], $this->CertificationRequest);
if (!isset($csr) || $csr === false) {
$this->currentCert = false;
return false;
}
$this->dn = $csr['certificationRequestInfo']['subject'];
$this->_mapInAttributes($csr, 'certificationRequestInfo/attributes', $asn1);
$this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']);
$algorithm = &$csr['certificationRequestInfo']['subjectPKInfo']['algorithm']['algorithm'];
$key = &$csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'];
$key = $this->_reformatKey($algorithm, $key);
switch ($algorithm) {
case 'rsaEncryption':
$this->publicKey = new RSA();
$this->publicKey->load($key);
$this->publicKey->setPublicKey();
break;
default:
$this->publicKey = null;
}
$this->currentKeyIdentifier = null;
$this->currentCert = $csr;
return $csr;
}
/**
* Save CSR request
*
* @param array $csr
* @param int $format optional
* @access public
* @return string
*/
function saveCSR($csr, $format = self::FORMAT_PEM)
{
if (!is_array($csr) || !isset($csr['certificationRequestInfo'])) {
return false;
}
switch (true) {
case !($algorithm = $this->_subArray($csr, 'certificationRequestInfo/subjectPKInfo/algorithm/algorithm')):
case is_object($csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']):
break;
default:
switch ($algorithm) {
case 'rsaEncryption':
$csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']
= base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'])));
}
}
$asn1 = new ASN1();
$asn1->loadOIDs($this->oids);
$filters = array();
$filters['certificationRequestInfo']['subject']['rdnSequence']['value']
= array('type' => ASN1::TYPE_UTF8_STRING);
$asn1->loadFilters($filters);
$this->_mapOutAttributes($csr, 'certificationRequestInfo/attributes', $asn1);
$csr = $asn1->encodeDER($csr, $this->CertificationRequest);
switch ($format) {
case self::FORMAT_DER:
return $csr;
// case self::FORMAT_PEM:
default:
return "-----BEGIN CERTIFICATE REQUEST-----\r\n" . chunk_split(base64_encode($csr), 64) . '-----END CERTIFICATE REQUEST-----';
}
}
/**
* Load a SPKAC CSR
*
* SPKAC's are produced by the HTML5 keygen element:
*
* https://developer.mozilla.org/en-US/docs/HTML/Element/keygen
*
* @param string $csr
* @access public
* @return mixed
*/
function loadSPKAC($spkac)
{
if (is_array($spkac) && isset($spkac['publicKeyAndChallenge'])) {
unset($this->currentCert);
unset($this->currentKeyIdentifier);
unset($this->signatureSubject);
$this->currentCert = $spkac;
return $spkac;
}
// see http://www.w3.org/html/wg/drafts/html/master/forms.html#signedpublickeyandchallenge
$asn1 = new ASN1();
// OpenSSL produces SPKAC's that are preceeded by the string SPKAC=
$temp = preg_replace('#(?:SPKAC=)|[ \r\n\\\]#', '', $spkac);
$temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false;
if ($temp != false) {
$spkac = $temp;
}
$orig = $spkac;
if ($spkac === false) {
$this->currentCert = false;
return false;
}
$asn1->loadOIDs($this->oids);
$decoded = $asn1->decodeBER($spkac);
if (empty($decoded)) {
$this->currentCert = false;
return false;
}
$spkac = $asn1->asn1map($decoded[0], $this->SignedPublicKeyAndChallenge);
if (!isset($spkac) || $spkac === false) {
$this->currentCert = false;
return false;
}
$this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']);
$algorithm = &$spkac['publicKeyAndChallenge']['spki']['algorithm']['algorithm'];
$key = &$spkac['publicKeyAndChallenge']['spki']['subjectPublicKey'];
$key = $this->_reformatKey($algorithm, $key);
switch ($algorithm) {
case 'rsaEncryption':
$this->publicKey = new RSA();
$this->publicKey->load($key);
$this->publicKey->setPublicKey();
break;
default:
$this->publicKey = null;
}
$this->currentKeyIdentifier = null;
$this->currentCert = $spkac;
return $spkac;
}
/**
* Save a SPKAC CSR request
*
* @param array $csr
* @param int $format optional
* @access public
* @return string
*/
function saveSPKAC($spkac, $format = self::FORMAT_PEM)
{
if (!is_array($spkac) || !isset($spkac['publicKeyAndChallenge'])) {
return false;
}
$algorithm = $this->_subArray($spkac, 'publicKeyAndChallenge/spki/algorithm/algorithm');
switch (true) {
case !$algorithm:
case is_object($spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']):
break;
default:
switch ($algorithm) {
case 'rsaEncryption':
$spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']
= base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $spkac['publicKeyAndChallenge']['spki']['subjectPublicKey'])));
}
}
$asn1 = new ASN1();
$asn1->loadOIDs($this->oids);
$spkac = $asn1->encodeDER($spkac, $this->SignedPublicKeyAndChallenge);
switch ($format) {
case self::FORMAT_DER:
return $spkac;
// case self::FORMAT_PEM:
default:
// OpenSSL's implementation of SPKAC requires the SPKAC be preceeded by SPKAC= and since there are pretty much
// no other SPKAC decoders phpseclib will use that same format
return 'SPKAC=' . base64_encode($spkac);
}
}
/**
* Load a Certificate Revocation List
*
* @param string $crl
* @access public
* @return mixed
*/
function loadCRL($crl, $mode = self::FORMAT_AUTO_DETECT)
{
if (is_array($crl) && isset($crl['tbsCertList'])) {
$this->currentCert = $crl;
unset($this->signatureSubject);
return $crl;
}
$asn1 = new ASN1();
if ($mode != self::FORMAT_DER) {
$newcrl = $this->_extractBER($crl);
if ($mode == self::FORMAT_PEM && $crl == $newcrl) {
return false;
}
$crl = $newcrl;
}
$orig = $crl;
if ($crl === false) {
$this->currentCert = false;
return false;
}
$asn1->loadOIDs($this->oids);
$decoded = $asn1->decodeBER($crl);
if (empty($decoded)) {
$this->currentCert = false;
return false;
}
$crl = $asn1->asn1map($decoded[0], $this->CertificateList);
if (!isset($crl) || $crl === false) {
$this->currentCert = false;
return false;
}
$this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']);
$this->_mapInExtensions($crl, 'tbsCertList/crlExtensions', $asn1);
$rclist = &$this->_subArray($crl, 'tbsCertList/revokedCertificates');
if (is_array($rclist)) {
foreach ($rclist as $i => $extension) {
$this->_mapInExtensions($rclist, "$i/crlEntryExtensions", $asn1);
}
}
$this->currentKeyIdentifier = null;
$this->currentCert = $crl;
return $crl;
}
/**
* Save Certificate Revocation List.
*
* @param array $crl
* @param int $format optional
* @access public
* @return string
*/
function saveCRL($crl, $format = self::FORMAT_PEM)
{
if (!is_array($crl) || !isset($crl['tbsCertList'])) {
return false;
}
$asn1 = new ASN1();
$asn1->loadOIDs($this->oids);
$filters = array();
$filters['tbsCertList']['issuer']['rdnSequence']['value']
= array('type' => ASN1::TYPE_UTF8_STRING);
$filters['tbsCertList']['signature']['parameters']
= array('type' => ASN1::TYPE_UTF8_STRING);
$filters['signatureAlgorithm']['parameters']
= array('type' => ASN1::TYPE_UTF8_STRING);
if (empty($crl['tbsCertList']['signature']['parameters'])) {
$filters['tbsCertList']['signature']['parameters']
= array('type' => ASN1::TYPE_NULL);
}
if (empty($crl['signatureAlgorithm']['parameters'])) {
$filters['signatureAlgorithm']['parameters']
= array('type' => ASN1::TYPE_NULL);
}
$asn1->loadFilters($filters);
$this->_mapOutExtensions($crl, 'tbsCertList/crlExtensions', $asn1);
$rclist = &$this->_subArray($crl, 'tbsCertList/revokedCertificates');
if (is_array($rclist)) {
foreach ($rclist as $i => $extension) {
$this->_mapOutExtensions($rclist, "$i/crlEntryExtensions", $asn1);
}
}
$crl = $asn1->encodeDER($crl, $this->CertificateList);
switch ($format) {
case self::FORMAT_DER:
return $crl;
// case self::FORMAT_PEM:
default:
return "-----BEGIN X509 CRL-----\r\n" . chunk_split(base64_encode($crl), 64) . '-----END X509 CRL-----';
}
}
/**
* Helper function to build a time field according to RFC 3280 section
* - 4.1.2.5 Validity
* - 5.1.2.4 This Update
* - 5.1.2.5 Next Update
* - 5.1.2.6 Revoked Certificates
* by choosing utcTime iff year of date given is before 2050 and generalTime else.
*
* @param string $date in format date('D, d M Y H:i:s O')
* @access private
* @return array
*/
function _timeField($date)
{
$year = @gmdate("Y", @strtotime($date)); // the same way ASN1.php parses this
if ($year < 2050) {
return array('utcTime' => $date);
} else {
return array('generalTime' => $date);
}
}
/**
* Sign an X.509 certificate
*
* $issuer's private key needs to be loaded.
* $subject can be either an existing X.509 cert (if you want to resign it),
* a CSR or something with the DN and public key explicitly set.
*
* @param \phpseclib\File\X509 $issuer
* @param \phpseclib\File\X509 $subject
* @param string $signatureAlgorithm optional
* @access public
* @return mixed
*/
function sign($issuer, $subject, $signatureAlgorithm = 'sha1WithRSAEncryption')
{
if (!is_object($issuer->privateKey) || empty($issuer->dn)) {
return false;
}
if (isset($subject->publicKey) && !($subjectPublicKey = $subject->_formatSubjectPublicKey())) {
return false;
}
$currentCert = isset($this->currentCert) ? $this->currentCert : null;
$signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: null;
if (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertificate'])) {
$this->currentCert = $subject->currentCert;
$this->currentCert['tbsCertificate']['signature']['algorithm'] = $signatureAlgorithm;
$this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm;
if (!empty($this->startDate)) {
$this->currentCert['tbsCertificate']['validity']['notBefore'] = $this->_timeField($this->startDate);
}
if (!empty($this->endDate)) {
$this->currentCert['tbsCertificate']['validity']['notAfter'] = $this->_timeField($this->endDate);
}
if (!empty($this->serialNumber)) {
$this->currentCert['tbsCertificate']['serialNumber'] = $this->serialNumber;
}
if (!empty($subject->dn)) {
$this->currentCert['tbsCertificate']['subject'] = $subject->dn;
}
if (!empty($subject->publicKey)) {
$this->currentCert['tbsCertificate']['subjectPublicKeyInfo'] = $subjectPublicKey;
}
$this->removeExtension('id-ce-authorityKeyIdentifier');
if (isset($subject->domains)) {
$this->removeExtension('id-ce-subjectAltName');
}
} elseif (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertList'])) {
return false;
} else {
if (!isset($subject->publicKey)) {
return false;
}
$startDate = !empty($this->startDate) ? $this->startDate : @date('D, d M Y H:i:s O');
$endDate = !empty($this->endDate) ? $this->endDate : @date('D, d M Y H:i:s O', strtotime('+1 year'));
/* "The serial number MUST be a positive integer"
"Conforming CAs MUST NOT use serialNumber values longer than 20 octets."
-- https://tools.ietf.org/html/rfc5280#section-4.1.2.2
for the integer to be positive the leading bit needs to be 0 hence the
application of a bitmap
*/
$serialNumber = !empty($this->serialNumber) ?
$this->serialNumber :
new BigInteger(Random::string(20) & ("\x7F" . str_repeat("\xFF", 19)), 256);
$this->currentCert = array(
'tbsCertificate' =>
array(
'version' => 'v3',
'serialNumber' => $serialNumber, // $this->setserialNumber()
'signature' => array('algorithm' => $signatureAlgorithm),
'issuer' => false, // this is going to be overwritten later
'validity' => array(
'notBefore' => $this->_timeField($startDate), // $this->setStartDate()
'notAfter' => $this->_timeField($endDate) // $this->setEndDate()
),
'subject' => $subject->dn,
'subjectPublicKeyInfo' => $subjectPublicKey
),
'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm),
'signature' => false // this is going to be overwritten later
);
// Copy extensions from CSR.
$csrexts = $subject->getAttribute('pkcs-9-at-extensionRequest', 0);
if (!empty($csrexts)) {
$this->currentCert['tbsCertificate']['extensions'] = $csrexts;
}
}
$this->currentCert['tbsCertificate']['issuer'] = $issuer->dn;
if (isset($issuer->currentKeyIdentifier)) {
$this->setExtension('id-ce-authorityKeyIdentifier', array(
//'authorityCertIssuer' => array(
// array(
// 'directoryName' => $issuer->dn
// )
//),
'keyIdentifier' => $issuer->currentKeyIdentifier
));
//$extensions = &$this->currentCert['tbsCertificate']['extensions'];
//if (isset($issuer->serialNumber)) {
// $extensions[count($extensions) - 1]['authorityCertSerialNumber'] = $issuer->serialNumber;
//}
//unset($extensions);
}
if (isset($subject->currentKeyIdentifier)) {
$this->setExtension('id-ce-subjectKeyIdentifier', $subject->currentKeyIdentifier);
}
$altName = array();
if (isset($subject->domains) && count($subject->domains) > 1) {
$altName = array_map(array('X509', '_dnsName'), $subject->domains);
}
if (isset($subject->ipAddresses) && count($subject->ipAddresses)) {
// should an IP address appear as the CN if no domain name is specified? idk
//$ips = count($subject->domains) ? $subject->ipAddresses : array_slice($subject->ipAddresses, 1);
$ipAddresses = array();
foreach ($subject->ipAddresses as $ipAddress) {
$encoded = $subject->_ipAddress($ipAddress);
if ($encoded !== false) {
$ipAddresses[] = $encoded;
}
}
if (count($ipAddresses)) {
$altName = array_merge($altName, $ipAddresses);
}
}
if (!empty($altName)) {
$this->setExtension('id-ce-subjectAltName', $altName);
}
if ($this->caFlag) {
$keyUsage = $this->getExtension('id-ce-keyUsage');
if (!$keyUsage) {
$keyUsage = array();
}
$this->setExtension(
'id-ce-keyUsage',
array_values(array_unique(array_merge($keyUsage, array('cRLSign', 'keyCertSign'))))
);
$basicConstraints = $this->getExtension('id-ce-basicConstraints');
if (!$basicConstraints) {
$basicConstraints = array();
}
$this->setExtension(
'id-ce-basicConstraints',
array_unique(array_merge(array('cA' => true), $basicConstraints)),
true
);
if (!isset($subject->currentKeyIdentifier)) {
$this->setExtension('id-ce-subjectKeyIdentifier', base64_encode($this->computeKeyIdentifier($this->currentCert)), false, false);
}
}
// resync $this->signatureSubject
// save $tbsCertificate in case there are any \phpseclib\File\ASN1\Element objects in it
$tbsCertificate = $this->currentCert['tbsCertificate'];
$this->loadX509($this->saveX509($this->currentCert));
$result = $this->_sign($issuer->privateKey, $signatureAlgorithm);
$result['tbsCertificate'] = $tbsCertificate;
$this->currentCert = $currentCert;
$this->signatureSubject = $signatureSubject;
return $result;
}
/**
* Sign a CSR
*
* @access public
* @return mixed
*/
function signCSR($signatureAlgorithm = 'sha1WithRSAEncryption')
{
if (!is_object($this->privateKey) || empty($this->dn)) {
return false;
}
$origPublicKey = $this->publicKey;
$class = get_class($this->privateKey);
$this->publicKey = new $class();
$this->publicKey->load($this->privateKey->getPublicKey());
$this->publicKey->setPublicKey();
if (!($publicKey = $this->_formatSubjectPublicKey())) {
return false;
}
$this->publicKey = $origPublicKey;
$currentCert = isset($this->currentCert) ? $this->currentCert : null;
$signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: null;
if (isset($this->currentCert) && is_array($this->currentCert) && isset($this->currentCert['certificationRequestInfo'])) {
$this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm;
if (!empty($this->dn)) {
$this->currentCert['certificationRequestInfo']['subject'] = $this->dn;
}
$this->currentCert['certificationRequestInfo']['subjectPKInfo'] = $publicKey;
} else {
$this->currentCert = array(
'certificationRequestInfo' =>
array(
'version' => 'v1',
'subject' => $this->dn,
'subjectPKInfo' => $publicKey
),
'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm),
'signature' => false // this is going to be overwritten later
);
}
// resync $this->signatureSubject
// save $certificationRequestInfo in case there are any \phpseclib\File\ASN1\Element objects in it
$certificationRequestInfo = $this->currentCert['certificationRequestInfo'];
$this->loadCSR($this->saveCSR($this->currentCert));
$result = $this->_sign($this->privateKey, $signatureAlgorithm);
$result['certificationRequestInfo'] = $certificationRequestInfo;
$this->currentCert = $currentCert;
$this->signatureSubject = $signatureSubject;
return $result;
}
/**
* Sign a SPKAC
*
* @access public
* @return mixed
*/
function signSPKAC($signatureAlgorithm = 'sha1WithRSAEncryption')
{
if (!is_object($this->privateKey)) {
return false;
}
$origPublicKey = $this->publicKey;
$class = get_class($this->privateKey);
$this->publicKey = new $class();
$this->publicKey->load($this->privateKey->getPublicKey());
$this->publicKey->setPublicKey();
$publicKey = $this->_formatSubjectPublicKey();
if (!$publicKey) {
return false;
}
$this->publicKey = $origPublicKey;
$currentCert = isset($this->currentCert) ? $this->currentCert : null;
$signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: null;
// re-signing a SPKAC seems silly but since everything else supports re-signing why not?
if (isset($this->currentCert) && is_array($this->currentCert) && isset($this->currentCert['publicKeyAndChallenge'])) {
$this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm;
$this->currentCert['publicKeyAndChallenge']['spki'] = $publicKey;
if (!empty($this->challenge)) {
// the bitwise AND ensures that the output is a valid IA5String
$this->currentCert['publicKeyAndChallenge']['challenge'] = $this->challenge & str_repeat("\x7F", strlen($this->challenge));
}
} else {
$this->currentCert = array(
'publicKeyAndChallenge' =>
array(
'spki' => $publicKey,
// quoting <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen>,
// "A challenge string that is submitted along with the public key. Defaults to an empty string if not specified."
// both Firefox and OpenSSL ("openssl spkac -key private.key") behave this way
// we could alternatively do this instead if we ignored the specs:
// Random::string(8) & str_repeat("\x7F", 8)
'challenge' => !empty($this->challenge) ? $this->challenge : ''
),
'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm),
'signature' => false // this is going to be overwritten later
);
}
// resync $this->signatureSubject
// save $publicKeyAndChallenge in case there are any \phpseclib\File\ASN1\Element objects in it
$publicKeyAndChallenge = $this->currentCert['publicKeyAndChallenge'];
$this->loadSPKAC($this->saveSPKAC($this->currentCert));
$result = $this->_sign($this->privateKey, $signatureAlgorithm);
$result['publicKeyAndChallenge'] = $publicKeyAndChallenge;
$this->currentCert = $currentCert;
$this->signatureSubject = $signatureSubject;
return $result;
}
/**
* Sign a CRL
*
* $issuer's private key needs to be loaded.
*
* @param \phpseclib\File\X509 $issuer
* @param \phpseclib\File\X509 $crl
* @param string $signatureAlgorithm optional
* @access public
* @return mixed
*/
function signCRL($issuer, $crl, $signatureAlgorithm = 'sha1WithRSAEncryption')
{
if (!is_object($issuer->privateKey) || empty($issuer->dn)) {
return false;
}
$currentCert = isset($this->currentCert) ? $this->currentCert : null;
$signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject : null;
$thisUpdate = !empty($this->startDate) ? $this->startDate : @date('D, d M Y H:i:s O');
if (isset($crl->currentCert) && is_array($crl->currentCert) && isset($crl->currentCert['tbsCertList'])) {
$this->currentCert = $crl->currentCert;
$this->currentCert['tbsCertList']['signature']['algorithm'] = $signatureAlgorithm;
$this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm;
} else {
$this->currentCert = array(
'tbsCertList' =>
array(
'version' => 'v2',
'signature' => array('algorithm' => $signatureAlgorithm),
'issuer' => false, // this is going to be overwritten later
'thisUpdate' => $this->_timeField($thisUpdate) // $this->setStartDate()
),
'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm),
'signature' => false // this is going to be overwritten later
);
}
$tbsCertList = &$this->currentCert['tbsCertList'];
$tbsCertList['issuer'] = $issuer->dn;
$tbsCertList['thisUpdate'] = $this->_timeField($thisUpdate);
if (!empty($this->endDate)) {
$tbsCertList['nextUpdate'] = $this->_timeField($this->endDate); // $this->setEndDate()
} else {
unset($tbsCertList['nextUpdate']);
}
if (!empty($this->serialNumber)) {
$crlNumber = $this->serialNumber;
} else {
$crlNumber = $this->getExtension('id-ce-cRLNumber');
// "The CRL number is a non-critical CRL extension that conveys a
// monotonically increasing sequence number for a given CRL scope and
// CRL issuer. This extension allows users to easily determine when a
// particular CRL supersedes another CRL."
// -- https://tools.ietf.org/html/rfc5280#section-5.2.3
$crlNumber = $crlNumber !== false ? $crlNumber->add(new BigInteger(1)) : null;
}
$this->removeExtension('id-ce-authorityKeyIdentifier');
$this->removeExtension('id-ce-issuerAltName');
// Be sure version >= v2 if some extension found.
$version = isset($tbsCertList['version']) ? $tbsCertList['version'] : 0;
if (!$version) {
if (!empty($tbsCertList['crlExtensions'])) {
$version = 1; // v2.
} elseif (!empty($tbsCertList['revokedCertificates'])) {
foreach ($tbsCertList['revokedCertificates'] as $cert) {
if (!empty($cert['crlEntryExtensions'])) {
$version = 1; // v2.
}
}
}
if ($version) {
$tbsCertList['version'] = $version;
}
}
// Store additional extensions.
if (!empty($tbsCertList['version'])) { // At least v2.
if (!empty($crlNumber)) {
$this->setExtension('id-ce-cRLNumber', $crlNumber);
}
if (isset($issuer->currentKeyIdentifier)) {
$this->setExtension('id-ce-authorityKeyIdentifier', array(
//'authorityCertIssuer' => array(
// array(
// 'directoryName' => $issuer->dn
// )
//),
'keyIdentifier' => $issuer->currentKeyIdentifier
));
//$extensions = &$tbsCertList['crlExtensions'];
//if (isset($issuer->serialNumber)) {
// $extensions[count($extensions) - 1]['authorityCertSerialNumber'] = $issuer->serialNumber;
//}
//unset($extensions);
}
$issuerAltName = $this->getExtension('id-ce-subjectAltName', $issuer->currentCert);
if ($issuerAltName !== false) {
$this->setExtension('id-ce-issuerAltName', $issuerAltName);
}
}
if (empty($tbsCertList['revokedCertificates'])) {
unset($tbsCertList['revokedCertificates']);
}
unset($tbsCertList);
// resync $this->signatureSubject
// save $tbsCertList in case there are any \phpseclib\File\ASN1\Element objects in it
$tbsCertList = $this->currentCert['tbsCertList'];
$this->loadCRL($this->saveCRL($this->currentCert));
$result = $this->_sign($issuer->privateKey, $signatureAlgorithm);
$result['tbsCertList'] = $tbsCertList;
$this->currentCert = $currentCert;
$this->signatureSubject = $signatureSubject;
return $result;
}
/**
* X.509 certificate signing helper function.
*
* @param object $key
* @param \phpseclib\File\X509 $subject
* @param string $signatureAlgorithm
* @access public
* @throws \phpseclib\Exception\UnsupportedAlgorithmException if the algorithm is unsupported
* @return mixed
*/
function _sign($key, $signatureAlgorithm)
{
if ($key instanceof RSA) {
switch ($signatureAlgorithm) {
case 'md2WithRSAEncryption':
case 'md5WithRSAEncryption':
case 'sha1WithRSAEncryption':
case 'sha224WithRSAEncryption':
case 'sha256WithRSAEncryption':
case 'sha384WithRSAEncryption':
case 'sha512WithRSAEncryption':
$key->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm));
$key->setSignatureMode(RSA::SIGNATURE_PKCS1);
$this->currentCert['signature'] = base64_encode("\0" . $key->sign($this->signatureSubject));
return $this->currentCert;
default:
throw new UnsupportedAlgorithmException('Signature algorithm unsupported');
}
}
throw new UnsupportedAlgorithmException('Unsupported public key algorithm');
}
/**
* Set certificate start date
*
* @param string $date
* @access public
*/
function setStartDate($date)
{
$this->startDate = @date('D, d M Y H:i:s O', @strtotime($date));
}
/**
* Set certificate end date
*
* @param string $date
* @access public
*/
function setEndDate($date)
{
/*
To indicate that a certificate has no well-defined expiration date,
the notAfter SHOULD be assigned the GeneralizedTime value of
99991231235959Z.
-- http://tools.ietf.org/html/rfc5280#section-4.1.2.5
*/
if (strtolower($date) == 'lifetime') {
$temp = '99991231235959Z';
$asn1 = new ASN1();
$temp = chr(ASN1::TYPE_GENERALIZED_TIME) . $asn1->_encodeLength(strlen($temp)) . $temp;
$this->endDate = new Element($temp);
} else {
$this->endDate = @date('D, d M Y H:i:s O', @strtotime($date));
}
}
/**
* Set Serial Number
*
* @param string $serial
* @param $base optional
* @access public
*/
function setSerialNumber($serial, $base = -256)
{
$this->serialNumber = new BigInteger($serial, $base);
}
/**
* Turns the certificate into a certificate authority
*
* @access public
*/
function makeCA()
{
$this->caFlag = true;
}
/**
* Get a reference to a subarray
*
* @param array $root
* @param string $path absolute path with / as component separator
* @param bool $create optional
* @access private
* @return array|false
*/
function &_subArray(&$root, $path, $create = false)
{
$false = false;
if (!is_array($root)) {
return $false;
}
foreach (explode('/', $path) as $i) {
if (!is_array($root)) {
return $false;
}
if (!isset($root[$i])) {
if (!$create) {
return $false;
}
$root[$i] = array();
}
$root = &$root[$i];
}
return $root;
}
/**
* Get a reference to an extension subarray
*
* @param array $root
* @param string $path optional absolute path with / as component separator
* @param bool $create optional
* @access private
* @return array|false
*/
function &_extensions(&$root, $path = null, $create = false)
{
if (!isset($root)) {
$root = $this->currentCert;
}
switch (true) {
case !empty($path):
case !is_array($root):
break;
case isset($root['tbsCertificate']):
$path = 'tbsCertificate/extensions';
break;
case isset($root['tbsCertList']):
$path = 'tbsCertList/crlExtensions';
break;
case isset($root['certificationRequestInfo']):
$pth = 'certificationRequestInfo/attributes';
$attributes = &$this->_subArray($root, $pth, $create);
if (is_array($attributes)) {
foreach ($attributes as $key => $value) {
if ($value['type'] == 'pkcs-9-at-extensionRequest') {
$path = "$pth/$key/value/0";
break 2;
}
}
if ($create) {
$key = count($attributes);
$attributes[] = array('type' => 'pkcs-9-at-extensionRequest', 'value' => array());
$path = "$pth/$key/value/0";
}
}
break;
}
$extensions = &$this->_subArray($root, $path, $create);
if (!is_array($extensions)) {
$false = false;
return $false;
}
return $extensions;
}
/**
* Remove an Extension
*
* @param string $id
* @param string $path optional
* @access private
* @return bool
*/
function _removeExtension($id, $path = null)
{
$extensions = &$this->_extensions($this->currentCert, $path);
if (!is_array($extensions)) {
return false;
}
$result = false;
foreach ($extensions as $key => $value) {
if ($value['extnId'] == $id) {
unset($extensions[$key]);
$result = true;
}
}
$extensions = array_values($extensions);
return $result;
}
/**
* Get an Extension
*
* Returns the extension if it exists and false if not
*
* @param string $id
* @param array $cert optional
* @param string $path optional
* @access private
* @return mixed
*/
function _getExtension($id, $cert = null, $path = null)
{
$extensions = $this->_extensions($cert, $path);
if (!is_array($extensions)) {
return false;
}
foreach ($extensions as $key => $value) {
if ($value['extnId'] == $id) {
return $value['extnValue'];
}
}
return false;
}
/**
* Returns a list of all extensions in use
*
* @param array $cert optional
* @param string $path optional
* @access private
* @return array
*/
function _getExtensions($cert = null, $path = null)
{
$exts = $this->_extensions($cert, $path);
$extensions = array();
if (is_array($exts)) {
foreach ($exts as $extension) {
$extensions[] = $extension['extnId'];
}
}
return $extensions;
}
/**
* Set an Extension
*
* @param string $id
* @param mixed $value
* @param bool $critical optional
* @param bool $replace optional
* @param string $path optional
* @access private
* @return bool
*/
function _setExtension($id, $value, $critical = false, $replace = true, $path = null)
{
$extensions = &$this->_extensions($this->currentCert, $path, true);
if (!is_array($extensions)) {
return false;
}
$newext = array('extnId' => $id, 'critical' => $critical, 'extnValue' => $value);
foreach ($extensions as $key => $value) {
if ($value['extnId'] == $id) {
if (!$replace) {
return false;
}
$extensions[$key] = $newext;
return true;
}
}
$extensions[] = $newext;
return true;
}
/**
* Remove a certificate, CSR or CRL Extension
*
* @param string $id
* @access public
* @return bool
*/
function removeExtension($id)
{
return $this->_removeExtension($id);
}
/**
* Get a certificate, CSR or CRL Extension
*
* Returns the extension if it exists and false if not
*
* @param string $id
* @param array $cert optional
* @access public
* @return mixed
*/
function getExtension($id, $cert = null)
{
return $this->_getExtension($id, $cert);
}
/**
* Returns a list of all extensions in use in certificate, CSR or CRL
*
* @param array $cert optional
* @access public
* @return array
*/
function getExtensions($cert = null)
{
return $this->_getExtensions($cert);
}
/**
* Set a certificate, CSR or CRL Extension
*
* @param string $id
* @param mixed $value
* @param bool $critical optional
* @param bool $replace optional
* @access public
* @return bool
*/
function setExtension($id, $value, $critical = false, $replace = true)
{
return $this->_setExtension($id, $value, $critical, $replace);
}
/**
* Remove a CSR attribute.
*
* @param string $id
* @param int $disposition optional
* @access public
* @return bool
*/
function removeAttribute($id, $disposition = self::ATTR_ALL)
{
$attributes = &$this->_subArray($this->currentCert, 'certificationRequestInfo/attributes');
if (!is_array($attributes)) {
return false;
}
$result = false;
foreach ($attributes as $key => $attribute) {
if ($attribute['type'] == $id) {
$n = count($attribute['value']);
switch (true) {
case $disposition == self::ATTR_APPEND:
case $disposition == self::ATTR_REPLACE:
return false;
case $disposition >= $n:
$disposition -= $n;
break;
case $disposition == self::ATTR_ALL:
case $n == 1:
unset($attributes[$key]);
$result = true;
break;
default:
unset($attributes[$key]['value'][$disposition]);
$attributes[$key]['value'] = array_values($attributes[$key]['value']);
$result = true;
break;
}
if ($result && $disposition != self::ATTR_ALL) {
break;
}
}
}
$attributes = array_values($attributes);
return $result;
}
/**
* Get a CSR attribute
*
* Returns the attribute if it exists and false if not
*
* @param string $id
* @param int $disposition optional
* @param array $csr optional
* @access public
* @return mixed
*/
function getAttribute($id, $disposition = self::ATTR_ALL, $csr = null)
{
if (empty($csr)) {
$csr = $this->currentCert;
}
$attributes = $this->_subArray($csr, 'certificationRequestInfo/attributes');
if (!is_array($attributes)) {
return false;
}
foreach ($attributes as $key => $attribute) {
if ($attribute['type'] == $id) {
$n = count($attribute['value']);
switch (true) {
case $disposition == self::ATTR_APPEND:
case $disposition == self::ATTR_REPLACE:
return false;
case $disposition == self::ATTR_ALL:
return $attribute['value'];
case $disposition >= $n:
$disposition -= $n;
break;
default:
return $attribute['value'][$disposition];
}
}
}
return false;
}
/**
* Returns a list of all CSR attributes in use
*
* @param array $csr optional
* @access public
* @return array
*/
function getAttributes($csr = null)
{
if (empty($csr)) {
$csr = $this->currentCert;
}
$attributes = $this->_subArray($csr, 'certificationRequestInfo/attributes');
$attrs = array();
if (is_array($attributes)) {
foreach ($attributes as $attribute) {
$attrs[] = $attribute['type'];
}
}
return $attrs;
}
/**
* Set a CSR attribute
*
* @param string $id
* @param mixed $value
* @param bool $disposition optional
* @access public
* @return bool
*/
function setAttribute($id, $value, $disposition = self::ATTR_ALL)
{
$attributes = &$this->_subArray($this->currentCert, 'certificationRequestInfo/attributes', true);
if (!is_array($attributes)) {
return false;
}
switch ($disposition) {
case self::ATTR_REPLACE:
$disposition = self::ATTR_APPEND;
case self::ATTR_ALL:
$this->removeAttribute($id);
break;
}
foreach ($attributes as $key => $attribute) {
if ($attribute['type'] == $id) {
$n = count($attribute['value']);
switch (true) {
case $disposition == self::ATTR_APPEND:
$last = $key;
break;
case $disposition >= $n:
$disposition -= $n;
break;
default:
$attributes[$key]['value'][$disposition] = $value;
return true;
}
}
}
switch (true) {
case $disposition >= 0:
return false;
case isset($last):
$attributes[$last]['value'][] = $value;
break;
default:
$attributes[] = array('type' => $id, 'value' => $disposition == self::ATTR_ALL ? $value: array($value));
break;
}
return true;
}
/**
* Sets the subject key identifier
*
* This is used by the id-ce-authorityKeyIdentifier and the id-ce-subjectKeyIdentifier extensions.
*
* @param string $value
* @access public
*/
function setKeyIdentifier($value)
{
if (empty($value)) {
unset($this->currentKeyIdentifier);
} else {
$this->currentKeyIdentifier = base64_encode($value);
}
}
/**
* Compute a public key identifier.
*
* Although key identifiers may be set to any unique value, this function
* computes key identifiers from public key according to the two
* recommended methods (4.2.1.2 RFC 3280).
* Highly polymorphic: try to accept all possible forms of key:
* - Key object
* - \phpseclib\File\X509 object with public or private key defined
* - Certificate or CSR array
* - \phpseclib\File\ASN1\Element object
* - PEM or DER string
*
* @param mixed $key optional
* @param int $method optional
* @access public
* @return string binary key identifier
*/
function computeKeyIdentifier($key = null, $method = 1)
{
if (is_null($key)) {
$key = $this;
}
switch (true) {
case is_string($key):
break;
case is_array($key) && isset($key['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']):
return $this->computeKeyIdentifier($key['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'], $method);
case is_array($key) && isset($key['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']):
return $this->computeKeyIdentifier($key['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'], $method);
case !is_object($key):
return false;
case $key instanceof Element:
// Assume the element is a bitstring-packed key.
$asn1 = new ASN1();
$decoded = $asn1->decodeBER($key->element);
if (empty($decoded)) {
return false;
}
$raw = $asn1->asn1map($decoded[0], array('type' => ASN1::TYPE_BIT_STRING));
if (empty($raw)) {
return false;
}
$raw = base64_decode($raw);
// If the key is private, compute identifier from its corresponding public key.
$key = new RSA();
if (!$key->load($raw)) {
return false; // Not an unencrypted RSA key.
}
if ($key->getPrivateKey() !== false) { // If private.
return $this->computeKeyIdentifier($key, $method);
}
$key = $raw; // Is a public key.
break;
case $key instanceof X509:
if (isset($key->publicKey)) {
return $this->computeKeyIdentifier($key->publicKey, $method);
}
if (isset($key->privateKey)) {
return $this->computeKeyIdentifier($key->privateKey, $method);
}
if (isset($key->currentCert['tbsCertificate']) || isset($key->currentCert['certificationRequestInfo'])) {
return $this->computeKeyIdentifier($key->currentCert, $method);
}
return false;
default: // Should be a key object (i.e.: \phpseclib\Crypt\RSA).
$key = $key->getPublicKey('PKCS1');
break;
}
// If in PEM format, convert to binary.
$key = $this->_extractBER($key);
// Now we have the key string: compute its sha-1 sum.
$hash = new Hash('sha1');
$hash = $hash->hash($key);
if ($method == 2) {
$hash = substr($hash, -8);
$hash[0] = chr((ord($hash[0]) & 0x0F) | 0x40);
}
return $hash;
}
/**
* Format a public key as appropriate
*
* @access private
* @return array
*/
function _formatSubjectPublicKey()
{
if ($this->publicKey instanceof RSA) {
// the following two return statements do the same thing. i dunno.. i just prefer the later for some reason.
// the former is a good example of how to do fuzzing on the public key
//return new Element(base64_decode(preg_replace('#-.+-|[\r\n]#', '', $this->publicKey->getPublicKey())));
return array(
'algorithm' => array('algorithm' => 'rsaEncryption'),
'subjectPublicKey' => $this->publicKey->getPublicKey('PKCS1')
);
}
return false;
}
/**
* Set the domain name's which the cert is to be valid for
*
* @access public
* @return array
*/
function setDomain()
{
$this->domains = func_get_args();
$this->removeDNProp('id-at-commonName');
$this->setDNProp('id-at-commonName', $this->domains[0]);
}
/**
* Set the IP Addresses's which the cert is to be valid for
*
* @access public
* @param string $ipAddress optional
*/
function setIPAddress()
{
$this->ipAddresses = func_get_args();
/*
if (!isset($this->domains)) {
$this->removeDNProp('id-at-commonName');
$this->setDNProp('id-at-commonName', $this->ipAddresses[0]);
}
*/
}
/**
* Helper function to build domain array
*
* @access private
* @param string $domain
* @return array
*/
function _dnsName($domain)
{
return array('dNSName' => $domain);
}
/**
* Helper function to build IP Address array
*
* (IPv6 is not currently supported)
*
* @access private
* @param string $address
* @return array
*/
function _iPAddress($address)
{
return array('iPAddress' => $address);
}
/**
* Get the index of a revoked certificate.
*
* @param array $rclist
* @param string $serial
* @param bool $create optional
* @access private
* @return int|false
*/
function _revokedCertificate(&$rclist, $serial, $create = false)
{
$serial = new BigInteger($serial);
foreach ($rclist as $i => $rc) {
if (!($serial->compare($rc['userCertificate']))) {
return $i;
}
}
if (!$create) {
return false;
}
$i = count($rclist);
$rclist[] = array('userCertificate' => $serial,
'revocationDate' => $this->_timeField(@date('D, d M Y H:i:s O')));
return $i;
}
/**
* Revoke a certificate.
*
* @param string $serial
* @param string $date optional
* @access public
* @return bool
*/
function revoke($serial, $date = null)
{
if (isset($this->currentCert['tbsCertList'])) {
if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates', true))) {
if ($this->_revokedCertificate($rclist, $serial) === false) { // If not yet revoked
if (($i = $this->_revokedCertificate($rclist, $serial, true)) !== false) {
if (!empty($date)) {
$rclist[$i]['revocationDate'] = $this->_timeField($date);
}
return true;
}
}
}
}
return false;
}
/**
* Unrevoke a certificate.
*
* @param string $serial
* @access public
* @return bool
*/
function unrevoke($serial)
{
if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates'))) {
if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) {
unset($rclist[$i]);
$rclist = array_values($rclist);
return true;
}
}
return false;
}
/**
* Get a revoked certificate.
*
* @param string $serial
* @access public
* @return mixed
*/
function getRevoked($serial)
{
if (is_array($rclist = $this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates'))) {
if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) {
return $rclist[$i];
}
}
return false;
}
/**
* List revoked certificates
*
* @param array $crl optional
* @access public
* @return array
*/
function listRevoked($crl = null)
{
if (!isset($crl)) {
$crl = $this->currentCert;
}
if (!isset($crl['tbsCertList'])) {
return false;
}
$result = array();
if (is_array($rclist = $this->_subArray($crl, 'tbsCertList/revokedCertificates'))) {
foreach ($rclist as $rc) {
$result[] = $rc['userCertificate']->toString();
}
}
return $result;
}
/**
* Remove a Revoked Certificate Extension
*
* @param string $serial
* @param string $id
* @access public
* @return bool
*/
function removeRevokedCertificateExtension($serial, $id)
{
if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates'))) {
if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) {
return $this->_removeExtension($id, "tbsCertList/revokedCertificates/$i/crlEntryExtensions");
}
}
return false;
}
/**
* Get a Revoked Certificate Extension
*
* Returns the extension if it exists and false if not
*
* @param string $serial
* @param string $id
* @param array $crl optional
* @access public
* @return mixed
*/
function getRevokedCertificateExtension($serial, $id, $crl = null)
{
if (!isset($crl)) {
$crl = $this->currentCert;
}
if (is_array($rclist = $this->_subArray($crl, 'tbsCertList/revokedCertificates'))) {
if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) {
return $this->_getExtension($id, $crl, "tbsCertList/revokedCertificates/$i/crlEntryExtensions");
}
}
return false;
}
/**
* Returns a list of all extensions in use for a given revoked certificate
*
* @param string $serial
* @param array $crl optional
* @access public
* @return array
*/
function getRevokedCertificateExtensions($serial, $crl = null)
{
if (!isset($crl)) {
$crl = $this->currentCert;
}
if (is_array($rclist = $this->_subArray($crl, 'tbsCertList/revokedCertificates'))) {
if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) {
return $this->_getExtensions($crl, "tbsCertList/revokedCertificates/$i/crlEntryExtensions");
}
}
return false;
}
/**
* Set a Revoked Certificate Extension
*
* @param string $serial
* @param string $id
* @param mixed $value
* @param bool $critical optional
* @param bool $replace optional
* @access public
* @return bool
*/
function setRevokedCertificateExtension($serial, $id, $value, $critical = false, $replace = true)
{
if (isset($this->currentCert['tbsCertList'])) {
if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates', true))) {
if (($i = $this->_revokedCertificate($rclist, $serial, true)) !== false) {
return $this->_setExtension($id, $value, $critical, $replace, "tbsCertList/revokedCertificates/$i/crlEntryExtensions");
}
}
}
return false;
}
/**
* Extract raw BER from Base64 encoding
*
* @access private
* @param string $str
* @return string
*/
function _extractBER($str)
{
/* X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them
* above and beyond the ceritificate.
* ie. some may have the following preceding the -----BEGIN CERTIFICATE----- line:
*
* Bag Attributes
* localKeyID: 01 00 00 00
* subject=/O=organization/OU=org unit/CN=common name
* issuer=/O=organization/CN=common name
*/
$temp = preg_replace('#.*?^-+[^-]+-+[\r\n ]*$#ms', '', $str, 1);
// remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff
$temp = preg_replace('#-+[^-]+-+#', '', $temp);
// remove new lines
$temp = str_replace(array("\r", "\n", ' '), '', $temp);
$temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false;
return $temp != false ? $temp : $str;
}
/**
* Returns the OID corresponding to a name
*
* What's returned in the associative array returned by loadX509() (or load*()) is either a name or an OID if
* no OID to name mapping is available. The problem with this is that what may be an unmapped OID in one version
* of phpseclib may not be unmapped in the next version, so apps that are looking at this OID may not be able
* to work from version to version.
*
* This method will return the OID if a name is passed to it and if no mapping is avialable it'll assume that
* what's being passed to it already is an OID and return that instead. A few examples.
*
* getOID('2.16.840.1.101.3.4.2.1') == '2.16.840.1.101.3.4.2.1'
* getOID('id-sha256') == '2.16.840.1.101.3.4.2.1'
* getOID('zzz') == 'zzz'
*
* @access public
* @return string
*/
function getOID($name)
{
static $reverseMap;
if (!isset($reverseMap)) {
$reverseMap = array_flip($this->oids);
}
return isset($reverseMap[$name]) ? $reverseMap[$name] : $name;
}
}
|
msulistijo/PhpseclibBundle
|
Utility/File/X509.php
|
PHP
|
mit
| 171,446
|
package provider
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"math/big"
"net/http"
"net/url"
"strings"
"time"
"github.com/netlify/gotrue/models"
"github.com/netlify/gotrue/storage"
"github.com/netlify/gotrue/conf"
saml2 "github.com/russellhaering/gosaml2"
"github.com/russellhaering/gosaml2/types"
dsig "github.com/russellhaering/goxmldsig"
"github.com/gobuffalo/uuid"
"golang.org/x/oauth2"
)
type SamlProvider struct {
ServiceProvider *saml2.SAMLServiceProvider
}
type ConfigX509KeyStore struct {
InstanceID uuid.UUID
DB *storage.Connection
Conf conf.SamlProviderConfiguration
}
func getMetadata(url string) (*types.EntityDescriptor, error) {
res, err := http.Get(url)
if err != nil {
return nil, err
}
if res.StatusCode >= 300 {
return nil, fmt.Errorf("Request failed with status %s", res.Status)
}
rawMetadata, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
metadata := &types.EntityDescriptor{}
err = xml.Unmarshal(rawMetadata, metadata)
if err != nil {
return nil, err
}
// TODO: cache in memory
return metadata, nil
}
// NewSamlProvider creates a Saml account provider.
func NewSamlProvider(ext conf.SamlProviderConfiguration, db *storage.Connection, instanceId uuid.UUID) (*SamlProvider, error) {
if !ext.Enabled {
return nil, errors.New("SAML Provider is not enabled")
}
if _, err := url.Parse(ext.MetadataURL); err != nil {
return nil, fmt.Errorf("Metadata URL is invalid: %+v", err)
}
meta, err := getMetadata(ext.MetadataURL)
if err != nil {
return nil, fmt.Errorf("Fetching metadata failed: %+v", err)
}
baseURI, err := url.Parse(strings.Trim(ext.APIBase, "/"))
if err != nil || ext.APIBase == "" {
return nil, fmt.Errorf("Invalid API base URI: %s", ext.APIBase)
}
var ssoService types.SingleSignOnService
foundService := false
for _, service := range meta.IDPSSODescriptor.SingleSignOnServices {
if service.Binding == "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" {
ssoService = service
foundService = true
break
}
}
if !foundService {
return nil, errors.New("No valid SSO service found in IDP metadata")
}
certStore := dsig.MemoryX509CertificateStore{
Roots: []*x509.Certificate{},
}
for _, kd := range meta.IDPSSODescriptor.KeyDescriptors {
for _, xcert := range kd.KeyInfo.X509Data.X509Certificates {
if xcert.Data == "" {
continue
}
certData, err := base64.StdEncoding.DecodeString(xcert.Data)
if err != nil {
continue
}
idpCert, err := x509.ParseCertificate(certData)
if err != nil {
continue
}
certStore.Roots = append(certStore.Roots, idpCert)
}
}
keyStore := &ConfigX509KeyStore{
InstanceID: instanceId,
DB: db,
Conf: ext,
}
sp := &saml2.SAMLServiceProvider{
IdentityProviderSSOURL: ssoService.Location,
IdentityProviderIssuer: meta.EntityID,
AssertionConsumerServiceURL: baseURI.String() + "/saml/acs",
ServiceProviderIssuer: baseURI.String() + "/saml",
SignAuthnRequests: true,
AudienceURI: baseURI.String() + "/saml",
IDPCertificateStore: &certStore,
SPKeyStore: keyStore,
AllowMissingAttributes: true,
}
p := &SamlProvider{
ServiceProvider: sp,
}
return p, nil
}
func (p SamlProvider) AuthCodeURL(tokenString string, args ...oauth2.AuthCodeOption) string {
url, err := p.ServiceProvider.BuildAuthURL(tokenString)
if err != nil {
return ""
}
return url
}
func (p SamlProvider) SPMetadata() ([]byte, error) {
metadata, err := p.ServiceProvider.Metadata()
if err != nil {
return nil, err
}
// the typing for encryption methods currently causes the xml to violate the spec
// therefore they are removed since they are optional anyways and mostly unused
metadata.SPSSODescriptor.KeyDescriptors[1].EncryptionMethods = []types.EncryptionMethod{}
rawMetadata, err := xml.Marshal(metadata)
if err != nil {
return nil, err
}
return rawMetadata, nil
}
func (ks ConfigX509KeyStore) GetKeyPair() (*rsa.PrivateKey, []byte, error) {
if ks.Conf.SigningCert == "" && ks.Conf.SigningKey == "" {
return ks.CreateSigningCert()
}
keyPair, err := tls.X509KeyPair([]byte(ks.Conf.SigningCert), []byte(ks.Conf.SigningKey))
if err != nil {
return nil, nil, fmt.Errorf("Parsing key pair failed: %+v", err)
}
var privKey *rsa.PrivateKey
switch key := keyPair.PrivateKey.(type) {
case *rsa.PrivateKey:
privKey = key
default:
return nil, nil, errors.New("Private key is not an RSA key")
}
return privKey, keyPair.Certificate[0], nil
}
func (ks ConfigX509KeyStore) CreateSigningCert() (*rsa.PrivateKey, []byte, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
currentTime := time.Now()
certBody := &x509.Certificate{
SerialNumber: big.NewInt(1),
NotBefore: currentTime.Add(-5 * time.Minute),
NotAfter: currentTime.Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{},
BasicConstraintsValid: true,
}
cert, err := x509.CreateCertificate(rand.Reader, certBody, certBody, &key.PublicKey, key)
if err != nil {
return nil, nil, fmt.Errorf("Failed to create certificate: %+v", err)
}
if err := ks.SaveConfig(cert, key); err != nil {
return nil, nil, fmt.Errorf("Saving signing keypair failed: %+v", err)
}
return key, cert, nil
}
func (ks ConfigX509KeyStore) SaveConfig(cert []byte, key *rsa.PrivateKey) error {
if ks.InstanceID == uuid.Nil {
return nil
}
pemCert := &pem.Block{
Type: "CERTIFICATE",
Bytes: cert,
}
certBytes := pem.EncodeToMemory(pemCert)
if certBytes == nil {
return errors.New("Could not encode certificate")
}
pemKey := &pem.Block{
Type: "PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
keyBytes := pem.EncodeToMemory(pemKey)
if keyBytes == nil {
return errors.New("Could not encode key")
}
instance, err := models.GetInstance(ks.DB, ks.InstanceID)
if err != nil {
return err
}
conf := instance.BaseConfig
conf.External.Saml.SigningCert = string(certBytes)
conf.External.Saml.SigningKey = string(keyBytes)
if err := instance.UpdateConfig(ks.DB, conf); err != nil {
return err
}
return nil
}
|
netlify/gotrue
|
api/provider/saml.go
|
GO
|
mit
| 6,380
|
all:
$(MAKE) -C ../../ test_credits_qt
clean:
$(MAKE) -C ../../ test_credits_qt_clean
check:
$(MAKE) -C ../../ test_credits_qt_check
|
credits-currency/credits
|
src/qt/test/Makefile
|
Makefile
|
mit
| 136
|
// To check if a library is compiled with CocoaPods you
// can use the `COCOAPODS` macro definition which is
// defined in the xcconfigs so it is available in
// headers also when they are imported in the client
// project.
// WaitBlock
#define COCOAPODS_POD_AVAILABLE_WaitBlock
#define COCOAPODS_VERSION_MAJOR_WaitBlock 0
#define COCOAPODS_VERSION_MINOR_WaitBlock 3
#define COCOAPODS_VERSION_PATCH_WaitBlock 0
|
remirobert/WaitBlock
|
Example/Pods/Target Support Files/Pods/Pods-environment.h
|
C
|
mit
| 415
|
import datetime
import json
from brake.decorators import ratelimit
from django.utils.decorators import method_decorator
from django.utils.translation import get_language
from django.conf import settings
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import redirect
from django.views.generic import FormView
from django.template import RequestContext
import logging
logger = logging.getLogger(__name__)
from django.contrib.admin.views.decorators import staff_member_required
from apps.forms.stages import MultiStageForm
from apps.forms.views import StorageView
from make_a_plea.helpers import (
filter_cases_by_month,
get_supported_language_from_request,
parse_date_or_400,
staff_or_404,
)
from .models import Case, Court, CaseTracker
from .forms import CourtFinderForm
from .stages import (URNEntryStage,
AuthenticationStage,
NoticeTypeStage,
CaseStage,
YourDetailsStage,
CompanyDetailsStage,
PleaStage,
YourStatusStage,
YourEmploymentStage,
YourSelfEmploymentStage,
YourOutOfWorkBenefitsStage,
AboutYourIncomeStage,
YourBenefitsStage,
YourPensionCreditStage,
YourIncomeStage,
HardshipStage,
HouseholdExpensesStage,
OtherExpensesStage,
CompanyFinancesStage,
ReviewStage,
CompleteStage)
from .fields import ERROR_MESSAGES
class PleaOnlineForms(MultiStageForm):
url_name = "plea_form_step"
stage_classes = [URNEntryStage,
AuthenticationStage,
NoticeTypeStage,
CaseStage,
YourDetailsStage,
CompanyDetailsStage,
PleaStage,
YourStatusStage,
YourEmploymentStage,
YourSelfEmploymentStage,
YourOutOfWorkBenefitsStage,
AboutYourIncomeStage,
YourBenefitsStage,
YourPensionCreditStage,
YourIncomeStage,
HardshipStage,
HouseholdExpensesStage,
OtherExpensesStage,
CompanyFinancesStage,
ReviewStage,
CompleteStage]
def __init__(self, *args, **kwargs):
super(PleaOnlineForms, self).__init__(*args, **kwargs)
self._urn_invalid = False
def save(self, *args, **kwargs):
"""
Check that the URN has not already been used.
"""
saved_urn = self.all_data.get("case", {}).get("urn")
saved_first_name = self.all_data.get("your_details", {}).get("first_name")
saved_last_name = self.all_data.get("your_details", {}).get("last_name")
if all([
saved_urn,
saved_first_name,
saved_last_name,
not Case.objects.can_use_urn(saved_urn, saved_first_name, saved_last_name)
]):
self._urn_invalid = True
else:
return super(PleaOnlineForms, self).save(*args, **kwargs)
def render(self, request, request_context=None):
request_context = request_context if request_context else {}
if self._urn_invalid:
return redirect("urn_already_used")
return super(PleaOnlineForms, self).render(request)
class PleaOnlineViews(StorageView):
start = "enter_urn"
def __init__(self, *args, **kwargs):
super(PleaOnlineViews, self).__init__(*args, **kwargs)
self.index = None
self.storage = None
def dispatch(self, request, *args, **kwargs):
# If the session has timed out, redirect to start page
if all([
not request.session.get("plea_data"),
kwargs.get("stage", self.start) != self.start,
]):
return HttpResponseRedirect("/")
# Store the index if we've got one
idx = kwargs.pop("index", None)
try:
self.index = int(idx)
except (ValueError, TypeError):
self.index = 0
# Load storage
self.storage = self.get_storage(request, "plea_data")
return super(PleaOnlineViews, self).dispatch(request, *args, **kwargs)
def get(self, request, stage=None):
if not stage:
stage = PleaOnlineForms.stage_classes[0].name
return HttpResponseRedirect(reverse_lazy("plea_form_step", args=(stage,)))
form = PleaOnlineForms(self.storage, stage, self.index)
case_redirect = form.load(RequestContext(request))
if case_redirect:
return case_redirect
form.process_messages(request)
if stage == "complete":
self.clear_storage(request, "plea_data")
return form.render(request)
@method_decorator(ratelimit(block=True, rate=settings.RATE_LIMIT))
def post(self, request, stage):
nxt = request.GET.get("next", None)
form = PleaOnlineForms(self.storage, stage, self.index)
form.save(request.POST, RequestContext(request), nxt)
if not form._urn_invalid:
form.process_messages(request)
request.session.modified = True
return form.render(request)
def render(self, request, request_context=None):
request_context = request_context if request_context else {}
return super(PleaOnlineViews, self).render(request)
class UrnAlreadyUsedView(StorageView):
template_name = "urn_used.html"
def post(self, request):
del request.session["plea_data"]
return redirect("plea_form_step", stage="case")
class CourtFinderView(FormView):
template_name = "court_finder.html"
form_class = CourtFinderForm
def form_valid(self, form):
try:
court = Court.objects.get_court_dx(form.cleaned_data["urn"])
except Court.DoesNotExist:
court = False
return self.render_to_response(
self.get_context_data(
form=form,
court=court,
submitted=True,
)
)
@staff_or_404
def stats(request):
"""
Generate usage statistics (optionally by language) and send via email
"""
filter_params = {
"sent": True,
"language": get_supported_language_from_request(request),
}
if "end_date" in request.GET:
end_date = parse_date_or_400(request.GET["end_date"])
else:
now = datetime.datetime.utcnow()
last_day_of_last_month = now - datetime.timedelta(days=now.day)
end_date = datetime.datetime(
last_day_of_last_month.year,
last_day_of_last_month.month,
last_day_of_last_month.day,
23, 59, 59)
filter_params["completed_on__lte"] = end_date
if "start_date" in request.GET:
start_date = parse_date_or_400(request.GET["start_date"])
else:
start_date = datetime.datetime(1970, 1, 1)
filter_params["completed_on__gte"] = start_date
journies = Case.objects.filter(**filter_params).order_by("completed_on")
count = journies.count()
journies_by_month = filter_cases_by_month(journies)
earliest_journey = journies[0] if journies else None
latest_journey = journies.reverse()[0] if journies else None
response = {
"summary": {
"language": filter_params["language"],
"total": count,
"start_date": start_date.isoformat(),
"end_date": end_date.isoformat(),
"earliest_journey": earliest_journey.completed_on.isoformat() if earliest_journey else None,
"latest_journey": latest_journey.completed_on.isoformat() if latest_journey else None,
"by_month": journies_by_month,
},
"latest_example": {
"urn": latest_journey.urn,
"name": latest_journey.name,
"extra_data": {
k: v
for k, v in latest_journey.extra_data.items()
if k in [
"Forename1",
"Forename2",
"Surname",
"DOB",
]
},
}
} if count else {}
return HttpResponse(
json.dumps(response, indent=4),
content_type="application/json",
)
|
ministryofjustice/manchester_traffic_offences_pleas
|
apps/plea/views.py
|
Python
|
mit
| 8,700
|
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="language" content="en" />
<link href="./assets/8067b7df/css/bootstrap.css" rel="stylesheet">
<link href="./assets/96d031ef/style.css" rel="stylesheet">
<script src="./assets/b9575682/jquery.js"></script>
<script src="./assets/8067b7df/js/bootstrap.js"></script>
<script src="./assets/b0f55ffc/jssearch.js"></script> <title>SaveAction, lajax\translatemanager\controllers\actions\SaveAction - Yii Framework 2.0 API Documentation</title>
</head>
<body>
<div class="wrap">
<nav id="w238" class="navbar-inverse navbar-fixed-top navbar" role="navigation"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#w238-collapse"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span></button><a class="navbar-brand" href="./index.html">Yii Framework 2.0 API Documentation</a></div><div id="w238-collapse" class="collapse navbar-collapse"><ul id="w239" class="navbar-nav nav"><li><a href="./index.html">Class reference</a></li></ul><div class="navbar-form navbar-left" role="search">
<div class="form-group">
<input id="searchbox" type="text" class="form-control" placeholder="Search">
</div>
</div>
</div></nav>
<div id="search-resultbox" style="display: none;" class="modal-content">
<ul id="search-results">
</ul>
</div>
<div class="row">
<div class="col-md-3">
<div id="navigation" class="list-group"><a class="list-group-item" href="#navigation-228" data-toggle="collapse" data-parent="#navigation">lajax\translatemanager <b class="caret"></b></a><div id="navigation-228" class="submenu panel-collapse collapse"><a class="list-group-item" href="./lajax-translatemanager-component.html">Component</a>
<a class="list-group-item" href="./lajax-translatemanager-module.html">Module</a></div>
<a class="list-group-item" href="#navigation-229" data-toggle="collapse" data-parent="#navigation">lajax\translatemanager\bundles <b class="caret"></b></a><div id="navigation-229" class="submenu panel-collapse collapse"><a class="list-group-item" href="./lajax-translatemanager-bundles-frontendtranslationasset.html">FrontendTranslationAsset</a>
<a class="list-group-item" href="./lajax-translatemanager-bundles-frontendtranslationpluginasset.html">FrontendTranslationPluginAsset</a>
<a class="list-group-item" href="./lajax-translatemanager-bundles-languageasset.html">LanguageAsset</a>
<a class="list-group-item" href="./lajax-translatemanager-bundles-languageitempluginasset.html">LanguageItemPluginAsset</a>
<a class="list-group-item" href="./lajax-translatemanager-bundles-languagepluginasset.html">LanguagePluginAsset</a>
<a class="list-group-item" href="./lajax-translatemanager-bundles-translateasset.html">TranslateAsset</a>
<a class="list-group-item" href="./lajax-translatemanager-bundles-translatemanagerasset.html">TranslateManagerAsset</a>
<a class="list-group-item" href="./lajax-translatemanager-bundles-translatepluginasset.html">TranslatePluginAsset</a>
<a class="list-group-item" href="./lajax-translatemanager-bundles-translationpluginasset.html">TranslationPluginAsset</a></div>
<a class="list-group-item" href="#navigation-230" data-toggle="collapse" data-parent="#navigation">lajax\translatemanager\controllers <b class="caret"></b></a><div id="navigation-230" class="submenu panel-collapse collapse"><a class="list-group-item" href="./lajax-translatemanager-controllers-languagecontroller.html">LanguageController</a></div>
<a class="list-group-item active" href="#navigation-231" data-toggle="collapse" data-parent="#navigation">lajax\translatemanager\controllers\actions <b class="caret"></b></a><div id="navigation-231" class="submenu panel-collapse collapse in"><a class="list-group-item" href="./lajax-translatemanager-controllers-actions-changestatusaction.html">ChangeStatusAction</a>
<a class="list-group-item" href="./lajax-translatemanager-controllers-actions-dialogaction.html">DialogAction</a>
<a class="list-group-item" href="./lajax-translatemanager-controllers-actions-listaction.html">ListAction</a>
<a class="list-group-item" href="./lajax-translatemanager-controllers-actions-messageaction.html">MessageAction</a>
<a class="list-group-item" href="./lajax-translatemanager-controllers-actions-optimizeraction.html">OptimizerAction</a>
<a class="list-group-item active" href="./lajax-translatemanager-controllers-actions-saveaction.html">SaveAction</a>
<a class="list-group-item" href="./lajax-translatemanager-controllers-actions-scanaction.html">ScanAction</a>
<a class="list-group-item" href="./lajax-translatemanager-controllers-actions-translateaction.html">TranslateAction</a></div>
<a class="list-group-item" href="#navigation-232" data-toggle="collapse" data-parent="#navigation">lajax\translatemanager\helpers <b class="caret"></b></a><div id="navigation-232" class="submenu panel-collapse collapse"><a class="list-group-item" href="./lajax-translatemanager-helpers-language.html">Language</a></div>
<a class="list-group-item" href="#navigation-233" data-toggle="collapse" data-parent="#navigation">lajax\translatemanager\models <b class="caret"></b></a><div id="navigation-233" class="submenu panel-collapse collapse"><a class="list-group-item" href="./lajax-translatemanager-models-language.html">Language</a>
<a class="list-group-item" href="./lajax-translatemanager-models-languagesource.html">LanguageSource</a>
<a class="list-group-item" href="./lajax-translatemanager-models-languagetranslate.html">LanguageTranslate</a></div>
<a class="list-group-item" href="#navigation-234" data-toggle="collapse" data-parent="#navigation">lajax\translatemanager\models\searches <b class="caret"></b></a><div id="navigation-234" class="submenu panel-collapse collapse"><a class="list-group-item" href="./lajax-translatemanager-models-searches-languagesearch.html">LanguageSearch</a>
<a class="list-group-item" href="./lajax-translatemanager-models-searches-languagesourcesearch.html">LanguageSourceSearch</a></div>
<a class="list-group-item" href="#navigation-235" data-toggle="collapse" data-parent="#navigation">lajax\translatemanager\services <b class="caret"></b></a><div id="navigation-235" class="submenu panel-collapse collapse"><a class="list-group-item" href="./lajax-translatemanager-services-generator.html">Generator</a>
<a class="list-group-item" href="./lajax-translatemanager-services-optimizer.html">Optimizer</a>
<a class="list-group-item" href="./lajax-translatemanager-services-scanner.html">Scanner</a></div>
<a class="list-group-item" href="#navigation-236" data-toggle="collapse" data-parent="#navigation">lajax\translatemanager\services\scanners <b class="caret"></b></a><div id="navigation-236" class="submenu panel-collapse collapse"><a class="list-group-item" href="./lajax-translatemanager-services-scanners-scannerdatabase.html">ScannerDatabase</a>
<a class="list-group-item" href="./lajax-translatemanager-services-scanners-scannerfile.html">ScannerFile</a>
<a class="list-group-item" href="./lajax-translatemanager-services-scanners-scannerjavascriptfunction.html">ScannerJavaScriptFunction</a>
<a class="list-group-item" href="./lajax-translatemanager-services-scanners-scannerphparray.html">ScannerPhpArray</a>
<a class="list-group-item" href="./lajax-translatemanager-services-scanners-scannerphpfunction.html">ScannerPhpFunction</a></div>
<a class="list-group-item" href="#navigation-237" data-toggle="collapse" data-parent="#navigation">lajax\translatemanager\widgets <b class="caret"></b></a><div id="navigation-237" class="submenu panel-collapse collapse"><a class="list-group-item" href="./lajax-translatemanager-widgets-toggletranslate.html">ToggleTranslate</a></div></div> </div>
<div class="col-md-9 api-content" role="main">
<h1>Class lajax\translatemanager\controllers\actions\SaveAction</h1>
<div id="nav">
<a href="index.html">All Classes</a>
| <a href="#methods">Methods</a>
</div>
<table class="summaryTable docClass table table-bordered">
<colgroup>
<col class="col-name" />
<col class="col-value" />
</colgroup>
<tr><th>Inheritance</th><td><a href="lajax-translatemanager-controllers-actions-saveaction.html">lajax\translatemanager\controllers\actions\SaveAction</a> »
yii\base\Action</td></tr>
<tr><th>Available since version</th><td>1.0</td></tr>
</table>
<div id="classDescription">
<p><strong>Class for saving translations.</strong></p>
</div>
<a id="properties"></a>
<a id="methods"></a>
<div class="summary doc-method">
<h2>Public Methods</h2>
<p><a href="#" class="toggle">Hide inherited methods</a></p>
<table class="summary-table table table-striped table-bordered table-hover">
<colgroup>
<col class="col-method" />
<col class="col-description" />
<col class="col-defined" />
</colgroup>
<tr>
<th>Method</th><th>Description</th><th>Defined By</th>
</tr>
<tr id="run()">
<td><a href="lajax-translatemanager-controllers-actions-saveaction.html#run()-detail">run()</a></td>
<td>Saving translated language elements.</td>
<td><a href="lajax-translatemanager-controllers-actions-saveaction.html">lajax\translatemanager\controllers\actions\SaveAction</a></td>
</tr>
</table>
</div>
<a id="events"></a>
<a id="constants"></a>
<h2>Method Details</h2>
<div class="method-doc">
<div class="detail-header h3" id="run()-detail">
<a href="#" class="tool-link" title="go to top"><span class="glyphicon glyphicon-arrow-up"></span></a>
<a class="tool-link hash" href="lajax-translatemanager-controllers-actions-saveaction.html#run()-detail" title="direct link to this method"><span class="glyphicon icon-hash"></span></a>
run()
<span class="detail-header-tag small">
public method
</span>
</div>
<div class="doc-description">
<p><strong>Saving translated language elements.</strong></p>
</div>
<table class="detail-table table table-striped table-bordered table-hover">
<tr><td colspan="3" class="signature">\lajax\translatemanager\controllers\actions\Json <strong><a href="lajax-translatemanager-controllers-actions-saveaction.html#run()-detail">run</a></strong><span style="color: #0000BB"></span><span style="color: #007700">( )</span></td></tr>
</table>
<!-- -->
</div>
</div>
</div>
<script type="text/javascript">
/*<![CDATA[*/
$("a.toggle").on('click', function () {
var $this = $(this);
if ($this.hasClass('properties-hidden')) {
$this.text($this.text().replace(/Show/,'Hide'));
$this.parents(".summary").find(".inherited").show();
$this.removeClass('properties-hidden');
} else {
$this.text($this.text().replace(/Hide/,'Show'));
$this.parents(".summary").find(".inherited").hide();
$this.addClass('properties-hidden');
}
return false;
});
/*
$(".sourceCode a.show").toggle(function () {
$(this).text($(this).text().replace(/show/,'hide'));
$(this).parents(".sourceCode").find("div.code").show();
},function () {
$(this).text($(this).text().replace(/hide/,'show'));
$(this).parents(".sourceCode").find("div.code").hide();
});
$("a.sourceLink").click(function () {
$(this).attr('target','_blank');
});
*/
/*]]>*/
</script>
</div>
<footer class="footer">
<p class="pull-right"><small>Page generated on Sun, 08 Feb 2015 17:17:43 +0000</small></p>
Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a></footer>
<script type="text/javascript">jQuery(document).ready(function () {
var shiftWindow = function () { scrollBy(0, -50) };
if (location.hash) shiftWindow();
window.addEventListener("hashchange", shiftWindow);
var element = document.createElement("script");
element.src = "./jssearch.index.js";
document.body.appendChild(element);
var searchBox = $('#searchbox');
// search when typing in search field
searchBox.on("keyup", function(event) {
var query = $(this).val();
if (query == '' || event.which == 27) {
$('#search-resultbox').hide();
return;
} else if (event.which == 13) {
var selectedLink = $('#search-resultbox a.selected');
if (selectedLink.length != 0) {
document.location = selectedLink.attr('href');
return;
}
} else if (event.which == 38 || event.which == 40) {
$('#search-resultbox').show();
var selected = $('#search-resultbox a.selected');
if (selected.length == 0) {
$('#search-results').find('a').first().addClass('selected');
} else {
var next;
if (event.which == 40) {
next = selected.parent().next().find('a').first();
} else {
next = selected.parent().prev().find('a').first();
}
if (next.length != 0) {
var resultbox = $('#search-results');
var position = next.position();
// TODO scrolling is buggy and jumps around
// resultbox.scrollTop(Math.floor(position.top));
// console.log(position.top);
selected.removeClass('selected');
next.addClass('selected');
}
}
return;
}
$('#search-resultbox').show();
$('#search-results').html('<li><span class="no-results">No results</span></li>');
var result = jssearch.search(query);
if (result.length > 0) {
var i = 0;
var resHtml = '';
for (var key in result) {
if (i++ > 20) {
break;
}
resHtml = resHtml +
'<li><a href="' + result[key].file.u.substr(3) +'"><span class="title">' + result[key].file.t + '</span>' +
'<span class="description">' + result[key].file.d + '</span></a></li>';
}
$('#search-results').html(resHtml);
}
});
// hide the search results on ESC
$(document).on("keyup", function(event) { if (event.which == 27) { $('#search-resultbox').hide(); } });
// hide search results on click to document
$(document).bind('click', function (e) { $('#search-resultbox').hide(); });
// except the following:
searchBox.bind('click', function(e) { e.stopPropagation(); });
$('#search-resultbox').bind('click', function(e) { e.stopPropagation(); });
});</script></body>
</html>
|
schmunk42/yii2-translate-manager
|
docs/lajax-translatemanager-controllers-actions-saveaction.html
|
HTML
|
mit
| 14,821
|
<script src="<?php echo base_url(); ?>assets/admin/js/plugin/summernote/summernote.min.js"></script>
<link href="<?php echo base_url(); ?>assets/admin/css/custom-main.css" rel="stylesheet">
<?php
$this->load->view('themes/admin/breadcrumb');
?>
<!-- MAIN CONTENT -->
<div id="content">
<div class="m-b-10">
<div class="pull-left">
<h3 class="pull-left">
<strong>Edit Rate Category</strong>
</h3>
</div>
</div>
<section id="widget-grid" class="">
<div data-widget-editbutton="false" id="8521cbb7b77c1acb05ccf76f73014447" class="jarviswidget jarviswidget-sortable" role="widget">
<div role="content">
<div class="jarviswidget-editbox"></div>
<div class="widget-body ">
<div class="tabbable">
<ul class="nav nav-tabs bordered">
<li class="active">
<a data-placement="top" rel="tooltip" data-toggle="tab" href="#tab1" data-original-title="" title="Rate Category" aria-expanded="false">
Basic Information
</a>
</li>
</ul>
<form class="smart-form" id="editRateCategoryForm" method="post" data-parsley-validate="" enctype="multipart/form-data" action="<?php echo base_url('admin/settings/editRateCategory/'.$rate_category['id']); ?>">
<div class="tab-content padding-10">
<div id="tab1" class="tab-pane active">
<div class="row">
<article class="col-xs-12 col-sm-12 col-md-12 col-lg-12 sortable-grid ui-sortable">
<div class="col-lg-6 col-sm-6">
<fieldset>
<section>
<label class="label">Rate Category</label>
<label class="textarea">
<textarea class="custom-scroll" rows="5" name="category_type" id="category_type" required=""><?php echo (!empty($rate_category['category_type']))?$rate_category['category_type']:'';?></textarea>
</label>
</section>
<section>
<label class="label">Meal Plan</label>
<label class="input">
<input type="text" placeholder="Meal Plan" required="" id="meal_plan" name="meal_plan" value="<?php echo (!empty($rate_category['meal_plan']))?$rate_category['meal_plan']:'';?>">
</label>
</section>
<section>
<label class="label">Status</label>
<div class="input input-radio">
<div class="col col-3">
<label class="radio state-success">
<input type="radio" <?php echo (!empty($rate_category['status']) && $rate_category['status'] == '1')?'checked':''?> value="1" name="status" data-parsley-multiple="status" data-parsley-id="1815">
<i></i>Enable
</label><ul class="parsley-errors-list" id="parsley-id-multiple-status"></ul>
</div>
<div class="col col-3">
<label class="radio state-error">
<input type="radio" <?php echo ($rate_category['status'] !='' && $rate_category['status'] == '0')?'checked':''?> value="0" name="status" data-parsley-multiple="status" data-parsley-id="1815">
<i></i>Disable
</label>
</div>
</div>
</section>
</fieldset>
</div>
</article>
</div>
</div>
<footer>
<hr class="simple">
<button class="btn btn-success pull-right frm-submit" type="submit" id="submit_btn">
Submit
</button>
<button onclick="window.history.back();" class="btn btn-default" type="button">Back</button>
</footer>
</form>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
<!-- PAGE RELATED PLUGIN(S) -->
<script type="text/javascript">
//****** Checking All tab validation ******//
$(document).ready(function () {
var instance = $('#editRateCategoryForm').parsley();
$('.frm-submit').click(function(){
if(instance.isValid() === false){
/* display a messge to show users there is some more errors in form */
bootstrap_alert.danger('Please check all contents');
}
});
});
</script>
|
abdul-tis/tmi_hotels
|
application/views/admin/settings/editratecategory.php
|
PHP
|
mit
| 6,794
|
// <auto-generated />
using HerpDesk.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using System;
namespace HerpDesk.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20180111081222_TicketAuthorLinks")]
partial class TicketAuthorLinks
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.0-rtm-26452");
modelBuilder.Entity("HerpDesk.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("Role");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("HerpDesk.Models.Ticket", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd();
b.Property<string>("Comment");
b.Property<string>("Content");
b.Property<DateTime>("CreatedDate");
b.Property<DateTime>("DueDate");
b.Property<string>("History");
b.Property<string>("Location");
b.Property<string>("Priority");
b.Property<string>("Status");
b.Property<string>("Title");
b.HasKey("ID");
b.ToTable("Ticket");
});
modelBuilder.Entity("HerpDesk.Models.TicketAuthorLink", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd();
b.Property<string>("AuthorId");
b.Property<int>("TicketId");
b.HasKey("ID");
b.ToTable("Links");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("HerpDesk.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("HerpDesk.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("HerpDesk.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("HerpDesk.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
|
MarcinSzyba/HerpDesk
|
HerpDesk/Migrations/20180111081222_TicketAuthorLinks.Designer.cs
|
C#
|
mit
| 8,712
|
require 'spec_helper'
describe Jruby::Pcap do
let(:file) { "spec/fixtures/ransomware.pcap" }
let(:handle) { Jruby::Pcap.open(file) }
subject(:packet) { handle.first }
context "handling a packet" do
it "able to get a packet timestamp" do
expect(packet.timestamp).to eq(1431626602000)
end
end
context "when fetching the ipv4 frame" do
subject(:frame) { packet.ipv4 }
it "get the src_addr attribute" do
expect(frame.src_addr).to eq("192.168.122.84")
end
it "get the src_host attribute" do
expect(frame.src_host).to eq("192.168.122.84")
end
end
describe "handling live packets" do
let(:handle) { Jruby::Pcap.live("en0") }
let(:now) { Time.now.to_i }
xit "able to get a packet timestamp" do
expect(packet.timestamp).to be > now
end
end
end
|
purbon/jruby-pcap
|
spec/jruby-pcap/packet_spec.rb
|
Ruby
|
mit
| 840
|
# Scaling Up And Scaling Out
Scaling is the effect of increasing capacity by adding more resources. Scaling vertically (scaling up) means adding resources to a single machine. Increasing the number of available machines is called horizontal scaling (scaling out).
Traditionally, adding more hardware resources to a database server has been the preferred way of increasing database capacity. Relational databases have emerged in the late seventies, and, for two and a half decades, the database vendors took advantage of the hardware advancements following the trends in Moore's Law.
Distributed systems are much more complex to manage than centralized ones, and that is why horizontal scaling is more challenging than scaling vertically. On the other hand, for the same price of a dedicated high-performance server, one could buy multiple commodity machines whose sum of available resources (CPU, Memory, Disk Storage) is greater than of the single dedicated server. When deciding which scaling method is better suited for a given enterprise system, one must take into account both the price (hardware and licenses) and the inherent developing and operational costs.
Being built on top of many open source projects (e.g. PHP, MySQL), Facebook uses a horizontal scaling architecture to accommodate its massive amounts of traffic.
StackOverflow is the best example of a vertical scaling architecture. In one of his blog posts, Jeff Atwood explained that the price of Windows and SQL Server licenses was one of the reasons for not choosing a horizontal scaling approach.
No matter how powerful it might be, one dedicated server is still a single point of failure, and throughput drops to zero if the system is no longer available. Database replication is therefore mandatory in most enterprise systems.
### Reference
* [performance-and-scaling-in-enterprise-systems](http://highscalability.com/blog/2016/5/11/performance-and-scaling-in-enterprise-systems.html)
|
kentsay/TIL
|
performance-and-scaling/scaling-up-scaling-out.md
|
Markdown
|
mit
| 1,965
|
(function() {
var url = new URL(location.href);
/**
* This represents one oscillator of Kuramoto-Network.
* @constructor
*/
var Oscillator = function () {
/**
* References to coupled oscillators.
* @type {Array.<Oscillator>} */
this.coupled = [];
this.omega = 0;
this.nextTheta = 0;
this.lastTheta = 0;
this.step = 0;
// 1st term
// Value between 0 and 1.0 will be stored
var times = parseInt(url.searchParams.get("gaussianLargeness"), 10);
this.omega = gaussianRand(isNaN(times) ? 10 : times );
};
// Coefficient of 2nd term (K in Wikipedia)
Oscillator.coeff = 1.0;
Oscillator.prototype.addCoupledOscillator = function (oscilattor) {
this.coupled.push(oscilattor);
};
Oscillator.prototype.calculateNextTheta = function () {
// Calculates the 2nd term
if (this.coupled.length < 1) {
this.nextTheta = this.omega;
return;
}
// Here is Kuramoto Model
var sum = 0.0;
for (var i = 0; i < this.coupled.length; i++) {
sum += Math.sin(this.lastTheta - this.coupled[ i ].lastTheta);
}
this.nextTheta += this.omega - ((Oscillator.coeff / this.coupled.length) * sum);
};
Oscillator.prototype.updateTheta = function () {
this.lastTheta = this.nextTheta;
this.step++;
};
Oscillator.prototype.getPhase = function () {
return this.lastTheta;
}
/**
* This class uses d3.js
* @param {Array.<Array.<Number>>} data
* @constructor
*/
function LineGraph(data, orderParameters) {
// Specifies the parent element this graph add to.
this.container = d3.select("#debugLineGraphs");
this.width = 960;
this.height = 200;
var margin = {};
margin.top = margin.right = margin.bottom = margin.left = 30;
this.margin = margin;
this.data = data;
this.orderParameters = orderParameters;
this.x = d3.scaleLinear().range([0, this.width]);
this.color = d3.scaleOrdinal(d3.schemeCategory10);
}
LineGraph.prototype.render = function() {
var self = this;
if (!self.svg) { // render first time
self.y = d3.scaleLinear()
.range([self.height, 0]);
self.yOrderParam = d3.scaleLinear()
.range([self.height, 0])
self.yOrderParam.domain([0,1]);
self.xAxis = d3.axisBottom()
.scale(self.x);
self.yAxis = d3.axisLeft()
.scale(self.y);
self.yAxis2 = d3.axisRight()
.scale(self.yOrderParam);
self.line = d3.line()
.x(function(d, i) { return self.x(i); })
.y(function(d) { return self.y(d); });
// Really need this?
//.interpolate("basis");
self.orderParamLine = d3.line()
.x(function(d, i) { /*console.log("x)d:" + d + ",i:" + i);*/ return self.x(i); })
.y(function(d) { /*console.log("y)d:" + d);*/ return self.yOrderParam(d);});
self.svg = self.container.append("svg")
.attr("width", self.width + self.margin.left + self.margin.right)
.attr("height", self.height + self.margin.top + self.margin.bottom)
.append("g")
.attr("transform", "translate(" + self.margin.left + "," + self.margin.top + ")");
//self.x.domain(d3.extent(data, function(d) { return d.x; }));
//self.y.domain(d3.extent(data, function(d) { return d.y; }));
self.svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + self.height + ")")
.call(self.xAxis);
self.svg.append("g")
.attr("class", "y axis")
.call(self.yAxis);
self.svg.append("g")
.attr("class", "y axis2")
.attr("transform", "translate(" + self.width + ",0)")
.call(self.yAxis2);
self.lines = self.svg.append("g")
.attr("class", "lines");
self.lines
.selectAll("path.line")
.data(self.data, function(ts, i) {return i;})
.enter()
.append("path")
.attr("class", "line")
.attr("stroke", "red")
.attr("fill", "none")
.attr("d", self.line);
self.orderParameter = self.svg.append("g")
.attr("class", "orderParameterLine");
self.orderParameter
.append("path")
.data(self.orderParameters)
.attr("fill", "none")
.attr("stroke", "silver")
.attr("d", self.orderParamLine);
} else {
// Resets the target domain (min and max values of each axis)
self.x.domain([0, d3.max(self.data, function(d) {return d.length;})]);
self.y.domain(d3.extent(d3.merge(self.data)));
self.svg.select("g.y")
.transition()
.duration(100)
.call(self.yAxis);
self.svg.select("g.x")
.transition()
.duration(100)
.call(self.xAxis);
self.lines
.selectAll("path.line")
.data(self.data)
.attr("d", self.line).style("stroke", function(d, i) {return self.color(i);});
self.orderParameter
.select("path")
.attr("stroke", "black")
.attr("d", self.orderParamLine(self.orderParameters));
}
};
/**
* Generate gaussian-distributed numbers with the Central number theorem.
* @param {Number} times Integer representing how large numbers to add to simulate gaussian distribution.
*/
function gaussianRand (times) {
var rand = 0;
for (var i = 1; i <= times; i++) {
rand += Math.random();
}
return rand / times;
}
/**
*
* @constructor
*/
function OrderParameterCell() {
this.td = document.createElement("td");
this.svg = d3.select(this.td).append("svg");
this.text = document.createTextNode("");
this.td.appendChild(this.text);
}
window.App = !(typeof window['App'] !== 'undefined') ? (function () {
var oscillators = parseInt(url.searchParams.get("oscillators") ,10);
var NUMBERS_OF_OSCILLATOR = isNaN(oscillators) ? 10 : oscillators;
var STEPS_TO_REMEMBER = 50;
var intervalTimer = null;
return {
init: function () {
var oscillators = [];
/**
* Stores old values of the oscillators.
* @type {Array.<Array.<Number>>}
* */
var oscillatorValues = [
// Elements such below come here
// - Time series values (an array) of oscillator #1,
// - Time series values (an array) of oscillator #2,..
];
var orderParameters = [];
var orderParameterTable = document.getElementById("orderParameterTable");
/* @type {Array.<Array.{Element(td)}>} */
var orderParameterCells = [];
// Set K
var k = parseFloat(document.getElementById("k").value);
if (Number.isNaN(k)) {
alert("K is NaN");
return;
} else {
Oscillator.coeff = k;
}
var omegaDist = {0.0: 0, 0.1:0, 0.2:0, 0.3:0, 0.4: 0,
0.5: 0, 0.6:0, 0.7:0, 0.8:0, 0.9: 0};
for (var i = 0; i < NUMBERS_OF_OSCILLATOR; i++) {
// Constructs an oscillator.
var oscillator = new Oscillator()
oscillators.push(oscillator);
// Constructs an oscillator value holder.
oscillatorValues.push([]);
// Appends a row of the order parameter table
var tr = document.createElement("tr");
var cells = [];
for (var k = 0; k < NUMBERS_OF_OSCILLATOR; k++) {
if (k === i) {
var td = document.createElement("td");
td.appendChild(document.createTextNode("Osc #" + i));
td.setAttribute("class", "diagonal");
tr.appendChild(td);
cells.push(td);
} else {
var cell = new OrderParameterCell();
tr.appendChild(cell.td);
cells.push(cell);
}
}
orderParameterTable.appendChild(tr);
orderParameterCells.push(cells);
omegaDist[oscillator.omega.toFixed(1)] += 1;
}
console.log("Omega distribution:");
for (var key in omegaDist) {
console.log("[" + key + "]" + omegaDist[key]);
}
var lineGraph = new LineGraph(oscillatorValues, orderParameters);
// Sets coupled oscillators
for (var target = 0; target < oscillators.length; target++) {
//console.log("connecting #" + target + " to:");
for (i = 0; i < oscillators.length; i++) {
if (i === target) {
// Skips if the setting target and the oscillator to be set are same.
continue;
}
oscillators[target].addCoupledOscillator(oscillators[i]);
//console.log("\t#" + i);
}
}
// Sets up interval oscillator updates.
var x = 0;
intervalTimer = window.setInterval(function() {
for (var i = 0; i < oscillators.length; i++) {
oscillators[i].calculateNextTheta();
}
// Its absolute value will be taken when we calculate the order parameter.
var sum_of_euler_real = 0.0;
var sum_of_euler_imaginary = 0.0;
for (var i = 0; i < oscillators.length; i++) {
oscillators[i].updateTheta();
// Saves the value onto oscillatorValues.
if (oscillatorValues[i].length >= STEPS_TO_REMEMBER) {
// Removes the oldest value if the array exceeds the limit.
oscillatorValues[i].shift();
}
oscillatorValues[i].push(Math.sin(oscillators[i].lastTheta % (Math.PI * 2)));
// Updates the order parameter table.
for (var k = i + 1; k < oscillators.length; k++) {
// Calculates an order parameter just for the 2 oscillators.
var real = Math.cos(oscillators[i].getPhase()) + Math.cos(oscillators[k].getPhase());
var imaginary = Math.sin(oscillators[i].getPhase()) + Math.sin(oscillators[k].getPhase());
var partialOrderParameter = Math.sqrt(Math.pow(real, 2) + Math.pow(imaginary, 2)) / 2;
// Updates the target cell.
if (orderParameterCells[i][k] instanceof OrderParameterCell) {
orderParameterCells[i][k].text.textContent = partialOrderParameter.toFixed(3);
// Updates: #FFFFFF
// ^^^^ here, like if 0.0 -> FFFFFF, 1.0 -> FF0000
var blueOrGreen = Math.round((1 - partialOrderParameter) * 255).toString(16);
// Add leading zeros
blueOrGreen = ("00" + blueOrGreen).substr(-2);
orderParameterCells[i][k].td.style.backgroundColor = "#FF" +
blueOrGreen + blueOrGreen;
}
}
// Calculates order parameter components for the whole system (all oscillators).
sum_of_euler_real += Math.cos(oscillators[i].getPhase());
sum_of_euler_imaginary += Math.sin(oscillators[i].getPhase());
}
if (orderParameters.length >= STEPS_TO_REMEMBER) {
// Removes the oldest value if the array exceeds the limit.
orderParameters.shift();
}
// Calculates the order parameter
var absoluteSum = Math.sqrt(Math.pow(sum_of_euler_real, 2) + Math.pow(sum_of_euler_imaginary, 2));
//console.log("m=" + (absoluteSum / oscillators.length));
orderParameters.push((absoluteSum / oscillators.length));
lineGraph.render();
x++;
}, 300);
},
stop: function() {
if (intervalTimer !== null)
{
clearInterval(intervalTimer);
}
}
};
})() : window.app;
})();
|
arumtaunsaram/Kuramoto-Model
|
app.js
|
JavaScript
|
mit
| 13,845
|
# Step Through Debugging
The area below is supposed to be a list of interesting facts about cats! If you look at the HTML you'll see the following:
```html
<ul id="catfacts"></ul>
```
And a file in this repo `/public/exercises/js/Debugging.js` is hitting an API and supposed to populate that list! Can you figure out what's going wrong?
Hint: Checking the console is a great place to start. Once you've identified the area, use the debugger in the Sources tab to get a lay of the land.
## Here is a list of FACTS about CATS
<ul id="catfacts"></ul>
## Finished?
All finished? Head on back to the [Lesson](/lesson/Debugging)
|
jkup/mastering-chrome-devtools
|
markdown/exercises/Debugging.md
|
Markdown
|
mit
| 631
|
# mip-hs-discuss
mip-hs-discuss 组件说明
此组件用于详情页面的评论列表的渲染并有回复功能,回复功能需要与mip-hs-replay组件一起使用效果更好,评论列表里面的点赞交互处理;
通过点击类disnum渲染插入评论列表数据;
标题|内容
----|----
类型|通用
支持布局|responsive,fixed-height,fill,container,fixed
所需脚本|https://c.mipcdn.com/static/v1/mip-hs-discuss/mip-hs-discuss.js
## 示例
### 基本用法
```html
<mip-hs-discuss>
<mip-hs-discuss data-url='http://hsanswer.xxx.cn/comment/more' user-id='1024'><i class="disnum">收起评论</i><i class="slidup">收起评论</i></mip-hs-discuss>
</mip-hs-discuss>
```
## 属性
data-url:是进行加载列表的时候所要调取的接口数据;
user-id:是进行加载列表的时候所要传过去的当前用户id;
### {属性名}
说明:{说明}
必选项:{是|否}
类型:{类型}
取值范围:{取值范围}
单位:{单位}
默认值:{默认值}
## 注意事项
|
mipengine/mip-extensions-platform
|
mip-hs-discuss/README.md
|
Markdown
|
mit
| 1,024
|
<?php
/*
* This file is part of the idlErrorManagementPlugin
* (c) Idael Software <info AT idael.ch>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* PluginApplicationError, reprents error object that are going to be record
*
* @package idlErrorManagementPlugin
* @subpackage model
* @author David Jeanmonod <david AT idael.ch>
*/
abstract class PluginApplicationError extends BaseApplicationError {
/**
* Update properties with an exception object
* @param Exception $e
*/
public function updateWithException($e) {
$this->fromArray(array(
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString(),
'type' => get_class($e),
'code' => $e->getCode()
));
}
/**
* Update properties with the symfony context
* @param sfContext An instance of sfContext
*/
public function updateWithContext($context = null) {
if ($context==null && !sfContext::hasInstance()){
return;
}
$c = is_null($context) ? sfContext::getInstance() : $context;
$this->fromArray(array(
'module' => $c->getModuleName(),
'action' => $c->getActionName()
));
if (is_object($r = $c->getRequest())){
$this->fromArray(array(
'uri' => $r->getUri(),
'user_agent' => $r->getHttpHeader('User-Agent')
));
}
}
/**
* Update properties with symfony user
* @param sfUser An instance of sfUser
*/
public function updateWithUser($user = null) {
$username = '-';
try {
$user = is_null($user) ? sfContext::getInstance()->getUser() : $user;
foreach (array('getUsername', 'getName', '__toString') as $method){
if (method_exists($user, $method)){
$username = (string) $user->$method();
break;
}
}
}
catch (Exception $e){}
$this->setUser($username);
}
/**
* Remove the base dir from the file name
*/
public function getShortFilePath(){
if ( strpos($this->getFile(),sfConfig::get('sf_root_dir')) !== false ){
return substr($this->getFile(),strlen(sfConfig::get('sf_root_dir')));
}
return $this->getFile();
}
/**
* Return a formated description of the error
*/
public function getFormattedDescription(){
$desc = "";
foreach ( $this->toArray() as $name => $value){
if (isset($value) && strlen($value)>0) {
$desc .= str_pad($name."\n", strlen($name)*2 , "-") ."\n$value\n\n";
}
}
return $desc;
}
}
|
Symfony-Plugins/idlErrorManagementPlugin
|
lib/model/doctrine/PluginApplicationError.class.php
|
PHP
|
mit
| 2,731
|
angular.module('inviteFactory', ['firebase'])
.factory('invite', ['$firebaseObject', '$http' , function ($firebaseObject, $http) {
var inviteFactory = {};
// mandrill API key ** free version API key only for production **
// in real use case, should store this securely
var mandrillKey = 'ul35c_Y39BxIZUIUa_HIog';
inviteFactory.sendEmailInvitation = function (sender, orgName, recipient, recipientEmail) {
// in production: use localhost for testing
// change link when deployed
var link = 'http://'+window.host+':3000/#/'+orgName+'/signup';
var orgId;
var orgRef = new Firebase('https://bizgramer.firebaseio.com/'+orgName);
var orgObj = $firebaseObject(orgRef);
orgObj.$loaded()
.then(function() {
// query firebase db to get the orgId for the logged in user's org
orgId = orgObj.orgKey;
var params = {
"key": mandrillKey,
"message": {
"from_email": sender+"."+orgName+"@Hiver.com",
"to":[{"email":recipientEmail}],
"subject": "Hey "+recipient+" go signup at Hive!",
"html":
"<h1>"+sender+" invited you to sign up for "+orgName+" at Hive</h1><h2>Your OrgID is "+orgId+"</h2><h3><a href='"+link+"''>"+link+"</a></h3>",
"autotext": true,
"track_opens": true,
"track_clicks": true
}
}; // end params
// send ajax request to Mandrill api for email invite
$http.post('https://mandrillapp.com/api/1.0/messages/send.json', params)
.success(function() {
console.log('email invite sent successfully');
})
.error(function() {
console.log('error sending email invite');
});
})
.catch(function (error) {
console.log('error', error);
});
}; //end .sendEmailInvitation
return inviteFactory;
}]);
|
onphenomenon/bizGram
|
client/app/Invites/inviteFactory.js
|
JavaScript
|
mit
| 1,938
|
=begin
#The Plaid API
#The Plaid REST API. Please see https://plaid.com/docs/api for more details.
The version of the OpenAPI document: 2020-09-14_1.79.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.0
=end
require 'date'
require 'time'
module Plaid
class CreditAccountSubtype
CREDIT_CARD = "credit card".freeze
PAYPAL = "paypal".freeze
ALL = "all".freeze
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def self.build_from_hash(value)
new.build_from_hash(value)
end
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def build_from_hash(value)
# We do not validate that the value is one of the enums set in the OpenAPI
# file because we want to be able to add to our list of enums without
# breaking this client library.
value
end
end
end
|
plaid/plaid-ruby
|
lib/plaid/models/credit_account_subtype.rb
|
Ruby
|
mit
| 1,012
|
/**
* Created by DOCer on 2017/7/11.
*/
import {connect} from 'app';
import UI from './UI/';
export default connect(
({test}) => (test),
{
onStart({dispatch, getState}){
dispatch({
type: "test/showTableLoading"
});
// ajax request after empty completing
setTimeout(() => {
dispatch({
type: "test/hideTableLoading",
});
dispatch({
type: "test/setSelectedRowKeys",
payload: [2]
});
}, 800);
},
onChange({dispatch, getState}, selectedRowKeys){
dispatch({
type: "test/setSelectedRowKeys",
payload: selectedRowKeys
});
},
onPanelChange({dispatch, getState}, {mode, data}){
console.log(data, mode);
},
onCascaderChange({dispatch, getState}, value){
console.log(value);
},
onCollapseChange({dispatch, getState}, key){
console.log(key);
},
onDecline ({dispatch, getState}){
let percent = getState().test.progressData.percent - 10;
if (percent < 0) {
percent = 0;
}
dispatch({
type: "test/decline",
payload: percent
});
},
onIncrease ({dispatch, getState}){
let percent = getState().test.progressData.percent + 10;
if (percent > 100) {
percent = 100;
}
dispatch({
type: "test/increase",
payload: percent
});
},
}
)(UI);
|
homkai/deef
|
examples/ant-design-demo/src/Root/modules/Test/index.js
|
JavaScript
|
mit
| 1,745
|
function AddressBook () {
this.contacts=[];
this.initialComplete = false;
AddressBook.prototype.addContact= function(newContact) {
this.contacts.push(newContact);
};
AddressBook.prototype.getContact = function(index) {
return this.contacts[index];
};
AddressBook.prototype.deleteContact = function(index) {
this.contacts.splice(index, 1);
};
AddressBook.prototype.getInitialContacts = function(cb) {
var self = this;
setTimeout(function() {
self.initialComplete = true;
if (cb) {
return cb();
}
}, 3);
};
}
|
Andrew-He/jasmine-practice
|
src/AddressBook.js
|
JavaScript
|
mit
| 596
|
import ListaDeNotas from "./ListaDeNotas"
export default ListaDeNotas
|
AlbertoAlfredo/exercicios-cursos
|
alura/react/ceep/src/components/ListaDeNotas/index.js
|
JavaScript
|
mit
| 69
|
package com.github.wreulicke.spring;
import org.springframework.boot.autoconfigure.web.WebMvcRegistrationsAdapter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SampleInterceptor());
};
@Configuration
public static class Config extends WebMvcRegistrationsAdapter {
}
}
|
Wreulicke/spring-sandbox
|
failsafe/src/main/java/com/github/wreulicke/spring/WebMvcConfiguration.java
|
Java
|
mit
| 629
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FDA.Attributes
{
/// <summary>
/// Indicates an Assembly contains datapoint models
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
public class ModelAttribute : Attribute
{
}
}
|
DefectiveCube/FlightDataAnalyzer
|
src/AnalysisLib/Attributes/ModelAttribute.cs
|
C#
|
mit
| 346
|
.screenName {
color: #999;
}
|
shibe97/worc
|
app/components/Atoms/ScreenName/screenName.css
|
CSS
|
mit
| 31
|
package elkm1androidexample.elk.org.elkm1androidexample;
import elkm1api.CharVector;
import elkm1api.M1Connection;
import java.io.IOException;
import java.net.Socket;
/**
* Created by feilen on 8/10/16.
*/
public class ConnectionWrapper extends M1Connection {
protected Socket tcp;
//AutoResetEvent evt = new AutoResetEvent(true);
public boolean Connect(String location, int port)
{
try {
tcp = new Socket(location, port);
return tcp.isConnected();
} catch (IOException ioe) {
return false;
}
}
public CharVector Recieve()
{
byte[] recv = new byte[256];
int recieved = 0;
try {
recieved = tcp.getInputStream().read(recv, 0, recv.length);
} catch (IOException ioe) {
}
//evt.Set();
CharVector cv = new CharVector(recieved);
for (int i = 0; i < recieved; i++)
{
cv.add((char)recv[i]);
}
return cv;
}
public void Send(CharVector data)
{
byte[] send = new byte[(int)data.size()];
for (int i = 0; i < data.size(); i++)
send[i] = (byte)data.get(i);
//evt.WaitOne(300);
// TODO: Rate limiting
try {
tcp.getOutputStream().write(send, 0, (int)data.size());
} catch (IOException ioe) {
}
//Console.WriteLine(Encoding.ASCII.GetString(send, 0, data.Count));
}
public void Disconnect()
{
// evt.set();
try {
tcp.close();
} catch (IOException ioe) {
//
}
}
}
|
ElkProducts/ElkM1API
|
ElkM1AndroidExample/app/src/main/java/elkm1androidexample/elk/org/elkm1androidexample/ConnectionWrapper.java
|
Java
|
mit
| 1,683
|
#!/bin/bash
# Script: install_eclipse_luna.sh
echo === Install & remove Eclipse CDT - this leaves the .desktop file
sudo apt-get update
sudo apt-get install -y eclipse-cdt
sudo cp /usr/share/applications/eclipse.desktop /usr/share/applications/eclipse.desktop.bak
sudo apt-get remove -y eclipse-cdt
echo
echo === Download Eclipse CDT Luna
wget http://www.gtlib.gatech.edu/pub/eclipse/technology/epp/downloads/release/luna/R/eclipse-cpp-luna-R-linux-gtk.tar.gz
tar -vxzf eclipse-cpp-luna-R-linux-gtk.tar.gz
rm -f eclipse-cpp-luna-R-linux-gtk.tar.gz
echo
echo === Move eclipse-cdt to /usr/share/eclipse/
sudo mkdir /usr/share/eclipse
sudo cp -vr ./eclipse/* /usr/share/eclipse/
sudo rm -rf ./eclipse
echo
echo === Create link to /usr/share/freemind/ in /usr/bin
pushd .
sudo rm /usr/bin/eclipse
cd /usr/bin && sudo ln -s /usr/share/eclipse/eclipse /usr/bin/eclipse
sudo apt-get install -y desktop-file-utils
cd /usr/share/applications && sudo mv eclipse.desktop.bak eclipse.desktop && sudo desktop-file-install eclipse.desktop
popd
|
fsziegler/Configurations
|
install_eclipse_luna.sh
|
Shell
|
mit
| 1,031
|
'use strict';
const {BrowserWindow, app} = require('electron');
const test = require('tape-async');
const delay = require('delay');
const {
appReady,
focusWindow,
minimizeWindow,
restoreWindow,
windowVisible
} = require('.');
let win;
test('exports an appReady function', async t => {
t.is(typeof appReady, 'function');
});
test('appReady return a promise that resolve when electron app is ready', async t => {
await appReady();
// We could create a window, because the app is ready
win = new BrowserWindow({show: false});
await delay(400);
t.is(typeof win, 'object');
});
test('focusWindow return a promise that resolve when window is focused', async t => {
const browser = new BrowserWindow();
// browser.loadURL(`file://${__dirname}/index.html`);
await windowVisible(browser);
t.true(await focusWindow(browser));
t.true(browser.isFocused());
browser.close();
});
test('minimizeWindow return a promise that resolve when window is minimized', async t => {
const browser = new BrowserWindow();
await windowVisible(browser);
t.false(browser.isMinimized());
t.true(await minimizeWindow(browser));
t.true(browser.isMinimized());
browser.close();
});
test('restoreWindow return a promise that resolve when window is restored', async t => {
const browser = new BrowserWindow();
await windowVisible(browser);
t.true(await minimizeWindow(browser));
t.true(browser.isMinimized());
t.true(await restoreWindow(browser));
await delay(100);
t.false(browser.isMinimized());
browser.close();
});
test('app quit', t => {
app.on('window-all-closed', () => app.quit());
t.end();
win.close();
});
|
parro-it/p-electron
|
test.js
|
JavaScript
|
mit
| 1,621
|
package unnoticed
import (
"errors"
"fmt"
"log"
"os"
"os/user"
"path"
"runtime"
)
var (
printLogger *log.Logger = log.New(os.Stdout, log.Prefix(), log.Flags())
fileLogger *log.Logger = nil
fileLogging bool = false
)
// OsuDir finds the root osu! directory where osu!.db and scores.db can be found.
func OsuDir() (string, error) {
if dbRootEnv := os.Getenv("OSU_ROOT"); len(dbRootEnv) > 0 {
if _, err := os.Stat(path.Join(dbRootEnv, "osu!.db")); err != nil {
return "", errors.New(fmt.Sprintf("osu!.db was not found at %s", dbRootEnv))
}
if _, err := os.Stat(path.Join(dbRootEnv, "scores.db")); err != nil {
return "", errors.New(fmt.Sprintf("scores.db was not found at %s", dbRootEnv))
}
return dbRootEnv, nil
}
dbRoot := []string{}
switch runtime.GOOS {
case "windows":
dbRoot = append(dbRoot, "C:\\\\Program Files (x86)\\osu!\\", "C:\\\\osu!\\")
if usr, err := user.Current(); err == nil {
dbRoot = append(dbRoot, path.Join(usr.HomeDir, "AppData", "Local", "osu!"))
}
case "darwin":
dbRoot = append(
dbRoot,
"/Applications/osu!.app/Contents/Resources/drive_c/Program Files/osu!/",
)
default:
dbRoot = append(dbRoot, "./") // TODO: Where will this go?
}
for _, dir := range dbRoot {
if _, err := os.Stat(path.Join(dir, "osu!.db")); err != nil {
continue
}
if _, err := os.Stat(path.Join(dir, "scores.db")); err != nil {
continue
}
LogMsgf("found .db files at %s", dir)
return dir, nil
}
return "", errors.New(".db files were not found")
}
// LogSetup tries sto set up file logging with with fn.
func LogSetup(fn string) (*os.File, error) {
f, err := os.OpenFile(fn, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
return nil, err
}
fileLogger = log.New(f, log.Prefix(), log.Flags())
fileLogging = true
return f, nil
}
// LogMsg logs a message.
func LogMsg(msg interface{}) {
printLogger.Println(msg)
if fileLogging {
fileLogger.Println(msg)
}
}
// LogMsgf logs a formatted message.
func LogMsgf(format string, a ...interface{}) {
LogMsg(fmt.Sprintf(format, a...))
}
|
christopher-dG/unnoticed
|
client/utils.go
|
GO
|
mit
| 2,084
|
# HTTPD Web Server Check
Check the health of the HTTPD service.
Note, we've seen case where the status command print "httpd dead but subsys
locked".
module.exports = header: 'HTTPD Check', handler: (options) ->
## Runing Sevrice
Ensure the "ntpd" service is up and running.
@service.assert
header: 'Service'
name: 'httpd'
installed: true
started: true
## TCP Connection
Ensure the port is listening.
@connection.assert
header: 'TCP'
host: options.wait_tcp.fqdn
port: options.wait_tcp.port
|
adaltas/node-masson
|
commons/httpd/check.coffee.md
|
Markdown
|
mit
| 571
|
class DatabaseRouter(object):
'''
These functions are called when Django accesses the database.
Returns the name of the database to use depending on the app and model.
Returning None means use default.
'''
def db_for_read(self, model, **hints):
return self.__db_for_read_and_write(model, **hints)
def db_for_write(self, model, **hints):
return self.__db_for_read_and_write(model, **hints)
def allow_relation(self, obj1, obj2, **hints):
return None
def allow_syncdb(self, db, model):
'''
Makes sure the correct databases are used when "python manage.py syncdb" is called.
Returning True means "model" should be synchronised with "db".
'''
allow = False
if db == 'default':
allow = model._meta.app_label != 'OGRgeoConverter'
allow = allow and model._meta.app_label != 'sessions'
elif db == 'sessions_db':
allow = model._meta.app_label == 'sessions'
elif db == 'ogrgeoconverter_db':
allow = model._meta.db_table != 'ogrgeoconverter_log_entries'
allow = allow and model._meta.db_table != 'ogrgeoconverter_ogr_log_entries'
allow = allow and model._meta.db_table != 'ogrgeoconverter_conversion_jobs'
allow = allow and model._meta.db_table != 'ogrgeoconverter_conversion_job_folders'
allow = allow and model._meta.db_table != 'ogrgeoconverter_conversion_job_file_matches'
allow = allow and model._meta.db_table != 'ogrgeoconverter_conversion_job_files'
allow = allow and model._meta.db_table != 'ogrgeoconverter_conversion_job_file_id_tracking'
allow = allow and model._meta.db_table != 'ogrgeoconverter_conversion_job_urls'
allow = allow and model._meta.db_table != 'ogrgeoconverter_conversion_job_shell_parameters'
allow = allow and model._meta.db_table != 'ogrgeoconverter_conversion_job_download_items'
allow = allow and model._meta.db_table != 'ogrgeoconverter_conversion_job_identification'
allow = allow and model._meta.app_label == 'OGRgeoConverter'
elif db == 'ogrgeoconverter_conversion_jobs_db':
allow = model._meta.db_table == 'ogrgeoconverter_conversion_jobs'
allow = allow or model._meta.db_table == 'ogrgeoconverter_conversion_job_folders'
allow = allow or model._meta.db_table == 'ogrgeoconverter_conversion_job_file_matches'
allow = allow or model._meta.db_table == 'ogrgeoconverter_conversion_job_files'
allow = allow or model._meta.db_table == 'ogrgeoconverter_conversion_job_file_id_tracking'
allow = allow or model._meta.db_table == 'ogrgeoconverter_conversion_job_urls'
allow = allow or model._meta.db_table == 'ogrgeoconverter_conversion_job_shell_parameters'
allow = allow or model._meta.db_table == 'ogrgeoconverter_conversion_job_download_items'
allow = allow or model._meta.db_table == 'ogrgeoconverter_conversion_job_identification'
allow = allow and model._meta.app_label == 'OGRgeoConverter'
elif db == 'ogrgeoconverter_log_db':
allow = model._meta.db_table == 'ogrgeoconverter_log_entries'
allow = allow or model._meta.db_table == 'ogrgeoconverter_ogr_log_entries'
allow = allow and model._meta.app_label == 'OGRgeoConverter'
else:
allow = None
return allow
def __db_for_read_and_write(self, model, **hints):
if model._meta.app_label == 'sessions':
return 'sessions_db'
elif model._meta.app_label == 'OGRgeoConverter':
if model._meta.db_table == 'ogrgeoconverter_log_entries' \
or model._meta.db_table == 'ogrgeoconverter_ogr_log_entries':
return 'ogrgeoconverter_log_db'
elif model._meta.db_table == 'ogrgeoconverter_conversion_jobs' \
or model._meta.db_table == 'ogrgeoconverter_conversion_job_folders' \
or model._meta.db_table == 'ogrgeoconverter_conversion_job_file_matches' \
or model._meta.db_table == 'ogrgeoconverter_conversion_job_files' \
or model._meta.db_table == 'ogrgeoconverter_conversion_job_file_id_tracking' \
or model._meta.db_table == 'ogrgeoconverter_conversion_job_urls' \
or model._meta.db_table == 'ogrgeoconverter_conversion_job_shell_parameters' \
or model._meta.db_table == 'ogrgeoconverter_conversion_job_download_items' \
or model._meta.db_table == 'ogrgeoconverter_conversion_job_identification':
return 'ogrgeoconverter_conversion_jobs_db'
else:
return 'ogrgeoconverter_db'
return None
|
geometalab/geoconverter
|
GeoConverter/database.py
|
Python
|
mit
| 4,858
|
(function() {
var modules = window.modules || [];
var navigation_graphCache = null;
var navigation_graphFunc = function() {
return (function() {
var NavigationGraph, NavigationNode, Navigator;
Navigator = require('gator/navigator');
NavigationNode = require('gator/navigation_node');
NavigationGraph = (function() {
var _setFrom;
function NavigationGraph(navigator) {
this.navigator = navigator;
this.nodes = [];
this.currentFrom = 'initial';
this.navigator.transitionFinished.add(_setFrom.call(this));
}
NavigationGraph.create = function() {
return new this(new Navigator());
};
NavigationGraph.prototype.registerTransition = function(from, to) {
if (!this.hasTransition(from, to)) {
return this.nodes.push(new NavigationNode(from, to));
}
};
NavigationGraph.prototype.hasTransition = function(from, to) {
return this.getTransition(from, to) != null;
};
NavigationGraph.prototype.getTransition = function(from, to) {
var node;
return ((function() {
var _i, _len, _ref, _results;
_ref = this.nodes;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
if (node.matches(from, to)) {
_results.push(node);
}
}
return _results;
}).call(this))[0] || null;
};
NavigationGraph.prototype.registerAction = function(action, from, to) {
var node, _i, _len, _ref, _results;
if (from == null) {
from = null;
}
if (to == null) {
to = null;
}
_ref = this.nodes;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
if (node.matches(from, to)) {
_results.push(node.registerAction(action));
}
}
return _results;
};
NavigationGraph.prototype.registerActionAt = function(position, action, from, to) {
var node, _i, _len, _ref, _results;
if (from == null) {
from = null;
}
if (to == null) {
to = null;
}
_ref = this.nodes;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
if (node.matches(from, to)) {
_results.push(node.registerActionAt(position, action));
}
}
return _results;
};
NavigationGraph.prototype.canTransitionTo = function(to) {
return this.hasTransition(this.currentFrom, to);
};
NavigationGraph.prototype.transitionTo = function(to, context, failedAction) {
if (context == null) {
context = null;
}
if (failedAction == null) {
failedAction = null;
}
if (this.canTransitionTo(to)) {
return this.navigator.perform(this.getTransition(this.currentFrom, to), context, failedAction);
} else {
return typeof failedAction === "function" ? failedAction() : void 0;
}
};
_setFrom = function() {
var _this = this;
return function(to) {
return _this.currentFrom = to;
};
};
return NavigationGraph;
})();
return NavigationGraph;
}).call(this);
};
modules.gator__navigation_graph = function() {
if (navigation_graphCache === null) {
navigation_graphCache = navigation_graphFunc();
}
return navigation_graphCache;
};
window.modules = modules;
})();
(function() {
var modules = window.modules || [];
var navigation_nodeCache = null;
var navigation_nodeFunc = function() {
return (function() {
var NavigationNode;
NavigationNode = (function() {
var _getIndexFrom;
function NavigationNode(from, to) {
this.from = from;
this.to = to;
this.actions = [];
}
NavigationNode.prototype.registerAction = function(action) {
return this.actions.push(action);
};
NavigationNode.prototype.registerActionAt = function(position, action) {
return this.actions.splice(_getIndexFrom.call(this, position), 0, action);
};
NavigationNode.prototype.matches = function(from, to) {
return ((from == null) || this.from === from) && ((to == null) || this.to === to);
};
_getIndexFrom = function(position) {
if (typeof position === 'number') {
if (position < 0) {
return 0;
}
if (position <= this.actions.length) {
return position;
}
return this.actions.length;
} else {
if (position === "first") {
return 0;
}
if (position === "last") {
return this.actions.length;
}
}
};
return NavigationNode;
})();
return NavigationNode;
}).call(this);
};
modules.gator__navigation_node = function() {
if (navigation_nodeCache === null) {
navigation_nodeCache = navigation_nodeFunc();
}
return navigation_nodeCache;
};
window.modules = modules;
})();
(function() {
var modules = window.modules || [];
var navigatorCache = null;
var navigatorFunc = function() {
return (function() {
var Navigator, Signal,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Signal = require('cronus/signal');
Navigator = (function() {
var _run;
function Navigator() {
this.halt = __bind(this.halt, this);
this["continue"] = __bind(this["continue"], this);
this.hold = __bind(this.hold, this);
var _this = this;
this.inTransition = false;
this.shouldHold = false;
this.failedAction = null;
this.transitionFinished = new Signal();
this.transitionFinished.add(function() {
return _this.inTransition = false;
});
}
Navigator.prototype.perform = function(node, context, failedAction) {
var action;
if (node == null) {
node = null;
}
if (context == null) {
context = null;
}
if (failedAction == null) {
failedAction = null;
}
if (this.inTransition) {
throw new Error("The previous transition ('" + this.node.from + "' to '" + this.node.to + "') is not closed.");
}
this.node = node;
this.context = context;
this.failedAction = failedAction;
this.pendingActions = (function() {
var _i, _len, _ref, _results;
_ref = this.node.actions;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
action = _ref[_i];
_results.push(action);
}
return _results;
}).call(this);
return _run.call(this, this.pendingActions);
};
Navigator.prototype.hold = function() {
if (this.inTransition) {
return this.shouldHold = true;
}
};
Navigator.prototype["continue"] = function() {
if (this.inTransition) {
this.shouldHold = false;
return _run.call(this, this.pendingActions);
}
};
Navigator.prototype.halt = function() {
if (this.inTransition) {
if (this.shouldHold) {
this.shouldHold = false;
this.inTransition = false;
return typeof this.failedAction === "function" ? this.failedAction() : void 0;
} else {
throw new Error("Halt");
}
}
};
_run = function(actions) {
var action, e;
this.inTransition = true;
try {
this.allActionsRun = true;
while (this.pendingActions.length) {
this.allActionsRun = false;
action = this.pendingActions.shift();
action(this, this.context);
if (this.shouldHold) {
break;
}
if (!this.pendingActions.length) {
this.allActionsRun = true;
}
}
if (this.allActionsRun) {
return this.transitionFinished.dispatch(this.node.to);
}
} catch (_error) {
e = _error;
if (e.message === "Halt") {
return typeof this.failedAction === "function" ? this.failedAction() : void 0;
} else {
throw e;
}
}
};
return Navigator;
})();
return Navigator;
}).call(this);
};
modules.gator__navigator = function() {
if (navigatorCache === null) {
navigatorCache = navigatorFunc();
}
return navigatorCache;
};
window.modules = modules;
})();
(function() {
var modules = window.modules || [];
window.require = function(path) {
var transformedPath = path.replace(/\//g, '__');
if (transformedPath.indexOf('__') === -1) {
transformedPath = '__' + transformedPath;
}
var factory = modules[transformedPath];
if (factory === null) {
return null;
} else {
return modules[transformedPath]();
}
};
})();
(function() {
var modules = window.modules || [];
var multi_signal_relayCache = null;
var multi_signal_relayFunc = function() {
return (function() {
var MultiSignalRelay, Signal,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Signal = require("cronus/signal");
MultiSignalRelay = (function(_super) {
__extends(MultiSignalRelay, _super);
function MultiSignalRelay(signals) {
var signal, _i, _len;
MultiSignalRelay.__super__.constructor.call(this);
for (_i = 0, _len = signals.length; _i < _len; _i++) {
signal = signals[_i];
signal.add(this.dispatch);
}
}
MultiSignalRelay.prototype.applyListeners = function(rest) {
var listener, _i, _len, _ref, _results;
_ref = this.listeners;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
listener = _ref[_i];
_results.push(listener.apply(listener, rest));
}
return _results;
};
return MultiSignalRelay;
})(Signal);
return MultiSignalRelay;
}).call(this);
};
modules.cronus__multi_signal_relay = function() {
if (multi_signal_relayCache === null) {
multi_signal_relayCache = multi_signal_relayFunc();
}
return multi_signal_relayCache;
};
window.modules = modules;
})();
(function() {
var modules = window.modules || [];
var signalCache = null;
var signalFunc = function() {
return (function() {
var Signal,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__slice = [].slice;
Signal = (function() {
function Signal() {
this.dispatch = __bind(this.dispatch, this); this.isApplyingListeners = false;
this.listeners = [];
this.onceListeners = [];
this.removeCache = [];
}
Signal.prototype.add = function(listener) {
return this.listeners.push(listener);
};
Signal.prototype.addOnce = function(listener) {
this.onceListeners.push(listener);
return this.add(listener);
};
Signal.prototype.remove = function(listener) {
if (this.isApplyingListeners) {
return this.removeCache.push(listener);
} else {
if (this.listeners.indexOf(listener) !== -1) {
return this.listeners.splice(this.listeners.indexOf(listener), 1);
}
}
};
Signal.prototype.removeAll = function() {
return this.listeners = [];
};
Signal.prototype.numListeners = function() {
return this.listeners.length;
};
Signal.prototype.dispatch = function() {
var rest;
rest = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
this.isApplyingListeners = true;
this.applyListeners(rest);
this.removeOnceListeners();
this.isApplyingListeners = false;
return this.clearRemoveCache();
};
Signal.prototype.applyListeners = function(rest) {
var listener, _i, _len, _ref, _results;
_ref = this.listeners;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
listener = _ref[_i];
_results.push(listener.apply(listener, rest));
}
return _results;
};
Signal.prototype.removeOnceListeners = function() {
var listener, _i, _len, _ref;
_ref = this.onceListeners;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
listener = _ref[_i];
this.remove(listener);
}
return this.onceListeners = [];
};
Signal.prototype.clearRemoveCache = function() {
var listener, _i, _len, _ref;
_ref = this.removeCache;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
listener = _ref[_i];
this.remove(listener);
}
return this.removeCache = [];
};
return Signal;
})();
return Signal;
}).call(this);
};
modules.cronus__signal = function() {
if (signalCache === null) {
signalCache = signalFunc();
}
return signalCache;
};
window.modules = modules;
})();
(function() {
var modules = window.modules || [];
var signal_relayCache = null;
var signal_relayFunc = function() {
return (function() {
var Signal, SignalRelay,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Signal = require("cronus/signal");
SignalRelay = (function(_super) {
__extends(SignalRelay, _super);
function SignalRelay(signal) {
SignalRelay.__super__.constructor.call(this);
signal.add(this.dispatch);
}
SignalRelay.prototype.applyListeners = function(rest) {
var listener, _i, _len, _ref, _results;
_ref = this.listeners;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
listener = _ref[_i];
_results.push(listener.apply(listener, rest));
}
return _results;
};
return SignalRelay;
})(Signal);
return SignalRelay;
}).call(this);
};
modules.cronus__signal_relay = function() {
if (signal_relayCache === null) {
signal_relayCache = signal_relayFunc();
}
return signal_relayCache;
};
window.modules = modules;
})();
|
tshelburne/gator-js
|
spec/bin/gator.js
|
JavaScript
|
mit
| 14,495
|
#!/bin/bash
RAND=$(( ( RANDOM % 42 ) + 1 ))
for (( i=1; i<=RAND; i++ ))
do
curl -s -o /dev/null http://147.75.100.207/zwitscher-service/admin/info
done
curl http://147.75.100.207/zwitscher-service/tweets
|
qaware/hitchhikers-guide-cloudnative
|
solution/random-zwitscher-service.sh
|
Shell
|
mit
| 208
|
//*****************************************************************************
//
// mpu9150.c - Driver for the MPU9150 accelerometer, gyroscope, and
// magnetometer.
//
// Copyright (c) 2013-2016 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 2.1.3.156 of the Tiva Firmware Development Package.
//
//*****************************************************************************
#include <stdint.h>
#include "sensorlib/hw_ak8975.h"
#include "sensorlib/hw_mpu9150.h"
#include "sensorlib/i2cm_drv.h"
#include "sensorlib/ak8975.h"
#include "sensorlib/mpu9150.h"
//*****************************************************************************
//
//! \addtogroup mpu9150_api
//! @{
//
//*****************************************************************************
//*****************************************************************************
//
// The states of the MPU9150 state machine.
//
//*****************************************************************************
#define MPU9150_STATE_IDLE 0 // State machine is idle
#define MPU9150_STATE_LAST 1 // Last step in a sequence
#define MPU9150_STATE_READ 2 // Waiting for read
#define MPU9150_STATE_WRITE 3 // Waiting for write
#define MPU9150_STATE_RMW 4 // Waiting for read modify write
#define MPU9150_STATE_INIT_RESET \
5 // reset request issued.
#define MPU9150_STATE_INIT_RESET_WAIT \
6 // polling wait for reset complete
#define MPU9150_STATE_INIT_PWR_MGMT \
7 // wake up the device.
#define MPU9150_STATE_INIT_USER_CTRL \
8 // init user control
#define MPU9150_STATE_INIT_SAMPLE_RATE_CFG \
9 // init the sensors and filters
#define MPU9150_STATE_INIT_I2C_SLAVE_DLY \
10 // set the ak8975 polling delay
#define MPU9150_STATE_INIT_I2C_SLAVE_0 \
11 // config ak8975 automatic read
#define MPU9150_STATE_RD_DATA 12 // Waiting for data read
//*****************************************************************************
//
// The factors used to convert the acceleration readings from the MPU9150 into
// floating point values in meters per second squared.
//
// Values are obtained by taking the g conversion factors from the data sheet
// and multiplying by 9.81 (1 g = 9.81 m/s^2).
//
//*****************************************************************************
static const float g_fMPU9150AccelFactors[] =
{
0.0005985482, // Range = +/- 2 g (16384 lsb/g)
0.0011970964, // Range = +/- 4 g (8192 lsb/g)
0.0023941928, // Range = +/- 8 g (4096 lsb/g)
0.0047883855 // Range = +/- 16 g (2048 lsb/g)
};
//*****************************************************************************
//
// The factors used to convert the acceleration readings from the MPU9150 into
// floating point values in radians per second.
//
// Values are obtained by taking the degree per second conversion factors
// from the data sheet and then converting to radians per sec (1 degree =
// 0.0174532925 radians).
//
//*****************************************************************************
static const float g_fMPU9150GyroFactors[] =
{
1.3323124e-4, // Range = +/- 250 dps (131.0)
2.6646248e-4, // Range = +/- 500 dps (65.5)
5.3211258e-4, // Range = +/- 1000 dps (32.8)
0.0010642252 // Range = +/- 2000 dps (16.4)
};
//*****************************************************************************
//
// Converting sensor data to tesla (0.3 uT per LSB)
//
//*****************************************************************************
#define CONVERT_TO_TESLA 0.0000003
//*****************************************************************************
//
// The callback function that is called when I2C transations to/from the
// MPU9150 have completed.
//
//*****************************************************************************
static void
MPU9150Callback(void *pvCallbackData, uint_fast8_t ui8Status)
{
tMPU9150 *psInst;
//
// Convert the instance data into a pointer to a tMPU9150 structure.
//
psInst = pvCallbackData;
//
// If the I2C master driver encountered a failure, force the state machine
// to the idle state (which will also result in a callback to propagate the
// error). Except in the case that we are in the reset wait state and the
// error is an address NACK. This error is handled by the reset wait
// state.
//
if((ui8Status != I2CM_STATUS_SUCCESS) &&
!((ui8Status == I2CM_STATUS_ADDR_NACK) &&
(psInst->ui8State == MPU9150_STATE_INIT_RESET_WAIT)))
{
psInst->ui8State = MPU9150_STATE_IDLE;
}
//
// Determine the current state of the MPU9150 state machine.
//
switch(psInst->ui8State)
{
//
// All states that trivially transition to IDLE, and all unknown
// states.
//
case MPU9150_STATE_READ:
case MPU9150_STATE_LAST:
case MPU9150_STATE_RD_DATA:
default:
{
//
// The state machine is now idle.
//
psInst->ui8State = MPU9150_STATE_IDLE;
//
// Done.
//
break;
}
//
// MPU9150 Device reset was issued
//
case MPU9150_STATE_INIT_RESET:
{
//
// Issue a read of the status register to confirm reset is done.
//
psInst->uCommand.pui8Buffer[0] = MPU9150_O_PWR_MGMT_1;
I2CMRead(psInst->psI2CInst, psInst->ui8Addr,
psInst->uCommand.pui8Buffer, 1, psInst->pui8Data, 1,
MPU9150Callback, psInst);
psInst->ui8State = MPU9150_STATE_INIT_RESET_WAIT;
break;
}
//
// Status register was read, check if reset is done before proceeding.
//
case MPU9150_STATE_INIT_RESET_WAIT:
{
//
// Check the value read back from status to determine if device
// is still in reset or if it is ready. Reset state for this
// register is 0x40, which has sleep bit set. Device may also
// respond with an address NACK during very early stages of the
// its internal reset. Keep polling until we verify device is
// ready.
//
if((psInst->pui8Data[0] != MPU9150_PWR_MGMT_1_SLEEP) ||
(ui8Status == I2CM_STATUS_ADDR_NACK))
{
//
// Device still in reset so begin polling this register.
//
psInst->uCommand.pui8Buffer[0] = MPU9150_O_PWR_MGMT_1;
I2CMRead(psInst->psI2CInst, psInst->ui8Addr,
psInst->uCommand.pui8Buffer, 1, psInst->pui8Data, 1,
MPU9150Callback, psInst);
//
// Intentionally stay in this state to create polling effect.
//
}
else
{
//
// Device is out of reset, bring it out of sleep mode.
//
psInst->uCommand.pui8Buffer[0] = MPU9150_O_PWR_MGMT_1;
psInst->uCommand.pui8Buffer[1] = MPU9150_PWR_MGMT_1_CLKSEL_XG;
I2CMWrite(psInst->psI2CInst, psInst->ui8Addr,
psInst->uCommand.pui8Buffer, 2, MPU9150Callback,
psInst);
//
// Update state to show we are modifing user control and
// power management 1 regs.
//
psInst->ui8State = MPU9150_STATE_INIT_PWR_MGMT;
}
break;
}
//
// Reset complete now take device out of sleep mode.
//
case MPU9150_STATE_INIT_PWR_MGMT:
{
psInst->uCommand.pui8Buffer[0] = MPU9150_O_USER_CTRL;
psInst->uCommand.pui8Buffer[1] = MPU9150_USER_CTRL_I2C_MST_EN;
I2CMWrite(psInst->psI2CInst, psInst->ui8Addr,
psInst->uCommand.pui8Buffer, 2, MPU9150Callback,
psInst);
//
// Update state to show we are modifing user control and
// power management 1 regs.
//
psInst->ui8State = MPU9150_STATE_INIT_USER_CTRL;
break;
}
//
// Change to power mode complete, device is ready for configuration.
//
case MPU9150_STATE_INIT_USER_CTRL:
{
//
// Load index 0 with the sample rate register number.
//
psInst->uCommand.pui8Buffer[0] = MPU9150_O_SMPLRT_DIV;
//
// Set sample rate to 50 hertz. 1000 hz / (1 + 19)
//
psInst->uCommand.pui8Buffer[1] = 19;
I2CMWrite(psInst->psI2CInst, psInst->ui8Addr,
psInst->uCommand.pui8Buffer, 2, MPU9150Callback, psInst);
//
// update state to show are in process of configuring sensors.
//
psInst->ui8State = MPU9150_STATE_INIT_SAMPLE_RATE_CFG;
break;
}
//
// Sensor configuration is complete.
//
case MPU9150_STATE_INIT_SAMPLE_RATE_CFG:
{
//
// Write the I2C Master delay control so we only sample the AK
// every 5th time that we sample accel/gyro. Delay Count itself
// handled in next state.
//
psInst->uCommand.pui8Buffer[0] = MPU9150_O_I2C_MST_DELAY_CTRL;
psInst->uCommand.pui8Buffer[1] =
(MPU9150_I2C_MST_DELAY_CTRL_I2C_SLV0_DLY_EN |
MPU9150_I2C_MST_DELAY_CTRL_I2C_SLV4_DLY_EN);
I2CMWrite(psInst->psI2CInst, psInst->ui8Addr,
psInst->uCommand.pui8Buffer, 2, MPU9150Callback, psInst);
//
// Update state to show we are configuring i2c slave delay between
// slave events. Slave 0 and Slave 4 transaction only occur every
// 5th sample cycle.
//
psInst->ui8State = MPU9150_STATE_INIT_I2C_SLAVE_DLY;
break;
}
//
// Master slave delay configuration complete.
//
case MPU9150_STATE_INIT_I2C_SLAVE_DLY:
{
//
// Write the configuration for I2C master control clock 400khz
// and wait for external sensor before asserting data ready
//
psInst->uCommand.pui8Buffer[0] = MPU9150_O_I2C_MST_CTRL;
psInst->uCommand.pui8Buffer[1] =
(MPU9150_I2C_MST_CTRL_I2C_MST_CLK_400 |
MPU9150_I2C_MST_CTRL_WAIT_FOR_ES);
//
// Configure I2C Slave 0 for read of AK8975 (I2C Address 0x0C)
// Start at AK8975 register status 1
// Read 8 bytes and enable this slave transaction
//
psInst->uCommand.pui8Buffer[2] = MPU9150_I2C_SLV0_ADDR_RW | 0x0C;
psInst->uCommand.pui8Buffer[3] = AK8975_O_ST1;
psInst->uCommand.pui8Buffer[4] = MPU9150_I2C_SLV0_CTRL_EN | 0x08;
I2CMWrite(psInst->psI2CInst, psInst->ui8Addr,
psInst->uCommand.pui8Buffer, 5, MPU9150Callback, psInst);
//
// Update state. Now in process of configuring slave 0.
//
psInst->ui8State = MPU9150_STATE_INIT_I2C_SLAVE_0;
break;
}
//
// I2C slave 0 init complete.
//
case MPU9150_STATE_INIT_I2C_SLAVE_0:
{
//
// Write the configuration for I2C Slave 4 transaction to AK8975
// 0x0c is the AK8975 address on i2c bus.
// we want to write the control register with the value for a
// starting a single measurement.
//
psInst->uCommand.pui8Buffer[0] = MPU9150_O_I2C_SLV4_ADDR;
psInst->uCommand.pui8Buffer[1] = 0x0C;
psInst->uCommand.pui8Buffer[2] = AK8975_O_CNTL;
psInst->uCommand.pui8Buffer[3] = AK8975_CNTL_MODE_SINGLE;
//
// Enable the SLV4 transaction and set the master delay to
// 0x04 + 1. This means the slave transactions with delay enabled
// will run every fifth accel/gyro sample.
//
psInst->uCommand.pui8Buffer[4] = MPU9150_I2C_SLV4_CTRL_EN | 0x04;
I2CMWrite(psInst->psI2CInst, psInst->ui8Addr,
psInst->uCommand.pui8Buffer, 5, MPU9150Callback, psInst);
//
// Update state. Now in the final init state.
//
psInst->ui8State = MPU9150_STATE_LAST;
break;
}
//
// A write just completed
//
case MPU9150_STATE_WRITE:
{
//
// Set the accelerometer and gyroscope ranges to the new values.
// If the register was not modified, the values will be the same so
// this has no effect.
//
psInst->ui8AccelAfsSel = psInst->ui8NewAccelAfsSel;
psInst->ui8GyroFsSel = psInst->ui8NewGyroFsSel;
//
// The state machine is now idle.
//
psInst->ui8State = MPU9150_STATE_IDLE;
//
// Done.
//
break;
}
//
// A read-modify-write just completed
//
case MPU9150_STATE_RMW:
{
//
// See if the PWR_MGMT_1 register was just modified.
//
if(psInst->uCommand.sReadModifyWriteState.pui8Buffer[0] ==
MPU9150_O_PWR_MGMT_1)
{
//
// See if a soft reset has been issued.
//
if(psInst->uCommand.sReadModifyWriteState.pui8Buffer[1] &
MPU9150_PWR_MGMT_1_DEVICE_RESET)
{
//
// Default range setting is +/- 2 g
//
psInst->ui8AccelAfsSel = 0;
psInst->ui8NewAccelAfsSel = 0;
//
// Default range setting is +/- 250 degrees/s
//
psInst->ui8GyroFsSel = 0;
psInst->ui8NewGyroFsSel = 0;
}
}
//
// See if the GYRO_CONFIG register was just modified.
//
if(psInst->uCommand.sReadModifyWriteState.pui8Buffer[0] ==
MPU9150_O_GYRO_CONFIG)
{
//
// Extract the FS_SEL from the GYRO_CONFIG register value.
//
psInst->ui8GyroFsSel =
((psInst->uCommand.sReadModifyWriteState.pui8Buffer[1] &
MPU9150_GYRO_CONFIG_FS_SEL_M) >>
MPU9150_GYRO_CONFIG_FS_SEL_S);
}
//
// See if the ACCEL_CONFIG register was just modified.
//
if(psInst->uCommand.sReadModifyWriteState.pui8Buffer[0] ==
MPU9150_O_ACCEL_CONFIG)
{
//
// Extract the FS_SEL from the ACCEL_CONFIG register value.
//
psInst->ui8AccelAfsSel =
((psInst->uCommand.sReadModifyWriteState.pui8Buffer[1] &
MPU9150_ACCEL_CONFIG_AFS_SEL_M) >>
MPU9150_ACCEL_CONFIG_AFS_SEL_S);
}
//
// The state machine is now idle.
//
psInst->ui8State = MPU9150_STATE_IDLE;
//
// Done.
//
break;
}
}
//
// See if the state machine is now idle and there is a callback function.
//
if((psInst->ui8State == MPU9150_STATE_IDLE) && psInst->pfnCallback)
{
//
// Call the application-supplied callback function.
//
psInst->pfnCallback(psInst->pvCallbackData, ui8Status);
}
}
//*****************************************************************************
//
//! Initializes the MPU9150 driver.
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//! \param psI2CInst is a pointer to the I2C master driver instance data.
//! \param ui8I2CAddr is the I2C address of the MPU9150 device.
//! \param pfnCallback is the function to be called when the initialization has
//! completed (can be \b NULL if a callback is not required).
//! \param pvCallbackData is a pointer that is passed to the callback function.
//!
//! This function initializes the MPU9150 driver, preparing it for operation.
//!
//! \return Returns 1 if the MPU9150 driver was successfully initialized and 0
//! if it was not.
//
//*****************************************************************************
uint_fast8_t
MPU9150Init(tMPU9150 *psInst, tI2CMInstance *psI2CInst,
uint_fast8_t ui8I2CAddr, tSensorCallback *pfnCallback,
void *pvCallbackData)
{
//
// Initialize the MPU9150 instance structure.
//
psInst->psI2CInst = psI2CInst;
psInst->ui8Addr = ui8I2CAddr;
//
// Save the callback information.
//
psInst->pfnCallback = pfnCallback;
psInst->pvCallbackData = pvCallbackData;
//
// Default range setting is +/- 2 g
//
psInst->ui8AccelAfsSel = (MPU9150_ACCEL_CONFIG_AFS_SEL_2G >>
MPU9150_ACCEL_CONFIG_AFS_SEL_S);
psInst->ui8NewAccelAfsSel = (MPU9150_ACCEL_CONFIG_AFS_SEL_2G >>
MPU9150_ACCEL_CONFIG_AFS_SEL_S);
//
// Default range setting is +/- 250 degrees/s
//
psInst->ui8GyroFsSel = (MPU9150_GYRO_CONFIG_FS_SEL_250 >>
MPU9150_GYRO_CONFIG_FS_SEL_S);
psInst->ui8NewGyroFsSel = (MPU9150_GYRO_CONFIG_FS_SEL_250 >>
MPU9150_GYRO_CONFIG_FS_SEL_S);
//
// Set the state to show we are initiating a reset.
//
psInst->ui8State = MPU9150_STATE_INIT_RESET;
//
// Load the buffer with command to perform device reset
//
psInst->uCommand.pui8Buffer[0] = MPU9150_O_PWR_MGMT_1;
psInst->uCommand.pui8Buffer[1] = MPU9150_PWR_MGMT_1_DEVICE_RESET;
if(I2CMWrite(psInst->psI2CInst, psInst->ui8Addr,
psInst->uCommand.pui8Buffer, 2, MPU9150Callback, psInst) == 0)
{
psInst->ui8State = MPU9150_STATE_IDLE;
return(0);
}
//
// Success
//
return(1);
}
//*****************************************************************************
//
//! Returns the pointer to the tAK8975 object
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//!
//! The MPU9150 contains in internal AK8975 magnetometer. To access data from
//! that sensor, application should use this function to get a pointer to the
//! tAK8975 object, and then use the AK8975 APIs.
//!
//! \return Returns the pointer to the tAK8975 object
//
//*****************************************************************************
tAK8975 *
MPU9150MagnetoInstGet(tMPU9150 *psInst)
{
return(&(psInst->sAK8975Inst));
}
//*****************************************************************************
//
//! Reads data from MPU9150 registers.
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//! \param ui8Reg is the first register to read.
//! \param pui8Data is a pointer to the location to store the data that is
//! read.
//! \param ui16Count is the number of data bytes to read.
//! \param pfnCallback is the function to be called when the data has been read
//! (can be \b NULL if a callback is not required).
//! \param pvCallbackData is a pointer that is passed to the callback function.
//!
//! This function reads a sequence of data values from consecutive registers in
//! the MPU9150.
//!
//! \return Returns 1 if the write was successfully started and 0 if it was
//! not.
//
//*****************************************************************************
uint_fast8_t
MPU9150Read(tMPU9150 *psInst, uint_fast8_t ui8Reg, uint8_t *pui8Data,
uint_fast16_t ui16Count, tSensorCallback *pfnCallback,
void *pvCallbackData)
{
//
// Return a failure if the MPU9150 driver is not idle (in other words,
// there is already an outstanding request to the MPU9150).
//
if(psInst->ui8State != MPU9150_STATE_IDLE)
{
return(0);
}
//
// Save the callback information.
//
psInst->pfnCallback = pfnCallback;
psInst->pvCallbackData = pvCallbackData;
//
// Move the state machine to the wait for read state.
//
psInst->ui8State = MPU9150_STATE_READ;
//
// Read the requested registers from the MPU9150.
//
psInst->uCommand.pui8Buffer[0] = ui8Reg;
if(I2CMRead(psInst->psI2CInst, psInst->ui8Addr,
psInst->uCommand.pui8Buffer, 1, pui8Data, ui16Count,
MPU9150Callback, psInst) == 0)
{
//
// The I2C write failed, so move to the idle state and return a
// failure.
//
psInst->ui8State = MPU9150_STATE_IDLE;
return(0);
}
//
// Success.
//
return(1);
}
//*****************************************************************************
//
//! Writes data to MPU9150 registers.
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//! \param ui8Reg is the first register to write.
//! \param pui8Data is a pointer to the data to write.
//! \param ui16Count is the number of data bytes to write.
//! \param pfnCallback is the function to be called when the data has been
//! written (can be \b NULL if a callback is not required).
//! \param pvCallbackData is a pointer that is passed to the callback function.
//!
//! This function writes a sequence of data values to consecutive registers in
//! the MPU9150. The first byte of the \e pui8Data buffer contains the value
//! to be written into the \e ui8Reg register, the second value contains the
//! data to be written into the next register, and so on.
//!
//! \return Returns 1 if the write was successfully started and 0 if it was
//! not.
//
//*****************************************************************************
uint_fast8_t
MPU9150Write(tMPU9150 *psInst, uint_fast8_t ui8Reg, const uint8_t *pui8Data,
uint_fast16_t ui16Count, tSensorCallback *pfnCallback,
void *pvCallbackData)
{
//
// Return a failure if the MPU9150 driver is not idle (in other words,
// there is already an outstanding request to the MPU9150).
//
if(psInst->ui8State != MPU9150_STATE_IDLE)
{
return(0);
}
//
// Save the callback information.
//
psInst->pfnCallback = pfnCallback;
psInst->pvCallbackData = pvCallbackData;
//
// See if the PWR_MGMT_1 register is being written.
//
if((ui8Reg <= MPU9150_O_PWR_MGMT_1) &&
((ui8Reg + ui16Count) > MPU9150_O_PWR_MGMT_1))
{
//
// See if a soft reset is being requested.
//
if(pui8Data[ui8Reg - MPU9150_O_PWR_MGMT_1] &
MPU9150_PWR_MGMT_1_DEVICE_RESET)
{
//
// Default range setting is +/- 2 g.
//
psInst->ui8NewAccelAfsSel = 0;
//
// Default range setting is +/- 250 degrees/s.
//
psInst->ui8NewGyroFsSel = 0;
}
}
//
// See if the GYRO_CONFIG register is being written.
//
if((ui8Reg <= MPU9150_O_GYRO_CONFIG) &&
((ui8Reg + ui16Count) > MPU9150_O_GYRO_CONFIG))
{
//
// Extract the FS_SEL from the GYRO_CONFIG register value.
//
psInst->ui8NewGyroFsSel = ((pui8Data[ui8Reg - MPU9150_O_GYRO_CONFIG] &
MPU9150_GYRO_CONFIG_FS_SEL_M) >>
MPU9150_GYRO_CONFIG_FS_SEL_S);
}
//
// See if the ACCEL_CONFIG register is being written.
//
if((ui8Reg <= MPU9150_O_ACCEL_CONFIG) &&
((ui8Reg + ui16Count) > MPU9150_O_ACCEL_CONFIG))
{
//
// Extract the AFS_SEL from the ACCEL_CONFIG register value.
//
psInst->ui8NewAccelAfsSel =
((pui8Data[ui8Reg - MPU9150_O_ACCEL_CONFIG] &
MPU9150_ACCEL_CONFIG_AFS_SEL_M) >>
MPU9150_ACCEL_CONFIG_AFS_SEL_S);
}
//
// Move the state machine to the wait for write state.
//
psInst->ui8State = MPU9150_STATE_WRITE;
//
// Write the requested registers to the MPU9150.
//
if(I2CMWrite8(&(psInst->uCommand.sWriteState), psInst->psI2CInst,
psInst->ui8Addr, ui8Reg, pui8Data, ui16Count,
MPU9150Callback, psInst) == 0)
{
//
// The I2C write failed, so move to the idle state and return a
// failure.
//
psInst->ui8State = MPU9150_STATE_IDLE;
return(0);
}
//
// Success.
//
return(1);
}
//*****************************************************************************
//
//! Performs a read-modify-write of a MPU9150 register.
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//! \param ui8Reg is the register to modify.
//! \param ui8Mask is the bit mask that is ANDed with the current register
//! value.
//! \param ui8Value is the bit mask that is ORed with the result of the AND
//! operation.
//! \param pfnCallback is the function to be called when the data has been
//! changed (can be \b NULL if a callback is not required).
//! \param pvCallbackData is a pointer that is passed to the callback function.
//!
//! This function changes the value of a register in the MPU9150 via a
//! read-modify-write operation, allowing one of the fields to be changed
//! without disturbing the other fields. The \e ui8Reg register is read, ANDed
//! with \e ui8Mask, ORed with \e ui8Value, and then written back to the
//! MPU9150.
//!
//! \return Returns 1 if the read-modify-write was successfully started and 0
//! if it was not.
//
//*****************************************************************************
uint_fast8_t
MPU9150ReadModifyWrite(tMPU9150 *psInst, uint_fast8_t ui8Reg,
uint_fast8_t ui8Mask, uint_fast8_t ui8Value,
tSensorCallback *pfnCallback, void *pvCallbackData)
{
//
// Return a failure if the MPU9150 driver is not idle (in other words,
// there is already an outstanding request to the MPU9150).
//
if(psInst->ui8State != MPU9150_STATE_IDLE)
{
return(0);
}
//
// Save the callback information.
//
psInst->pfnCallback = pfnCallback;
psInst->pvCallbackData = pvCallbackData;
//
// Move the state machine to the wait for read-modify-write state.
//
psInst->ui8State = MPU9150_STATE_RMW;
//
// Submit the read-modify-write request to the MPU9150.
//
if(I2CMReadModifyWrite8(&(psInst->uCommand.sReadModifyWriteState),
psInst->psI2CInst, psInst->ui8Addr, ui8Reg,
ui8Mask, ui8Value, MPU9150Callback, psInst) == 0)
{
//
// The I2C read-modify-write failed, so move to the idle state and
// return a failure.
//
psInst->ui8State = MPU9150_STATE_IDLE;
return(0);
}
//
// Success.
//
return(1);
}
//*****************************************************************************
//
//! Reads the accelerometer and gyroscope data from the MPU9150 and the
//! magnetometer data from the on-chip aK8975.
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//! \param pfnCallback is the function to be called when the data has been read
//! (can be \b NULL if a callback is not required).
//! \param pvCallbackData is a pointer that is passed to the callback function.
//!
//! This function initiates a read of the MPU9150 data registers. When the
//! read has completed (as indicated by calling the callback function), the new
//! readings can be obtained via:
//!
//! - MPU9150DataAccelGetRaw()
//! - MPU9150DataAccelGetFloat()
//! - MPU9150DataGyroGetRaw()
//! - MPU9150DataGyroGetFloat()
//! - MPU9150DataMagnetoGetRaw()
//! - MPU9150DataMagnetoGetFloat()
//!
//! \return Returns 1 if the read was successfully started and 0 if it was not.
//
//*****************************************************************************
uint_fast8_t
MPU9150DataRead(tMPU9150 *psInst, tSensorCallback *pfnCallback,
void *pvCallbackData)
{
//
// Return a failure if the MPU9150 driver is not idle (in other words,
// there is already an outstanding request to the MPU9150).
//
if(psInst->ui8State != MPU9150_STATE_IDLE)
{
return(0);
}
//
// Save the callback information.
//
psInst->pfnCallback = pfnCallback;
psInst->pvCallbackData = pvCallbackData;
//
// Move the state machine to the wait for data read state.
//
psInst->ui8State = MPU9150_STATE_RD_DATA;
//
// Read the data registers from the MPU9150.
//
// (ACCEL_XOUT_H(0x3B) -> GYRO_ZOUT_L(0x48) = 14 bytes
// Grab Ext Sens Data as well for another 8 bytes. ST1 + Mag Data + ST2
//
psInst->uCommand.pui8Buffer[0] = MPU9150_O_ACCEL_XOUT_H;
if(I2CMRead(psInst->psI2CInst, psInst->ui8Addr,
psInst->uCommand.pui8Buffer, 1, psInst->pui8Data, 22,
MPU9150Callback, psInst) == 0)
{
//
// The I2C read failed, so move to the idle state and return a failure.
//
psInst->ui8State = MPU9150_STATE_IDLE;
return(0);
}
//
// Success.
//
return(1);
}
//*****************************************************************************
//
//! Gets the raw accelerometer data from the most recent data read.
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//! \param pui16AccelX is a pointer to the value into which the raw X-axis
//! accelerometer data is stored.
//! \param pui16AccelY is a pointer to the value into which the raw Y-axis
//! accelerometer data is stored.
//! \param pui16AccelZ is a pointer to the value into which the raw Z-axis
//! accelerometer data is stored.
//!
//! This function returns the raw accelerometer data from the most recent data
//! read. The data is not manipulated in any way by the driver. If any of the
//! output data pointers are \b NULL, the corresponding data is not provided.
//!
//! \return None.
//
//*****************************************************************************
void
MPU9150DataAccelGetRaw(tMPU9150 *psInst, uint_fast16_t *pui16AccelX,
uint_fast16_t *pui16AccelY, uint_fast16_t *pui16AccelZ)
{
//
// Return the raw accelerometer values.
//
if(pui16AccelX)
{
*pui16AccelX = (psInst->pui8Data[0] << 8) | psInst->pui8Data[1];
}
if(pui16AccelY)
{
*pui16AccelY = (psInst->pui8Data[2] << 8) | psInst->pui8Data[3];
}
if(pui16AccelZ)
{
*pui16AccelZ = (psInst->pui8Data[4] << 8) | psInst->pui8Data[5];
}
}
//*****************************************************************************
//
//! Gets the accelerometer data from the most recent data read.
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//! \param pfAccelX is a pointer to the value into which the X-axis
//! accelerometer data is stored.
//! \param pfAccelY is a pointer to the value into which the Y-axis
//! accelerometer data is stored.
//! \param pfAccelZ is a pointer to the value into which the Z-axis
//! accelerometer data is stored.
//!
//! This function returns the accelerometer data from the most recent data
//! read, converted into meters per second squared (m/s^2). If any of the
//! output data pointers are \b NULL, the corresponding data is not provided.
//!
//! \return None.
//
//*****************************************************************************
void
MPU9150DataAccelGetFloat(tMPU9150 *psInst, float *pfAccelX, float *pfAccelY,
float *pfAccelZ)
{
float fFactor;
//
// Get the acceleration conversion factor for the current data format.
//
fFactor = g_fMPU9150AccelFactors[psInst->ui8AccelAfsSel];
//
// Convert the accelerometer values into m/sec^2
//
if(pfAccelX)
{
*pfAccelX = ((float)(int16_t)((psInst->pui8Data[0] << 8) |
psInst->pui8Data[1]) * fFactor);
}
if(pfAccelY)
{
*pfAccelY = ((float)(int16_t)((psInst->pui8Data[2] << 8) |
psInst->pui8Data[3]) * fFactor);
}
if(pfAccelZ)
{
*pfAccelZ = ((float)(int16_t)((psInst->pui8Data[4] << 8) |
psInst->pui8Data[5]) * fFactor);
}
}
//*****************************************************************************
//
//! Gets the raw gyroscope data from the most recent data read.
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//! \param pui16GyroX is a pointer to the value into which the raw X-axis
//! gyroscope data is stored.
//! \param pui16GyroY is a pointer to the value into which the raw Y-axis
//! gyroscope data is stored.
//! \param pui16GyroZ is a pointer to the value into which the raw Z-axis
//! gyroscope data is stored.
//!
//! This function returns the raw gyroscope data from the most recent data
//! read. The data is not manipulated in any way by the driver. If any of the
//! output data pointers are \b NULL, the corresponding data is not provided.
//!
//! \return None.
//
//*****************************************************************************
void
MPU9150DataGyroGetRaw(tMPU9150 *psInst, uint_fast16_t *pui16GyroX,
uint_fast16_t *pui16GyroY, uint_fast16_t *pui16GyroZ)
{
//
// Return the raw gyroscope values.
//
if(pui16GyroX)
{
*pui16GyroX = (psInst->pui8Data[8] << 8) | psInst->pui8Data[9];
}
if(pui16GyroY)
{
*pui16GyroY = (psInst->pui8Data[10] << 8) | psInst->pui8Data[11];
}
if(pui16GyroZ)
{
*pui16GyroZ = (psInst->pui8Data[12] << 8) | psInst->pui8Data[13];
}
}
//*****************************************************************************
//
//! Gets the gyroscope data from the most recent data read.
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//! \param pfGyroX is a pointer to the value into which the X-axis
//! gyroscope data is stored.
//! \param pfGyroY is a pointer to the value into which the Y-axis
//! gyroscope data is stored.
//! \param pfGyroZ is a pointer to the value into which the Z-axis
//! gyroscope data is stored.
//!
//! This function returns the gyroscope data from the most recent data read,
//! converted into radians per second. If any of the output data pointers are
//! \b NULL, the corresponding data is not provided.
//!
//! \return None.
//
//*****************************************************************************
void
MPU9150DataGyroGetFloat(tMPU9150 *psInst, float *pfGyroX, float *pfGyroY,
float *pfGyroZ)
{
float fFactor;
int16_t i16Temp;
//
// Get the gyroscope conversion factor for the current data format.
//
fFactor = g_fMPU9150GyroFactors[psInst->ui8GyroFsSel];
//
// Convert the gyroscope values into rad/sec
//
if(pfGyroX)
{
i16Temp = (int16_t)psInst->pui8Data[8];
i16Temp <<= 8;
i16Temp += psInst->pui8Data[9];
*pfGyroX = (float)i16Temp;
*pfGyroX *= fFactor;
}
if(pfGyroY)
{
i16Temp = (int16_t)psInst->pui8Data[10];
i16Temp <<= 8;
i16Temp += psInst->pui8Data[11];
*pfGyroY = (float)i16Temp;
*pfGyroY *= fFactor;
}
if(pfGyroZ)
{
i16Temp = (int16_t)psInst->pui8Data[12];
i16Temp <<= 8;
i16Temp += psInst->pui8Data[13];
*pfGyroZ = (float)i16Temp;
*pfGyroZ *= fFactor;
}
}
//*****************************************************************************
//
//! Gets the raw magnetometer data from the most recent data read.
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//! \param pui16MagnetoX is a pointer to the value into which the raw X-axis
//! magnetometer data is stored.
//! \param pui16MagnetoY is a pointer to the value into which the raw Y-axis
//! magnetometer data is stored.
//! \param pui16MagnetoZ is a pointer to the value into which the raw Z-axis
//! magnetometer data is stored.
//!
//! This function returns the raw magnetometer data from the most recent data
//! read. The data is not manipulated in any way by the driver. If any of the
//! output data pointers are \b NULL, the corresponding data is not provided.
//!
//! \return None.
//
//*****************************************************************************
void
MPU9150DataMagnetoGetRaw(tMPU9150 *psInst, uint_fast16_t *pui16MagnetoX,
uint_fast16_t *pui16MagnetoY,
uint_fast16_t *pui16MagnetoZ)
{
uint8_t *pui8ExtSensData;
pui8ExtSensData = &(psInst->pui8Data[14]);
//
// Return the raw magnetometer values.
//
if(pui16MagnetoX)
{
*pui16MagnetoX = (pui8ExtSensData[2] << 8) | pui8ExtSensData[1];
}
if(pui16MagnetoY)
{
*pui16MagnetoY = (pui8ExtSensData[4] << 8) | pui8ExtSensData[3];
}
if(pui16MagnetoZ)
{
*pui16MagnetoZ = (pui8ExtSensData[6] << 8) | pui8ExtSensData[5];
}
}
//*****************************************************************************
//
//! Gets the magnetometer data from the most recent data read.
//!
//! \param psInst is a pointer to the MPU9150 instance data.
//! \param pfMagnetoX is a pointer to the value into which the X-axis
//! magnetometer data is stored.
//! \param pfMagnetoY is a pointer to the value into which the Y-axis
//! magnetometer data is stored.
//! \param pfMagnetoZ is a pointer to the value into which the Z-axis
//! magnetometer data is stored.
//!
//! This function returns the magnetometer data from the most recent data read,
//! converted into tesla. If any of the output data pointers are
//! \b NULL, the corresponding data is not provided.
//!
//! \return None.
//
//*****************************************************************************
void
MPU9150DataMagnetoGetFloat(tMPU9150 *psInst, float *pfMagnetoX,
float *pfMagnetoY, float *pfMagnetoZ)
{
int16_t *pi16Data;
pi16Data = (int16_t *)(psInst->pui8Data + 15);
//
// Convert the magnetometer values into floating-point tesla values.
//
if(pfMagnetoX)
{
*pfMagnetoX = (float)pi16Data[0];
*pfMagnetoX *= CONVERT_TO_TESLA;
}
if(pfMagnetoY)
{
*pfMagnetoY = (float)pi16Data[1];
*pfMagnetoY *= CONVERT_TO_TESLA;
}
if(pfMagnetoZ)
{
*pfMagnetoZ = (float)pi16Data[2];
*pfMagnetoZ *= CONVERT_TO_TESLA;
}
}
//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************
|
robotics-at-maryland/qubo
|
embedded/drivers/sensorlib/mpu9150.c
|
C
|
mit
| 40,883
|
SIMPLE_SETTINGS = {
'OVERRIDE_BY_ENV': True
}
MY_VAR = u'Some Value'
|
drgarcia1986/simple-settings
|
tests/samples/special.py
|
Python
|
mit
| 74
|
import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name="size",
parent_name="histogram.marker.colorbar.tickfont",
**kwargs
):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
min=kwargs.pop("min", 1),
role=kwargs.pop("role", "style"),
**kwargs
)
|
plotly/python-api
|
packages/python/plotly/plotly/validators/histogram/marker/colorbar/tickfont/_size.py
|
Python
|
mit
| 541
|
# Introduction
Provide some promisified version (by bluebird) for some commonly used libs.
# Install
```bash
$ npm i bblib
```
# Usage
For Standard libs:
```js
const bfs = require('bblib/fs');
async function main() {
var exists = await bfs.exists('/path/to/file');
if (exists) {
// do something
}
}
main();
```
For npm packages:
bblib provide only the promisify script, so that you don't need to install all the packages.
in order to use promisified version of a npm package, you need to install it to your project manually.
for example, if you'd like to use promisified *request* lib:
1. install the request package by:
```bash
$ npm i request -S
```
2. use the promisified version in your code:
```js
const request = require('bblib/request');
async function main() {
var res = await request('https://www.google.com');
console.log(`status: ${res.statusCode}`);
console.log(`body : ${res.body}`);
}
main();
```
# Wrappers
Some libs were designed base on EvenEmitter, which can not be promisified simply.
Here is the list or some useful libs
Same as before, you need to install the original package first by
```bash
$ npm i $PKG -S
```
## sh
Wrap `child_process` to execute shell command
## ssh2
Wrap `ssh2` to provide ssh access
Homepage: https://github.com/mscdex/ssh2
```
const Client = require('bblib/ssh2');
async function main() {
var client = new Client({
host: 'example.com',
username: 'root',
password: '******'
});
var retryCount = 10;
try {
await client.connect(retryCount);
} catch (e) {
...
}
var files = await client.exec('ls');
var sftp = await client.sftp();
await sftp.writeFile('/path/to/files.log', files);
client.disconnect();
}
```
## RestClient
Wrap request to provide a general purpose RESTful client
```
var client = new RestClient({
suppress: true, // suppress rejection while response status is not ok
prefix: 'http://api.example.com', // api url prefix
beforeSend: async function(opts) { // modify request options before sending, like adding signature
opts.headers = {
signature: await sign(opt.form)
};
},
afterReceive: function(resp) { // reject with a custom error while status code is not 200
if (resp.status !== 200)
return P.reject(new MyOwnError('request error'));
}
})
// or:
var client = new RestClient({ suppress: true });
client.prefix = 'https://api.example.com';
client.beforeSend = function(options) { };
// then:
async function madin() {
var getQuery = { page: 2 };
var list = await client.get('/orders', getQuery);
if (list['error'])
throw new Error(list['message']);
console.log(list.body['data']);
var postJson = { name: 'John Doe', phone: '94823944', ... };
var postQuery = { overwrite: true };
var created = await client.post('/orders', postJson, postQuery);
if (created['error'])
throw new Error(created['message']);
console.log(created.body.data.id);
try {
client.suppress = false;
await client.get('/path/some/error');
} catch (e) {
console.log(e.response.body.message);
}
}
```
# Contribution
You are more than welcome to contribute by sending Pull Request.
|
klesh/bblib
|
README.md
|
Markdown
|
mit
| 3,254
|
<?php
/*
Safe sample
input : Get a serialize string in POST and unserialize it
sanitize : use of the function htmlspecialchars. Sanitizes the query but has a high chance to produce unexpected results
construction : concatenation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$string = $_POST['UserData'] ;
$tainted = unserialize($string);
$tainted = htmlspecialchars($tainted, ENT_QUOTES);
$var = include("'". $tainted . ".php'");
?>
|
stivalet/PHP-Vulnerability-test-suite
|
Injection/CWE_98/safe/CWE_98__unserialize__func_htmlspecialchars__include_file_name-concatenation_simple_quote.php
|
PHP
|
mit
| 1,331
|
/*!
@package noty - jQuery Notification Plugin
@version version: 2.3.7
@contributors https://github.com/needim/noty/graphs/contributors
@documentation Examples and Documentation - http://needim.github.com/noty/
@license Licensed under the MIT licenses: http://www.opensource.org/licenses/mit-license.php
*/
if(typeof Object.create !== 'function') {
Object.create = function(o) {
function F() {
}
F.prototype = o;
return new F();
};
}
var NotyObject = {
init: function(options) {
// Mix in the passed in options with the default options
this.options = $.extend({}, $.noty.defaults, options);
this.options.layout = (this.options.custom) ? $.noty.layouts['inline'] : $.noty.layouts[this.options.layout];
if($.noty.themes[this.options.theme])
this.options.theme = $.noty.themes[this.options.theme];
else
options.themeClassName = this.options.theme;
delete options.layout;
delete options.theme;
this.options = $.extend({}, this.options, this.options.layout.options);
this.options.id = 'noty_' + (new Date().getTime() * Math.floor(Math.random() * 1000000));
this.options = $.extend({}, this.options, options);
// Build the noty dom initial structure
this._build();
// return this so we can chain/use the bridge with less code.
return this;
}, // end init
_build: function() {
// Generating noty bar
var $bar = $('<div class="noty_bar noty_type_' + this.options.type + '"></div>').attr('id', this.options.id);
$bar.append(this.options.template).find('.noty_text').html(this.options.text);
this.$bar = (this.options.layout.parent.object !== null) ? $(this.options.layout.parent.object).css(this.options.layout.parent.css).append($bar) : $bar;
if(this.options.themeClassName)
this.$bar.addClass(this.options.themeClassName).addClass('noty_container_type_' + this.options.type);
// Set buttons if available
if(this.options.buttons) {
// If we have button disable closeWith & timeout options
this.options.closeWith = [];
this.options.timeout = false;
var $buttons = $('<div/>').addClass('noty_buttons');
(this.options.layout.parent.object !== null) ? this.$bar.find('.noty_bar').append($buttons) : this.$bar.append($buttons);
var self = this;
$.each(this.options.buttons, function(i, button) {
var $button = $('<button/>').addClass((button.addClass) ? button.addClass : 'gray').html(button.text).attr('id', button.id ? button.id : 'button-' + i)
.attr('title', button.title)
.appendTo(self.$bar.find('.noty_buttons'))
.on('click', function(event) {
if($.isFunction(button.onClick)) {
button.onClick.call($button, self, event);
}
});
});
}
// For easy access
this.$message = this.$bar.find('.noty_message');
this.$closeButton = this.$bar.find('.noty_close');
this.$buttons = this.$bar.find('.noty_buttons');
$.noty.store[this.options.id] = this; // store noty for api
}, // end _build
show: function() {
var self = this;
(self.options.custom) ? self.options.custom.find(self.options.layout.container.selector).append(self.$bar) : $(self.options.layout.container.selector).append(self.$bar);
if(self.options.theme && self.options.theme.style)
self.options.theme.style.apply(self);
($.type(self.options.layout.css) === 'function') ? this.options.layout.css.apply(self.$bar) : self.$bar.css(this.options.layout.css || {});
self.$bar.addClass(self.options.layout.addClass);
self.options.layout.container.style.apply($(self.options.layout.container.selector), [self.options.within]);
self.showing = true;
if(self.options.theme && self.options.theme.style)
self.options.theme.callback.onShow.apply(this);
if($.inArray('click', self.options.closeWith) > -1)
self.$bar.css('cursor', 'pointer').one('click', function(evt) {
self.stopPropagation(evt);
if(self.options.callback.onCloseClick) {
self.options.callback.onCloseClick.apply(self);
}
self.close();
});
if($.inArray('hover', self.options.closeWith) > -1)
self.$bar.one('mouseenter', function() {
self.close();
});
if($.inArray('button', self.options.closeWith) > -1)
self.$closeButton.one('click', function(evt) {
self.stopPropagation(evt);
self.close();
});
if($.inArray('button', self.options.closeWith) == -1)
self.$closeButton.remove();
if(self.options.callback.onShow)
self.options.callback.onShow.apply(self);
if (typeof self.options.animation.open == 'string') {
self.$bar.css('height', self.$bar.innerHeight());
self.$bar.show().addClass(self.options.animation.open).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
if(self.options.callback.afterShow) self.options.callback.afterShow.apply(self);
self.showing = false;
self.shown = true;
});
} else {
self.$bar.animate(
self.options.animation.open,
self.options.animation.speed,
self.options.animation.easing,
function() {
if(self.options.callback.afterShow) self.options.callback.afterShow.apply(self);
self.showing = false;
self.shown = true;
});
}
// If noty is have a timeout option
if(self.options.timeout)
self.$bar.delay(self.options.timeout).promise().done(function() {
self.close();
});
return this;
}, // end show
close: function() {
if(this.closed) return;
if(this.$bar && this.$bar.hasClass('i-am-closing-now')) return;
var self = this;
if(this.showing) {
self.$bar.queue(
function() {
self.close.apply(self);
}
);
return;
}
if(!this.shown && !this.showing) { // If we are still waiting in the queue just delete from queue
var queue = [];
$.each($.noty.queue, function(i, n) {
if(n.options.id != self.options.id) {
queue.push(n);
}
});
$.noty.queue = queue;
return;
}
self.$bar.addClass('i-am-closing-now');
if(self.options.callback.onClose) {
self.options.callback.onClose.apply(self);
}
if (typeof self.options.animation.close == 'string') {
self.$bar.addClass(self.options.animation.close).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
if(self.options.callback.afterClose) self.options.callback.afterClose.apply(self);
self.closeCleanUp();
});
} else {
self.$bar.clearQueue().stop().animate(
self.options.animation.close,
self.options.animation.speed,
self.options.animation.easing,
function() {
if(self.options.callback.afterClose) self.options.callback.afterClose.apply(self);
})
.promise().done(function() {
self.closeCleanUp();
});
}
}, // end close
closeCleanUp: function() {
var self = this;
// Modal Cleaning
if(self.options.modal) {
$.notyRenderer.setModalCount(-1);
if($.notyRenderer.getModalCount() == 0) $('.noty_modal').fadeOut(self.options.animation.fadeSpeed, function() {
$(this).remove();
});
}
// Layout Cleaning
$.notyRenderer.setLayoutCountFor(self, -1);
if($.notyRenderer.getLayoutCountFor(self) == 0) $(self.options.layout.container.selector).remove();
// Make sure self.$bar has not been removed before attempting to remove it
if(typeof self.$bar !== 'undefined' && self.$bar !== null) {
if (typeof self.options.animation.close == 'string') {
self.$bar.css('transition', 'all 100ms ease').css('border', 0).css('margin', 0).height(0);
self.$bar.one('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function() {
self.$bar.remove();
self.$bar = null;
self.closed = true;
if(self.options.theme.callback && self.options.theme.callback.onClose) {
self.options.theme.callback.onClose.apply(self);
}
});
} else {
self.$bar.remove();
self.$bar = null;
self.closed = true;
}
}
delete $.noty.store[self.options.id]; // deleting noty from store
if(self.options.theme.callback && self.options.theme.callback.onClose) {
self.options.theme.callback.onClose.apply(self);
}
if(!self.options.dismissQueue) {
// Queue render
$.noty.ontap = true;
$.notyRenderer.render();
}
if(self.options.maxVisible > 0 && self.options.dismissQueue) {
$.notyRenderer.render();
}
}, // end close clean up
setText: function(text) {
if(!this.closed) {
this.options.text = text;
this.$bar.find('.noty_text').html(text);
}
return this;
},
setType: function(type) {
if(!this.closed) {
this.options.type = type;
this.options.theme.style.apply(this);
this.options.theme.callback.onShow.apply(this);
}
return this;
},
setTimeout: function(time) {
if(!this.closed) {
var self = this;
this.options.timeout = time;
self.$bar.delay(self.options.timeout).promise().done(function() {
self.close();
});
}
return this;
},
stopPropagation: function(evt) {
evt = evt || window.event;
if(typeof evt.stopPropagation !== "undefined") {
evt.stopPropagation();
}
else {
evt.cancelBubble = true;
}
},
closed : false,
showing: false,
shown : false
}; // end NotyObject
$.notyRenderer = {};
$.notyRenderer.init = function(options) {
// Renderer creates a new noty
var notification = Object.create(NotyObject).init(options);
if(notification.options.killer)
$.noty.closeAll();
(notification.options.force) ? $.noty.queue.unshift(notification) : $.noty.queue.push(notification);
$.notyRenderer.render();
return ($.noty.returns == 'object') ? notification : notification.options.id;
};
$.notyRenderer.render = function() {
var instance = $.noty.queue[0];
if($.type(instance) === 'object') {
if(instance.options.dismissQueue) {
if(instance.options.maxVisible > 0) {
if($(instance.options.layout.container.selector + ' li').length < instance.options.maxVisible) {
$.notyRenderer.show($.noty.queue.shift());
}
else {
}
}
else {
$.notyRenderer.show($.noty.queue.shift());
}
}
else {
if($.noty.ontap) {
$.notyRenderer.show($.noty.queue.shift());
$.noty.ontap = false;
}
}
}
else {
$.noty.ontap = true; // Queue is over
}
};
$.notyRenderer.show = function(notification) {
if(notification.options.modal) {
$.notyRenderer.createModalFor(notification);
$.notyRenderer.setModalCount(+1);
}
// Where is the container?
if(notification.options.custom) {
if(notification.options.custom.find(notification.options.layout.container.selector).length == 0) {
notification.options.custom.append($(notification.options.layout.container.object).addClass('i-am-new'));
}
else {
notification.options.custom.find(notification.options.layout.container.selector).removeClass('i-am-new');
}
}
else {
if($(notification.options.layout.container.selector).length == 0) {
$('body').append($(notification.options.layout.container.object).addClass('i-am-new'));
}
else {
$(notification.options.layout.container.selector).removeClass('i-am-new');
}
}
$.notyRenderer.setLayoutCountFor(notification, +1);
notification.show();
};
$.notyRenderer.createModalFor = function(notification) {
if($('.noty_modal').length == 0) {
var modal = $('<div/>').addClass('noty_modal').addClass(notification.options.theme).data('noty_modal_count', 0);
if(notification.options.theme.modal && notification.options.theme.modal.css)
modal.css(notification.options.theme.modal.css);
modal.prependTo($('body')).fadeIn(self.options.animation.fadeSpeed);
if($.inArray('backdrop', notification.options.closeWith) > -1)
modal.on('click', function(e) {
$.noty.closeAll();
});
}
};
$.notyRenderer.getLayoutCountFor = function(notification) {
return $(notification.options.layout.container.selector).data('noty_layout_count') || 0;
};
$.notyRenderer.setLayoutCountFor = function(notification, arg) {
return $(notification.options.layout.container.selector).data('noty_layout_count', $.notyRenderer.getLayoutCountFor(notification) + arg);
};
$.notyRenderer.getModalCount = function() {
return $('.noty_modal').data('noty_modal_count') || 0;
};
$.notyRenderer.setModalCount = function(arg) {
return $('.noty_modal').data('noty_modal_count', $.notyRenderer.getModalCount() + arg);
};
// This is for custom container
$.fn.noty = function(options) {
options.custom = $(this);
return $.notyRenderer.init(options);
};
$.noty = {};
$.noty.queue = [];
$.noty.ontap = true;
$.noty.layouts = {};
$.noty.themes = {};
$.noty.returns = 'object';
$.noty.store = {};
$.noty.get = function(id) {
return $.noty.store.hasOwnProperty(id) ? $.noty.store[id] : false;
};
$.noty.close = function(id) {
return $.noty.get(id) ? $.noty.get(id).close() : false;
};
$.noty.setText = function(id, text) {
return $.noty.get(id) ? $.noty.get(id).setText(text) : false;
};
$.noty.setType = function(id, type) {
return $.noty.get(id) ? $.noty.get(id).setType(type) : false;
};
$.noty.clearQueue = function() {
$.noty.queue = [];
};
$.noty.closeAll = function() {
$.noty.clearQueue();
$.each($.noty.store, function(id, noty) {
noty.close();
});
};
var windowAlert = window.alert;
$.noty.consumeAlert = function(options) {
window.alert = function(text) {
if(options)
options.text = text;
else
options = {text: text};
$.notyRenderer.init(options);
};
};
$.noty.stopConsumeAlert = function() {
window.alert = windowAlert;
};
$.noty.defaults = {
layout : 'top',
theme : 'defaultTheme',
type : 'alert',
text : '',
dismissQueue: true,
template : '<div class="noty_message"><span class="noty_text"></span><div class="noty_close"></div></div>',
animation : {
open : {height: 'toggle'},
close : {height: 'toggle'},
easing: 'swing',
speed : 500,
fadeSpeed: 'fast',
},
timeout : false,
force : false,
modal : false,
maxVisible : 5,
killer : false,
closeWith : ['click'],
callback : {
onShow : function() {
},
afterShow : function() {
},
onClose : function() {
},
afterClose : function() {
},
onCloseClick: function() {
}
},
buttons : false
};
$(window).on('resize', function() {
$.each($.noty.layouts, function(index, layout) {
layout.container.style.apply($(layout.container.selector));
});
});
// Helpers
window.noty = function noty(options) {
return $.notyRenderer.init(options);
};
|
fico-juliuskabugu/noty
|
js/noty/jquery.noty.js
|
JavaScript
|
mit
| 18,619
|
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of // TODO: needs to adjusted for checkpoint checks, also see main.cpp
( 0, uint256("0x908ce9659ba0219008012712f47e2efe81fb408d72299198439c852035281fad"))
( 1, uint256("0x908ce9659ba0219008012712f47e2efe81fb408d72299198439c852035281fad"))
( 2, uint256("0x43682e5929c9234209db6592953347aa8b4c8e233692369a61b4780b80835c42"))
( 34336, uint256("0xfc6a3ee59b9f2429114178ff7a4792a7af102688156d26a3edbb90c243850dcd"))
( 50000, uint256("0x5fa3d8bb008a55a1b6e301b435be3a68985083435748b913ef8572bf1282303c"))
( 70000, uint256("0x7ee7864ffec5a23f526e01a1388a6e988d2773365522e04dd51d3c71c19b459f"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
if (i == mapCheckpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0;
return mapCheckpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
|
Baisang/antcoin
|
src/checkpoints.cpp
|
C++
|
mit
| 2,373
|
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
package announcement
import (
"encoding"
"fmt"
"reflect"
"strings"
"time"
pb "github.com/TheThingsNetwork/ttn/api/discovery"
"github.com/TheThingsNetwork/ttn/core/types"
"github.com/fatih/structs"
)
const currentDBVersion = "2.4.1"
// Metadata represents metadata that is stored with an Announcement
type Metadata interface {
encoding.TextMarshaler
ToProto() *pb.Metadata
}
// AppEUIMetadata is used to store an AppEUI
type AppEUIMetadata struct {
AppEUI types.AppEUI
}
// ToProto implements the Metadata interface
func (m AppEUIMetadata) ToProto() *pb.Metadata {
return &pb.Metadata{
Metadata: &pb.Metadata_AppEui{
AppEui: m.AppEUI.Bytes(),
},
}
}
// MarshalText implements the encoding.TextMarshaler interface
func (m AppEUIMetadata) MarshalText() ([]byte, error) {
return []byte(fmt.Sprintf("AppEUI %s", m.AppEUI)), nil
}
// AppIDMetadata is used to store an AppID
type AppIDMetadata struct {
AppID string
}
// ToProto implements the Metadata interface
func (m AppIDMetadata) ToProto() *pb.Metadata {
return &pb.Metadata{
Metadata: &pb.Metadata_AppId{
AppId: m.AppID,
},
}
}
// MarshalText implements the encoding.TextMarshaler interface
func (m AppIDMetadata) MarshalText() ([]byte, error) {
return []byte(fmt.Sprintf("AppID %s", m.AppID)), nil
}
// PrefixMetadata is used to store a DevAddr prefix
type PrefixMetadata struct {
Prefix types.DevAddrPrefix
}
// ToProto implements the Metadata interface
func (m PrefixMetadata) ToProto() *pb.Metadata {
return &pb.Metadata{
Metadata: &pb.Metadata_DevAddrPrefix{
DevAddrPrefix: m.Prefix.Bytes(),
},
}
}
// MarshalText implements the encoding.TextMarshaler interface
func (m PrefixMetadata) MarshalText() ([]byte, error) {
return []byte(fmt.Sprintf("Prefix %s", m.Prefix)), nil
}
// MetadataFromProto converts a protocol buffer metadata to a Metadata
func MetadataFromProto(proto *pb.Metadata) Metadata {
if euiBytes := proto.GetAppEui(); euiBytes != nil {
eui := new(types.AppEUI)
if err := eui.Unmarshal(euiBytes); err != nil {
return nil
}
return AppEUIMetadata{*eui}
}
if id := proto.GetAppId(); id != "" {
return AppIDMetadata{id}
}
if prefixBytes := proto.GetDevAddrPrefix(); prefixBytes != nil {
prefix := new(types.DevAddrPrefix)
if err := prefix.Unmarshal(prefixBytes); err != nil {
return nil
}
return PrefixMetadata{*prefix}
}
return nil
}
// MetadataFromString converts a string to a Metadata
func MetadataFromString(str string) Metadata {
meta := strings.SplitAfterN(str, " ", 2)
key := strings.TrimSpace(meta[0])
value := meta[1]
switch key {
case "AppEUI":
var appEUI types.AppEUI
appEUI.UnmarshalText([]byte(value))
return AppEUIMetadata{appEUI}
case "AppID":
return AppIDMetadata{value}
case "Prefix":
prefix := &types.DevAddrPrefix{
Length: 32,
}
prefix.UnmarshalText([]byte(value))
return PrefixMetadata{*prefix}
}
return nil
}
// Announcement of a network component
type Announcement struct {
old *Announcement
ID string `redis:"id"`
ServiceName string `redis:"service_name"`
ServiceVersion string `redis:"service_version"`
Description string `redis:"description"`
URL string `redis:"url"`
Public bool `redis:"public"`
NetAddress string `redis:"net_address"`
PublicKey string `redis:"public_key"`
Certificate string `redis:"certificate"`
APIAddress string `redis:"api_address"`
MQTTAddress string `redis:"mqtt_address"`
AMQPAddress string `redis:"amqp_address"`
Metadata []Metadata
CreatedAt time.Time `redis:"created_at"`
UpdatedAt time.Time `redis:"updated_at"`
}
// StartUpdate stores the state of the announcement
func (a *Announcement) StartUpdate() {
old := *a
a.old = &old
}
// DBVersion of the model
func (a *Announcement) DBVersion() string {
return currentDBVersion
}
// ChangedFields returns the names of the changed fields since the last call to StartUpdate
func (a Announcement) ChangedFields() (changed []string) {
new := structs.New(a)
fields := new.Names()
if a.old == nil {
return fields
}
old := structs.New(*a.old)
for _, field := range new.Fields() {
if !field.IsExported() || field.Name() == "old" {
continue
}
if !reflect.DeepEqual(field.Value(), old.Field(field.Name()).Value()) {
changed = append(changed, field.Name())
}
}
if len(changed) == 1 && changed[0] == "UpdatedAt" {
return []string{}
}
return
}
// ToProto converts the Announcement to a protobuf Announcement
func (a Announcement) ToProto() *pb.Announcement {
metadata := make([]*pb.Metadata, 0, len(a.Metadata))
for _, meta := range a.Metadata {
metadata = append(metadata, meta.ToProto())
}
return &pb.Announcement{
Id: a.ID,
ServiceName: a.ServiceName,
ServiceVersion: a.ServiceVersion,
Description: a.Description,
Url: a.URL,
Public: a.Public,
NetAddress: a.NetAddress,
PublicKey: a.PublicKey,
Certificate: a.Certificate,
ApiAddress: a.APIAddress,
MqttAddress: a.MQTTAddress,
AmqpAddress: a.AMQPAddress,
Metadata: metadata,
}
}
// FromProto converts an Announcement protobuf to an Announcement
func FromProto(a *pb.Announcement) Announcement {
metadata := make([]Metadata, 0, len(a.Metadata))
for _, meta := range a.Metadata {
metadata = append(metadata, MetadataFromProto(meta))
}
return Announcement{
ID: a.Id,
ServiceName: a.ServiceName,
ServiceVersion: a.ServiceVersion,
Description: a.Description,
URL: a.Url,
Public: a.Public,
NetAddress: a.NetAddress,
PublicKey: a.PublicKey,
Certificate: a.Certificate,
APIAddress: a.ApiAddress,
MQTTAddress: a.MqttAddress,
AMQPAddress: a.AmqpAddress,
Metadata: metadata,
}
}
|
jvanmalder/ttn
|
core/discovery/announcement/announcement.go
|
GO
|
mit
| 5,951
|
namespace NetBike.Xml
{
using System;
using System.Collections.Generic;
using System.Xml;
using NetBike.Xml.Contracts;
using NetBike.Xml.Converters;
public sealed class XmlSerializationContext
{
private XmlContract currentContract;
private XmlMember currentMember;
private bool initialState;
private Dictionary<string, object> properties;
private XmlNameRef typeNameRef;
private XmlNameRef nullNameRef;
private XmlReader lastUsedReader;
public XmlSerializationContext(XmlSerializerSettings settings)
{
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
this.Settings = settings;
this.initialState = true;
}
internal XmlSerializationContext(XmlSerializerSettings settings, XmlMember member, XmlContract contract)
: this(settings)
{
if (contract == null)
{
throw new ArgumentNullException(nameof(contract));
}
if (member == null)
{
throw new ArgumentNullException(nameof(member));
}
this.currentContract = contract;
this.currentMember = member;
this.initialState = false;
}
public Type ValueType => this.currentContract.ValueType;
public XmlContract Contract => this.currentContract;
public XmlMember Member => this.currentMember;
public IDictionary<string, object> Properties => this.properties ?? (this.properties = new Dictionary<string, object>());
public XmlSerializerSettings Settings { get; }
public XmlContract GetTypeContract(Type valueType)
{
return this.Settings.GetTypeContext(valueType).Contract;
}
public void Serialize(XmlWriter writer, object value, Type valueType)
{
if (valueType == null)
{
throw new ArgumentNullException(nameof(valueType));
}
this.Serialize(writer, value, valueType, null);
}
public void Serialize(XmlWriter writer, object value, XmlMember member)
{
if (member == null)
{
throw new ArgumentNullException(nameof(member));
}
this.Serialize(writer, value, member.ValueType, member);
}
public object Deserialize(XmlReader reader, Type valueType)
{
return this.Deserialize(reader, valueType, null);
}
public object Deserialize(XmlReader reader, XmlMember member)
{
return this.Deserialize(reader, member.ValueType, member);
}
public void SerializeBody(XmlWriter writer, object value, Type valueType)
{
if (valueType == null)
{
throw new ArgumentNullException(nameof(valueType));
}
this.SerializeBody(writer, value, valueType, null);
}
public void SerializeBody(XmlWriter writer, object value, XmlMember member)
{
if (member == null)
{
throw new ArgumentNullException(nameof(member));
}
this.SerializeBody(writer, value, member.ValueType, member);
}
internal void WriteTypeName(XmlWriter writer, Type valueType)
{
var typeName = this.Settings.TypeResolver.GetTypeName(valueType);
writer.WriteAttributeString(this.Settings.TypeAttributeName, typeName);
}
internal void WriteNull(XmlWriter writer, Type valueType, XmlMember member)
{
var nullValueHandling = this.Settings.NullValueHandling;
if (member != null)
{
if (member.MappingType == XmlMappingType.Attribute)
{
return;
}
nullValueHandling = member.NullValueHandling ?? nullValueHandling;
}
if (nullValueHandling != XmlNullValueHandling.Ignore)
{
if (member == null)
{
member = this.Settings.GetTypeContext(valueType).Contract.Root;
}
writer.WriteStartElement(member.Name);
if (this.initialState)
{
this.initialState = false;
this.WriteNamespaces(writer);
}
writer.WriteAttributeString(this.Settings.NullAttributeName, "true");
writer.WriteEndElement();
}
}
internal bool ReadValueType(XmlReader reader, ref Type valueType)
{
if (reader.AttributeCount > 0)
{
if (!object.ReferenceEquals(this.lastUsedReader, reader))
{
this.typeNameRef.Reset(this.Settings.TypeAttributeName, reader.NameTable);
this.nullNameRef.Reset(this.Settings.NullAttributeName, reader.NameTable);
this.lastUsedReader = reader;
}
if (reader.MoveToFirstAttribute())
{
do
{
if (this.nullNameRef.Match(reader))
{
return false;
}
else if (this.typeNameRef.Match(reader))
{
valueType = this.Settings.TypeResolver.ResolveTypeName(valueType, reader.Value);
}
}
while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
}
return true;
}
internal bool TryResolveValueType(object value, ref XmlMember member, out Type valueType)
{
if (member.IsOpenType)
{
var typeHandling = member.TypeHandling ?? this.Settings.TypeHandling;
if (typeHandling != XmlTypeHandling.None)
{
valueType = value.GetType();
member = member.ResolveMember(valueType);
return typeHandling == XmlTypeHandling.Always || valueType != member.ValueType;
}
}
valueType = member.ValueType;
return false;
}
internal void WriteXml(XmlWriter writer, object value, XmlMember member, XmlTypeContext typeContext)
{
var lastMember = this.currentMember;
var lastContract = this.currentContract;
this.currentMember = member;
this.currentContract = typeContext.Contract;
typeContext.WriteXml(writer, value, this);
this.currentMember = lastMember;
this.currentContract = lastContract;
}
internal object ReadXml(XmlReader reader, XmlMember member, XmlTypeContext typeContext)
{
var lastMember = this.currentMember;
var lastContract = this.currentContract;
this.currentMember = member;
this.currentContract = typeContext.Contract;
var value = typeContext.ReadXml(reader, this);
this.currentMember = lastMember;
this.currentContract = lastContract;
return value;
}
private void SerializeBody(XmlWriter writer, object value, Type memberType, XmlMember member)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (value == null)
{
this.WriteNull(writer, memberType, member);
}
else
{
var typeContext = this.Settings.GetTypeContext(memberType);
this.WriteXml(writer, value, member ?? typeContext.Contract.Root, typeContext);
}
}
private void Serialize(XmlWriter writer, object value, Type memberType, XmlMember member)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (value == null)
{
this.WriteNull(writer, memberType, member);
return;
}
XmlTypeContext context = null;
if (member == null)
{
context = this.Settings.GetTypeContext(memberType);
member = context.Contract.Root;
}
var shouldWriteTypeName = this.TryResolveValueType(value, ref member, out var valueType);
if (member.DefaultValue != null)
{
var defaultValueHandling = member.DefaultValueHandling ?? this.Settings.DefaultValueHandling;
if (defaultValueHandling == XmlDefaultValueHandling.Ignore && value.Equals(member.DefaultValue))
{
return;
}
}
if (context == null || context.Contract.ValueType != member.ValueType)
{
context = this.Settings.GetTypeContext(valueType);
}
switch (member.MappingType)
{
case XmlMappingType.Element:
writer.WriteStartElement(member.Name);
if (this.initialState)
{
this.initialState = false;
this.WriteNamespaces(writer);
}
if (shouldWriteTypeName)
{
this.WriteTypeName(writer, valueType);
}
this.WriteXml(writer, value, member, context);
writer.WriteEndElement();
break;
case XmlMappingType.Attribute:
writer.WriteStartAttribute(member.Name);
this.WriteXml(writer, value, member, context);
writer.WriteEndAttribute();
break;
case XmlMappingType.InnerText:
this.WriteXml(writer, value, member, context);
break;
}
}
private object Deserialize(XmlReader reader, Type valueType, XmlMember member)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
if (valueType == null)
{
throw new ArgumentNullException(nameof(valueType));
}
if (this.initialState && reader.NodeType == XmlNodeType.None)
{
this.initialState = false;
while (reader.NodeType != XmlNodeType.Element)
{
if (!reader.Read())
{
return null;
}
}
}
if (reader.NodeType == XmlNodeType.Element)
{
if (!this.ReadValueType(reader, ref valueType))
{
reader.Skip();
return null;
}
}
var typeInfo = this.Settings.GetTypeContext(valueType);
if (member == null)
{
member = typeInfo.Contract.Root;
}
return this.ReadXml(reader, member, typeInfo);
}
private void WriteNamespaces(XmlWriter writer)
{
foreach (var item in this.Settings.Namespaces)
{
writer.WriteNamespace(item);
}
}
}
}
|
netbike/netbike.xml
|
NetBike.Xml/XmlSerializationContext.cs
|
C#
|
mit
| 11,863
|
---
published: true
title: 开始我的博客
layout: post
author: Eureka912
category: Essay
---
### 1. 我为什么要写博客?
我的想法是,尽可能多的写计算机相关的文章,保持知识上的成长和学习状态;除去知识性的文章之外,也分享自己的思想关于人生或是别的之类的思考。大部分知识性分享的文章,我会放在别的网站--我的[博客园][2],以便别人可以检索到,这里只留下一下还算有趣的东西。因此,这个博客看起来更像是我写字的地方。
拥有知识是幸福的事情,但是人的思维和想法也极为重要,古希腊哲学家埃皮克提图(Epuctetus)就认为,“哲学不仅仅是一门学科,也是一种生活方式”。每个人都应该拥有自己对生活的思考。
>我对自己的要求很低:我活在世上,无非想要明白些道理,遇见些有趣的事。倘能如我所愿,我的一生就算成功。为此也要去论是非,否则道理不给保明白,有趣的事也不让你遇到。我开始得太晚了,很可能做不成什么,但我总得申明我的态度 -- 《沉默的大多数》 王小波
### 2. 计算机
很可惜也毫不掩饰的说,我没能珍惜我的大学时光。当等到大三之后,才开始思考自己该做什么,想要做什么。这是我个人的失败,这也是中国教育的失败之处:学生们总是高考之后才不得不思考自己将选择什么样的专业,大学毕业之后才开始思考起自己该选择什么样的工作,要到结婚的时候,才想起该找一个什么样的伴侣。不是说我们的教育培养不出人才,而是培养不出有着独立思考能力和理想追去的人才。
我从零基础自学了计算机知识。为什么要选择程序员这个工作?坦白说,我最初的想法也谈不上出于喜好,而只是觉得自己更适合伏案工作,倾向于从事一个人就可以专注的事情。计算机满足了我的这种要求,与社交相关的工作不太适合我。我一开始选择的是考计算机方向的研究生,在考研期间,我学习了大量的计算机底层原理。我看了好多原版的英文书,《Computer Systems: A Programmer's Perspective》, 难以置信,我一个普通本科专业的学渣,竟然啃完了1000页的纯英文书籍。一发不可收拾,我又继续看了《Operating System Comcepts》,《Computer Networking: A Top-down Approach》和《Introduce to Algorithm》...并且发誓不再碰任何中文的专业书籍,中文的计算机书太狗屎了。那段时间实在是人生中一段十分快乐的时光,从早上6点多起床看到晚上9点,完全沉浸在其中的世界,仅此我一个人,孤独又十分快乐。就这样,我的考研以失败而告终,如果我不看这些对考试帮助不大的书籍,把更多的时间分配在数学和刷题上,或许我会有个不错的考试结果。但我并不后悔,正是因为这些书,让我得以在后面的学习和工作中进步很快,它也让我找到了自己继续努力的方向--我喜欢底层的事物
所以就这样,在考研的过程中,发现了计算机底层一些有趣的东西。如今看来,这样的喜好与工作和赚钱之类的无关,只能算作是纯粹的个人小癖好,我要经营好这个小癖好,而且它也无利可图。而相比之下,工作是多么乏味的一件事,不论是Web开发还是别的,总是为老板打工,很难去做自己真正喜欢的事情。不管是编程,还是大部分人的所做的工作,都可能必须忍受着这种乏味。一方面,我喜欢编程和一些有趣的知识,这种激情只有当自己做喜欢的事情时;另一方面,我又不得不忍受着像拧螺丝钉一样重复着无聊的事情。叔本华说,“人能够做他想做的,但不能要他所要的”,人总是不自由的,因为总得为活着而奔波;但是如果不工作,乞讨或啃老,像寄生虫一样指望别人养活,那就更不自由了!难怪马克思要说人的本质是劳动,我深以为然。
### 3. 我最崇拜的人

[Donald Knuth][1] 就像黑暗中的星星一样,指引我所前进的方向。令人喜欢的不仅是他的艺术品,而是他的性格和他的思想。诸多伟大的人,他们在自己的领域开疆拓土,更重要的是富有魅力的人格和思想也在并驾齐驱。我钦佩老爷子的灵魂。
Donald Knuth 他老人家并不知晓,我是他的一个小小小中国粉丝。而且我同样也开始的太晚了,很可能做不成什么,庸庸碌碌就这样结束一辈子。但是人总有自己喜欢的事情,去尽心尽力的做好就足够了。毕竟人生本就是虚无,所以要找些事情自娱自乐,聊以自慰。
### 4. 我喜欢的文章和书
我的世界观和思想,来源与自身的经历和也来源于读书。分享自己喜欢的一些文章,我必须时时反复的读它们,让自己保持清醒。
哲学与人生:
- [What I belive][b1]-- Albert Einstein, published in "Forum and Century," vol. 84, pp. 193-194
- [人是一棵思想的芦苇][b2] --《思想录》,布莱兹·帕斯卡尔
- [论祖传][b3] -- 《昆虫记》,法布尔
- [论自立(Self-reliance)][b4] -- 拉尔夫·沃尔多·爱默生
- 两篇:真性情,亲自然 -- 《人生哲思录》,周国平
- [工作与人生][b5] -- 王小波
- [我生活的目的,我生活的意义][b6] -- 《瓦尔登湖》,梭罗
- [逝去(Passing)][b7] -- 《RWBY》导演MontyOum
- [永不知足,我行我素(Stay Hungry,Stay Foolish)][b8] -- 史蒂夫·乔布斯
- [拉里·佩奇在密歇根大学的演讲][b9] -- 拉里·佩奇
- [沉默的大多数·序言][b10] -- 王小波
计算机:
- [作为艺术的计算机编程(Computer programming as an art)][c0]
-- ACM通讯,Donald Knuth
- [喜鹊开发者(The Magpie Developer)][c1] \
-- StackOverflow创始人, Jeff Atwood
- [Teach Yourself Programming in Ten Years][c2]
-- 美国计算机科学家, Peter Norvig
我们总是能够面对问题。
我们会侦破这起悬案的,
因为我们能够理出头绪,找到办法。
--赫尔克里·波洛,《东方快车谋杀案》(1934)
---
写于:2016-6月
更新: 2018-06-26
[1]: https://en.wikipedia.org/wiki/Donald_Knuth
[2]: https://www.cnblogs.com/crb912/
[b1]: https://history.aip.org/exhibits/einstein/essay.htm
[b2]: https://www.douban.com/group/topic/56237703/
[b3]: http://www.99lib.net/book/550/17508.htm
[b4]: https://www.douban.com/group/topic/85627257/
[b5]: https://wenku.baidu.com/view/71781862f5335a8102d2205e.html
[b6]: http://www.docin.com/p-401918679.html
[b7]: http://montyoum.net/archives/602
[b8]: https://wenku.baidu.com/view/67fc2fb5f121dd36a32d82e6.html
[b9]: https://wenku.baidu.com/view/2066fb34ee06eff9aef807a6.html
[b10]: http://wangxiaobo.zuopinj.com/3087/116359.html
[c0]: https://dl.acm.org/citation.cfm?id=361612
[c1]: https://www.tuicool.com/articles/QRZ7j2Y
[c2]: http://www.cnblogs.com/kaneboy/archive/2004/02/28/2436733.html
|
crb912/blog
|
_posts/2016-06-01-My-First-Post.md
|
Markdown
|
mit
| 7,220
|
<?php
namespace ATManager\BackendBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use ATManager\BackendBundle\Entity\EstadioClasif;
use ATManager\BackendBundle\Form\EstadioClasifType;
class EstadioClasifController extends Controller
{
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('BackendBundle:EstadioClasif')->findAll();
return $this->render('BackendBundle:EstadioClasif:index.html.twig', array(
'entities' => $entities,
));
}
public function newAction()
{
$entity = new EstadioClasif();
$form = $this->createForm(new EstadioClasifType(), $entity);
$form->handleRequest($this->getRequest());
if ($form->isValid())
{
try{
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$this->get('session')->getFlashBag()->add('success','Item Guardado');
return $this->redirect($this->generateUrl('estadioclasif_show', array('id' => $entity->getId())));
}
catch(\Exception $e){
$this->get('session')->getFlashBag()->add('error','Error al intentar agregar item');
// return $this->redirect($this->generateUrl('estadioclasif_new'));
}
}
return $this->render('BackendBundle:EstadioClasif:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BackendBundle:EstadioClasif')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find EstadioClasif entity.');
}
return $this->render('BackendBundle:EstadioClasif:show.html.twig', array(
'entity' => $entity,
));
}
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BackendBundle:EstadioClasif')->find($id);
$editForm = $this->createForm(new EstadioClasifType(), $entity);
$editForm->handleRequest($this->getRequest());
if ($editForm->isValid()) {
try{
$em->persist($entity);
$em->flush();
$this->get('session')->getFlashBag()->add('success','Item actualizado');
return $this->redirect($this->generateUrl('estadioclasif_edit', array('id' => $id)));
}
catch(\Exception $e){
$this->get('session')->getFlashBag()->add('error','Error al intentar actualizar item');
// return $this->redirect($this->generateUrl('estadioclasif_edit', array('id' => $id)));
}
}
return $this->render('BackendBundle:EstadioClasif:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView()
));
}
public function eliminarAction($id)
{
try{
$em = $this->getDoctrine()->getManager();
$objec = $em->getRepository('BackendBundle:EstadioClasif')->find($id);
$em->remove($objec);
$em->flush();
$this->get('session')->getFlashBag()->add('success','Item Eliminado');
return $this->redirect($this->generateUrl('estadioclasif'));
}
catch(\Exception $e) {
$this->get('session')->getFlashBag()->add('error','Error al intentar eliminar item');
return $this->redirect($this->generateUrl('estadioclasif'));
}
}
}
|
atmanager/atmanager
|
src/ATManager/BackendBundle/Controller/EstadioClasifController.php
|
PHP
|
mit
| 3,732
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Graph.RBAC.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Graph.RBAC.Fluent.Models;
using Microsoft.Azure.Management.Graph.RBAC.Fluent.RoleAssignment.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
public partial class RoleAssignmentImpl
{
/// <summary>
/// Gets the role assignment scope.
/// </summary>
string Microsoft.Azure.Management.Graph.RBAC.Fluent.IRoleAssignment.Scope
{
get
{
return this.Scope();
}
}
/// <summary>
/// Gets the principal ID.
/// </summary>
string Microsoft.Azure.Management.Graph.RBAC.Fluent.IRoleAssignment.PrincipalId
{
get
{
return this.PrincipalId();
}
}
/// <summary>
/// Gets the role definition ID.
/// </summary>
string Microsoft.Azure.Management.Graph.RBAC.Fluent.IRoleAssignment.RoleDefinitionId
{
get
{
return this.RoleDefinitionId();
}
}
/// <summary>
/// Specifies the assignee of the role assignment to be a service principal.
/// </summary>
/// <param name="servicePrincipal">The service principal object.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithRole RoleAssignment.Definition.IWithAssignee.ForServicePrincipal(IServicePrincipal servicePrincipal)
{
return this.ForServicePrincipal(servicePrincipal);
}
/// <summary>
/// Specifies the assignee of the role assignment to be a service principal.
/// </summary>
/// <param name="servicePrincipalName">The service principal name.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithRole RoleAssignment.Definition.IWithAssignee.ForServicePrincipal(string servicePrincipalName)
{
return this.ForServicePrincipal(servicePrincipalName);
}
/// <summary>
/// Specifies the assignee of the role assignment to be a user.
/// </summary>
/// <param name="user">The user object.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithRole RoleAssignment.Definition.IWithAssignee.ForUser(IActiveDirectoryUser user)
{
return this.ForUser(user);
}
/// <summary>
/// Specifies the assignee of the role assignment to be a user.
/// </summary>
/// <param name="name">The user's user principal name, full display name, or email address.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithRole RoleAssignment.Definition.IWithAssignee.ForUser(string name)
{
return this.ForUser(name);
}
/// <summary>
/// Specifies the assignee of the role assignment to be a group.
/// </summary>
/// <param name="activeDirectoryGroup">The user group.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithRole RoleAssignment.Definition.IWithAssignee.ForGroup(IActiveDirectoryGroup activeDirectoryGroup)
{
return this.ForGroup(activeDirectoryGroup);
}
/// <summary>
/// Specifies the assignee of the role assignment.
/// </summary>
/// <param name="objectId">The object ID of an Active Directory identity.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithRole RoleAssignment.Definition.IWithAssignee.ForObjectId(string objectId)
{
return this.ForObjectId(objectId);
}
/// <summary>
/// Specifies the name of a built in role for this assignment.
/// </summary>
/// <param name="role">The name of the role.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithScope RoleAssignment.Definition.IWithRole.WithBuiltInRole(BuiltInRole role)
{
return this.WithBuiltInRole(role);
}
/// <summary>
/// Specifies the ID of the custom role for this assignment.
/// </summary>
/// <param name="roleDefinitionId">ID of the custom role definition.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithScope RoleAssignment.Definition.IWithRole.WithRoleDefinition(string roleDefinitionId)
{
return this.WithRoleDefinition(roleDefinitionId);
}
/// <summary>
/// Specifies the scope of the role assignment to be a resource group.
/// </summary>
/// <param name="resourceGroup">The resource group the assignee is assigned to access.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithCreate RoleAssignment.Definition.IWithScope.WithResourceGroupScope(IResourceGroup resourceGroup)
{
return this.WithResourceGroupScope(resourceGroup);
}
/// <summary>
/// Specifies the scope of the role assignment to be a specific resource.
/// </summary>
/// <param name="resource">The resource the assignee is assigned to access.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithCreate RoleAssignment.Definition.IWithScope.WithResourceScope(IResource resource)
{
return this.WithResourceScope(resource);
}
/// <summary>
/// Specifies the scope of the role assignment to be an entire subscription.
/// </summary>
/// <param name="subscriptionId">The subscription the assignee is assigned to access.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithCreate RoleAssignment.Definition.IWithScope.WithSubscriptionScope(string subscriptionId)
{
return this.WithSubscriptionScope(subscriptionId);
}
/// <summary>
/// Specifies the scope of the role assignment. The scope is usually the ID of
/// a subscription, a resource group, a resource, etc.
/// </summary>
/// <param name="scope">The scope of the assignment.</param>
/// <return>The next stage in role assignment definition.</return>
RoleAssignment.Definition.IWithCreate RoleAssignment.Definition.IWithScope.WithScope(string scope)
{
return this.WithScope(scope);
}
}
}
|
hovsepm/azure-libraries-for-net
|
src/ResourceManagement/Graph.RBAC/Domain/InterfaceImpl/RoleAssignmentImpl.cs
|
C#
|
mit
| 7,241
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.