code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
require_relative '../../../spec_helper'
require 'matrix'
describe "Vector#normalize" do
it "returns a normalized copy of the vector" do
x = 0.2672612419124244
Vector[1, 2, 3].normalize.should == Vector[x, x * 2, x * 3]
end
it "raises an error for zero vectors" do
lambda {
Vector[].normalize
}.should raise_error(Vector::ZeroVectorError)
lambda {
Vector[0, 0, 0].normalize
}.should raise_error(Vector::ZeroVectorError)
end
end
| ruby/rubyspec | library/matrix/vector/normalize_spec.rb | Ruby | mit | 473 |
'use strict';
/**
* Module dependencies.
*/
var users = require('../../app/controllers/users'),
goaliedash = require('../../app/controllers/goaliedash');
module.exports = function(app) {
app.route('/goaliedash')
.get(users.requiresLogin, users.hasAuthorization);
}; | thcmc/412hockey | app/routes/goaliedash.server.routes.js | JavaScript | mit | 275 |
// @flow
import React from 'react'
import withPropsStream from '@vega/utils/withPropsStream'
import {map} from 'rxjs/operators'
import styles from './styles/Communicator.css'
import ThreadList from './ThreadList'
import CreateComment from './CreateComment'
function getPropsStream(props$) {
// todo: implement open/close behavior
return props$.pipe(map(props => ({...props, isOpen: true})))
}
type Props = {
isOpen: boolean,
subjectIds: string[],
focusedCommentId: string
}
export default withPropsStream(
getPropsStream,
class Communicator extends React.Component<Props> {
state = {
createCommentIsSticky: false
}
handleCloseCreateComment = event => {
this.setState({
createCommentIsSticky: false
})
event.stopPropagation()
}
handleStickCreateComment = () => {
this.setState({
createCommentIsSticky: true
})
}
render() {
const {isOpen, subjectIds, focusedCommentId} = this.props
const {createCommentIsSticky} = this.state
return isOpen ? (
<div className={styles.root}>
<div
className={
createCommentIsSticky
? styles.feedWithWithStickyCreateComment
: styles.feed
}
>
<ThreadList
subjectId={subjectIds}
focusedCommentId={focusedCommentId}
/>
</div>
{subjectIds.length === 1 && (
<CreateComment
subjectId={subjectIds[0]}
showCloseButton={createCommentIsSticky}
className={
createCommentIsSticky
? styles.createCommentSticky
: styles.createComment
}
onClose={this.handleCloseCreateComment}
onSubmit={this.handleCloseCreateComment}
onClick={this.handleStickCreateComment}
/>
)}
</div>
) : null
}
}
)
| VegaPublish/vega-studio | packages/@vega/communicator-system/src/components/providers/Communicator.js | JavaScript | mit | 1,991 |
# ember-promise-block
This is an Ember Addon that exposes a component `promise-block` which shows a loader while a given promise is being resolved.
## Installing
Install as an Ember-CLI addon:
ember install ember-promise-block
## Usage
// templates/posts.hbs
{{#promise-block promise=postsPromise loaderTemplate='helpers/loader'}}
{{#each posts as |post|}}
{{post.title}}
{{/each}}
{{/promise-block}}
The component will show the partial in `loaderTemplate` while `promise` is not resolved. It then shows the block when it resolves. The default value for `loaderTemplate` is `helpers/loader`.
Example controller:
// controllers/posts.js
import Ember from 'ember';
export default Ember.Controller.extend({
postsPromise: function() {
return this.get('store').query('post');
}.property(),
posts: Ember.computed.reads('postsPromise.content')
});
Example model:
// models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string')
});
## Example
Below is a (fast) example of what the addon does. The loader is displayed until the data is loaded, i.e. the Promise gets resolved.

## Building yourself
* `git clone` this repository
* `npm install`
* `bower install`
## Running Tests
* `npm test` (Runs `ember try:testall` to test your addon against multiple Ember versions)
* `ember test`
* `ember test --server`
| Hstry/ember-promise-block | README.md | Markdown | mit | 1,597 |
package pricing;
import org.configureme.ConfigurationManager;
import org.configureme.Environment;
import org.configureme.GlobalEnvironment;
import org.configureme.environments.DynamicEnvironment;
public class ShowPrice {
public static void main(String a[]){
showPrice();
showPriceIn("USA", GlobalEnvironment.INSTANCE);
showPriceIn("United Kingdom", new DynamicEnvironment("europe", "uk"));
showPriceIn("Germany", new DynamicEnvironment("europe", "de"));
showPriceIn("Austria", new DynamicEnvironment("europe", "at"));
}
private static void showPriceIn(String description, Environment environment){
Pricing pricing = new Pricing();
ConfigurationManager.INSTANCE.configure(pricing, environment);
System.out.println("Price in "+description+" is "+pricing.getProductPrice());
}
private static void showPrice(){
Pricing pricing = new Pricing();
ConfigurationManager.INSTANCE.configure(pricing);
System.out.println("Please pay "+pricing.getProductPrice());
}
}
| anotheria/configureme | src/examples/pricing/ShowPrice.java | Java | mit | 989 |
## Part 3
[](https://rawgit.com/Bogdan-Lyashenko/Under-the-hood-ReactJS/master/stack/images/3/part-3.svg)
<em>3.0 第 3 部分 (点击查看大图)</em>
### 挂载
`componentMount` 是我们整个系列中极其重要的一个板块。如图,我们关注 `ReactCompositeComponent.mountComponent` (1) 方法
如果你还记得,我曾提到过 **组件树的入口组件** 是 `TopLevelWrapper` 组件 (React 底层内部类)。我们准备挂载它。由于它实际上是一个空的包装器,调试起来非常枯燥并且对实际的流程而言没有任何影响,所以我们跳过这个组件从他的孩子组件开始分析。
把组件挂载到组件树上的过程就是先挂载父亲组件,然后他的孩子组件,然后他的孩子的孩子组件,依次类推。可以肯定,当 `TopLevelWrapper` 挂载后,他的孩子组件 (用来管理 `ExampleApplication` 的组件 `ReactCompositeComponent`) 也会在同一阶段注入.
现在我们回到步骤 (1) 观察这个方法的内部实现,有一些重要行为会发生,接下来让我们深入研究这些重要行为。
### 构造 instance 和 updater
从 `transaction.getUpdateQueue()` 结果返回的步骤 (2) 方法 `updater` 实际上就是 `ReactUpdateQueue` 模块。 那么为什么需要在这里构造它呢?因为我们正在研究的类 `ReactCompositeComponent` 是一个全平台的共用的类,但是 `updater` 却依赖于平台环境而不尽相同,所以我们在这里根据不同的平台动态的构造它。
然而,我们现在并不马上需要这个 `updater` ,但是你要记住它是非常重要的,因为它很快就会应用于非常知名的组件内更新方法 **`setState`**。
事实上在这个过程中,不仅仅 `updater` 被构造,组件实例(你的自定义组件)也获得了继承的 `props`, `context`, 和 `refs`.
我们来看下面的代码:
```javascript
// \src\renderers\shared\stack\reconciler\ReactCompositeComponent.js#255
// These should be set up in the constructor, but as a convenience for
// simpler class abstractions, we set them up after the fact.
inst.props = publicProps;
inst.context = publicContext;
inst.refs = emptyObject;
inst.updater = updateQueue;
```
因此,你才可以通过一个实例从你的代码中获得 `props`,比如 `this.props`。
### 创建 ExampleApplication 实例
通过调用步骤 (3) 的方法 `_constructComponent` 然后经过几个构造方法的作用后,最终创建了 `new ExampleApplication()`。这就是我们代码中构造方法第一次被执行的时机,当然也是我们的代码第一次实际接触到 React 的生态系统,很棒。
### 执行首次挂载
接着我们研究步骤 (4),第一个即将发生的行为是 `componentWillMount`(当然仅当它被定义时) 的调用。这是我们遇到的第一个生命周期钩子函数。当然,在下面一点你会看到 `componentDidMount` 函数, 只不过这时由于它不能马上执行,而是被注入了一个事务队列中,在很后面执行。他会在挂载系列操作执行完毕后执行。当然你也可能在 `componentWillMount` 内部调用 `setState`,在这种情况下 `state` 会被重新计算但此时不会调用 `render`。(这是合理的,因为这时候组件还没有被挂载)
官方文档的解释也证明这一点:
> `componentWillMount()` 在挂载执行之前执行,他会在 `render()` 之前被调用,因此在这个过程中设置组件状态不会触发重绘。
观察以下的代码
```javascript
// \src\renderers\shared\stack\reconciler\ReactCompositeComponent.js#476
if (inst.componentWillMount) {
//..
inst.componentWillMount();
// 当挂载时, 在 `componentWillMount` 中调用的 `setState` 会执行并改变状态
// `this._pendingStateQueue` 不会触发重渲染
if (this._pendingStateQueue) {
inst.state = this._processPendingState(inst.props, inst.context);
}
}
```
确实如此,但是当 state 被重新计算完成后,会调用我们在组件中申明的 render 方法。再一次接触 “我们的” 代码。
接下来下一步就会创建 React 的组件实例。然后呢?我们已经看见过步骤 (5) `this._instantiateReactComponent` 的调用了,对吗?是的。在那个时候它为我们的 `ExampleApplication` 组件实例化了 `ReactCompositeComponent` ,现在我们准备基于它的 `render` 方法获得的元素作为它的孩子创建 VDOM (虚拟 DOM) 实例,当该实例被创建后,我们会再次调用 `ReactReconciler.mountComponent` ,但是这次我们传入刚刚新创建的 `ReactDOMComponent` 实例 作为`internalInstance` 。
然后继续调用此类中的 `mountComponent` 方法,这样递归往下..
### 好,**第 3 部分**我们讲完了
我们来回顾一下我们学到的。我们再看一下这种模式,然后去掉冗余的部分:
[](https://rawgit.com/Bogdan-Lyashenko/Under-the-hood-ReactJS/master/stack/images/3/part-3-A.svg)
<em>3.1 第 3 部分简化版 (点击查看大图)</em>
让我们适度在调整一下:
[](https://rawgit.com/Bogdan-Lyashenko/Under-the-hood-ReactJS/master/stack/images/3/part-3-B.svg)
<em>3.2 第 3 部分简化和重构 (点击查看大图)</em>
很好,实际上,下面的示意图就是我们所讲的。因此,我们可以理解**第 3 部分**的本质,并将其用于最终的 `mount` 方案::
[](https://rawgit.com/Bogdan-Lyashenko/Under-the-hood-ReactJS/master/stack/images/3/part-3-C.svg)
<em>3.3 第 3 部分本质 (点击查看大图)</em>
完成!
[下一节: 第 4 部分 >>](./Part-4.md)
[<< 上一节: 第 0 部分](./Part-2.md)
[主页](../../README.md)
| blizzardzheng/Under-the-hood-ReactJS | stack/book/Part-3.md | Markdown | mit | 6,096 |
## Release 1.1.0
## Breaking Changes
* removed cross-spawn dependency
### Features
- ([fc25d5e](https://github.com/igniteram/protractor-cli/commit/fc25d5edc09d775f35e356796c19e0425fc936d2))
feat(install modules): added npm progress & async installation
## Release 1.0.1
### Features
- ([7441967](https://github.com/igniteram/protractor-cli/commit/7441967b1ec32e4718a656956c4573fd6245aa7a))
build(commitizen): Added commitizen to the project
### Fixes
- ([bb5c6b8](https://github.com/igniteram/protractor-cli/commit/bb5c6b8c837f146c2934d2dc726a5e72f8980c4b))
chore(release):updated package version to 1.0.1 (#23)
## Release 1.0.0
## Breaking Changes
- ([30e1a43](https://github.com/igniteram/protractor-cli/commit/30e1a4336e7a5ec0d55a3458d7452476d5d4683c))
chore(docs):update readme (#19)
* Changed the project name to **protractor-cli**
* Updated readme with protracto-cli info
* Moved the spec files to test folder
- ([a49828e](https://github.com/igniteram/protractor-cli/commit/a49828e065355041aa945e206d43162afcd77f3a))
chore(release):updated package name to protractor-cli (#22)
* chore(release):updated package name to protractor-cli
* chore(release):removed tslint from npmignore
### Features
- ([722f9ba](https://github.com/igniteram/protractor-cli/commit/722f9baa1a3e3f40ec1dd51d1557914357edfac5))
chore(modules): added yarn for better package management (#15)
- ([0c97bb5](https://github.com/igniteram/protractor-cli/commit/0c97bb5666664d0a56c73c789c3bf673b47b8776))
chore(modules): add linters option to cli (#13)
* Added eslint-plugin-protractor & tslint options to cli
* Updated all dependencies
- ([84859ba](https://github.com/igniteram/protractor-cli/commit/84859ba90e34cb11e3767f0ed744870c65d278ae))
chore(modules):update deprecated coffee-script module (#18)
* chore(modules):update deprecated coffee-script module
* updated coffee-script to new coffeescript module
* chore(tests):fix unit tests for coffeescript
- ([c761e6c](https://github.com/igniteram/protractor-cli/commit/c761e6c7540effb5d7994b1d4780e75cdacb413d))
chore(loglevel):replace previous loglevel to config interface (#17)
* protractor's new changes support loglevel in config file
* added loglevel option in config ejs file
### Fixes
- ([90d98e3](https://github.com/igniteram/protractor-cli/commit/90d98e3037f8a8a6707ea6a3b6e730c51e6e6738))
chore(release):updated package.json to 1.0 version (#21)
* chore(docs):updated badge links in readme
* chore(release):updated package.json to 1.0 version
- ([d5509ff](https://github.com/igniteram/protractor-cli/commit/d5509ff3f594e15ec63a09b0f431b5942c6aa3ee))
chore(docs):updated badge links in readme (#20)
- ([da30e17](https://github.com/igniteram/protractor-cli/commit/da30e17ffdee0cae998776978aa9f25b8376c93f))
bug(template):fixed cucumber custom framework config (#16)
* Added the custom framework option for cucumber
* Upgraded the cross-spawn to 6.x
- ([722f9ba](https://github.com/igniteram/protractor-cli/commit/722f9baa1a3e3f40ec1dd51d1557914357edfac5))
chore(modules): added yarn for better package management (#15)
- ([63b64a0](https://github.com/igniteram/protractor-cli/commit/63b64a00cc1b5f6de66ed58ff6e48058805cc7f8))
Chore(cleanup): Updated license & moduleHelper spec file (#12)
* chore(license): updated license year & version
* chore(cleanup_specs): Added removeDevModules function in moduleHelper spec
- ([05e0874](https://github.com/igniteram/protractor-cli/commit/05e0874343d85cbc8d31f4a69174f6a76efbf260))
chore(cleanup modules):move all modules to dev dependencies (#10)
* chore(cleanup modules):move all modules to dev dependencies
## Release 0.2.1
### Fixes
- ([05e0874](https://github.com/igniteram/protractor-cli/commit/05e0874343d85cbc8d31f4a69174f6a76efbf260))
chore(cleanup modules):move all modules to dev dependencies (#10)
* chore(cleanup modules):move all modules to dev dependencies
* Removed save dependency installation.
* Added unit test for module helper
* Bumped to version to 0.2.0
* updated circle.yml
| igniteram/Cliptor.js | CHANGELOG.md | Markdown | mit | 4,128 |
local d = require "distribution"
d6 = d.uniform(6)
d20 = d.uniform(20)
foo = 2*d6 + d20
-- The basic summary method gives a sorted list of all the outcomes
-- and a summary of statistical values
print("2d6 + d20")
print(foo:summary())
-- Note that tostring(foo) and print(foo) will automatically call summary
-- To check the content of the distribution you can use
-- the outcomes member, which is a table of probabilities
print("Outcomes")
for outcome,probability in pairs(foo.outcomes) do
print(outcome .. ": " .. probability * 100 .. "%")
end
print()
-- The method sorted_outcomes return a sorted list of pairs {outcome, probability}
-- If the outcomes' type is not number, the list is not sorted
print("Outcomes again")
for _,v in ipairs(foo:sorted_outcomes()) do
print(v[1] .. ": " .. v[2])
end
print()
-- The Cumulative Distribution Function of distribution D is the probability that D <= x
print("CDF")
for _,v in ipairs(foo:cdf()) do
print("foo <= " .. v[1] .. ": " .. v[2])
end
print()
-- You can also use the shortcut print_cdf
print("CDF again")
foo:print_cdf()
print()
-- Finally, individual statistical methods
print("Average", foo:average())
print("Standard deviation", foo:deviation())
print("Median", foo:median())
print("Median absolute deviation", foo:median_absolute_deviation())
-- And percentiles/quartiles/deciles/etc. via the nth_iles method
print("Thirds", table.concat(foo:nth_iles(3), ", "))
print("Quartiles", table.concat(foo:nth_iles(4), ", "))
print("Deciles", table.concat(foo:nth_iles(10), ", "))
print("Percentiles", table.concat(foo:nth_iles(100), ", ")) | Castux/distribution | examples/2. results.lua | Lua | mit | 1,616 |
/* Error handling */
#include "Python.h"
void
PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
{
PyThreadState *tstate = PyThreadState_GET();
PyObject *oldtype, *oldvalue, *oldtraceback;
/* Save these in locals to safeguard against recursive
invocation through Py_XDECREF */
oldtype = tstate->curexc_type;
oldvalue = tstate->curexc_value;
oldtraceback = tstate->curexc_traceback;
tstate->curexc_type = type;
tstate->curexc_value = value;
tstate->curexc_traceback = traceback;
Py_XDECREF(oldtype);
Py_XDECREF(oldvalue);
Py_XDECREF(oldtraceback);
}
void
PyErr_SetObject(PyObject *exception, PyObject *value)
{
Py_XINCREF(exception);
Py_XINCREF(value);
PyErr_Restore(exception, value, (PyObject *)NULL);
}
void
PyErr_SetNone(PyObject *exception)
{
PyErr_SetObject(exception, (PyObject *)NULL);
}
void
PyErr_SetString(PyObject *exception, const char *string)
{
PyObject *value = PyString_FromString(string);
PyErr_SetObject(exception, value);
Py_XDECREF(value);
}
PyObject *
PyErr_Occurred(void)
{
PyThreadState *tstate = PyThreadState_GET();
return tstate->curexc_type;
}
int
PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
{
if (err == NULL || exc == NULL) {
/* maybe caused by "import exceptions" that failed early on */
return 0;
}
if (PyTuple_Check(exc)) {
int i, n;
n = PyTuple_Size(exc);
for (i = 0; i < n; i++) {
/* Test recursively */
if (PyErr_GivenExceptionMatches(
err, PyTuple_GET_ITEM(exc, i)))
{
return 1;
}
}
return 0;
}
/* err might be an instance, so check its class. */
// if (PyInstance_Check(err))
// err = (PyObject*)((PyInstanceObject*)err)->in_class;
//if (PyClass_Check(err) && PyClass_Check(exc))
// return PyClass_IsSubclass(err, exc);
return err == exc;
}
int
PyErr_ExceptionMatches(PyObject *exc)
{
return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
}
/* Used in many places to normalize a raised exception, including in
eval_code2(), do_raise(), and PyErr_Print()
*/
void
PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
{
PyObject *type = *exc;
PyObject *value = *val;
PyObject *inclass = NULL;
PyObject *initial_tb = NULL;
if (type == NULL) {
/* There was no exception, so nothing to do. */
return;
}
/* If PyErr_SetNone() was used, the value will have been actually
set to NULL.
*/
if (!value) {
value = Py_None;
Py_INCREF(value);
}
if (PyInstance_Check(value))
inclass = (PyObject*)((PyInstanceObject*)value)->in_class;
/* Normalize the exception so that if the type is a class, the
value will be an instance.
*/
if (PyClass_Check(type)) {
/* if the value was not an instance, or is not an instance
whose class is (or is derived from) type, then use the
value as an argument to instantiation of the type
class.
*/
if (!inclass || !PyClass_IsSubclass(inclass, type)) {
PyObject *args, *res;
if (value == Py_None)
args = Py_BuildValue("()");
else if (PyTuple_Check(value)) {
Py_INCREF(value);
args = value;
}
else
args = Py_BuildValue("(O)", value);
if (args == NULL)
goto finally;
res = PyEval_CallObject(type, args);
Py_DECREF(args);
if (res == NULL)
goto finally;
Py_DECREF(value);
value = res;
}
/* if the class of the instance doesn't exactly match the
class of the type, believe the instance
*/
else if (inclass != type) {
Py_DECREF(type);
type = inclass;
Py_INCREF(type);
}
}
*exc = type;
*val = value;
return;
finally:
Py_DECREF(type);
Py_DECREF(value);
/* If the new exception doesn't set a traceback and the old
exception had a traceback, use the old traceback for the
new exception. It's better than nothing.
*/
initial_tb = *tb;
PyErr_Fetch(exc, val, tb);
if (initial_tb != NULL) {
if (*tb == NULL)
*tb = initial_tb;
else
Py_DECREF(initial_tb);
}
/* normalize recursively */
PyErr_NormalizeException(exc, val, tb);
}
void
PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
{
PyThreadState *tstate = PyThreadState_Get();
*p_type = tstate->curexc_type;
*p_value = tstate->curexc_value;
*p_traceback = tstate->curexc_traceback;
tstate->curexc_type = NULL;
tstate->curexc_value = NULL;
tstate->curexc_traceback = NULL;
}
void
PyErr_Clear(void)
{
PyErr_Restore(NULL, NULL, NULL);
}
/* Convenience functions to set a type error exception and return 0 */
int
PyErr_BadArgument(void)
{
PyErr_SetString(PyExc_TypeError,
"bad argument type for built-in operation");
return 0;
}
PyObject *
PyErr_NoMemory(void)
{
if (PyErr_ExceptionMatches(PyExc_MemoryError))
/* already current */
return NULL;
/* raise the pre-allocated instance if it still exists */
if (PyExc_MemoryErrorInst)
PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
else
/* this will probably fail since there's no memory and hee,
hee, we have to instantiate this class
*/
PyErr_SetNone(PyExc_MemoryError);
return NULL;
}
/* ... */
void
_PyErr_BadInternalCall(char *filename, int lineno)
{
PyErr_Format(PyExc_SystemError,
"%s:%d: bad argument to internal function",
filename, lineno);
}
/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
export the entry point for existing object code: */
#undef PyErr_BadInternalCall
void
PyErr_BadInternalCall(void)
{
PyErr_Format(PyExc_SystemError,
"bad argument to internal function");
}
#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
PyObject *
PyErr_Format(PyObject *exception, const char *format, ...)
{
va_list vargs;
PyObject* string;
va_start(vargs, format);
string = PyString_FromFormatV(format, vargs);
PyErr_SetObject(exception, string);
Py_XDECREF(string);
va_end(vargs);
return NULL;
}
PyObject *
PyErr_NewException(char *name, PyObject *base, PyObject *dict)
{
char *dot;
PyObject *modulename = NULL;
PyObject *classname = NULL;
PyObject *mydict = NULL;
PyObject *bases = NULL;
PyObject *result = NULL;
dot = strrchr(name, '.');
if (dot == NULL) {
PyErr_SetString(PyExc_SystemError,
"PyErr_NewException: name must be module.class");
return NULL;
}
if (base == NULL)
base = PyExc_Exception;
if (!PyClass_Check(base)) {
/* Must be using string-based standard exceptions (-X) */
return PyString_FromString(name);
}
if (dict == NULL) {
dict = mydict = PyDict_New();
if (dict == NULL)
goto failure;
}
if (PyDict_GetItemString(dict, "__module__") == NULL) {
modulename = PyString_FromStringAndSize(name, (int)(dot-name));
if (modulename == NULL)
goto failure;
if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
goto failure;
}
classname = PyString_FromString(dot+1);
if (classname == NULL)
goto failure;
bases = Py_BuildValue("(O)", base);
if (bases == NULL)
goto failure;
result = PyClass_New(bases, dict, classname);
failure:
Py_XDECREF(bases);
Py_XDECREF(mydict);
Py_XDECREF(classname);
Py_XDECREF(modulename);
return result;
}
/* Call when an exception has occurred but there is no way for Python
to handle it. Examples: exception in __del__ or during GC. */
void
PyErr_WriteUnraisable(PyObject *obj)
{
printf("Unraisable Exception\n");
// PyObject *f, *t, *v, *tb;
// PyErr_Fetch(&t, &v, &tb);
// f = PySys_GetObject("stderr");
// if (f != NULL) {
// PyFile_WriteString("Exception ", f);
// if (t) {
// PyFile_WriteObject(t, f, Py_PRINT_RAW);
// if (v && v != Py_None) {
// PyFile_WriteString(": ", f);
// PyFile_WriteObject(v, f, 0);
// }
// }
// PyFile_WriteString(" in ", f);
// PyFile_WriteObject(obj, f, 0);
// PyFile_WriteString(" ignored\n", f);
// PyErr_Clear(); /* Just in case */
// }
// Py_XDECREF(t);
// Py_XDECREF(v);
// Py_XDECREF(tb);
}
extern PyObject *PyModule_GetWarningsModule();
/* Function to issue a warning message; may raise an exception. */
int
PyErr_Warn(PyObject *category, char *message)
{
PyObject *dict, *func = NULL;
PyObject *warnings_module = PyModule_GetWarningsModule();
if (warnings_module != NULL) {
dict = PyModule_GetDict(warnings_module);
func = PyDict_GetItemString(dict, "warn");
}
if (func == NULL) {
printf("warning: %s\n", message);
return 0;
}
else {
PyObject *args, *res;
if (category == NULL)
category = PyExc_RuntimeWarning;
args = Py_BuildValue("(sO)", message, category);
if (args == NULL)
return -1;
res = PyEval_CallObject(func, args);
Py_DECREF(args);
if (res == NULL)
return -1;
Py_DECREF(res);
return 0;
}
}
| jtauber/cleese | necco/python/Python/errors.c | C | mit | 8,613 |
/*
* Copyright (c) 2014-2022 The Voxie Authors
*
* 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.
*/
#pragma once
#include <VoxieBackend/VoxieBackend.hpp>
#include <VoxieBackend/Data/Data.hpp>
#include <VoxieClient/ObjectExport/Client.hpp>
#include <VoxieClient/ObjectExport/ExportedObject.hpp>
#include <QtCore/QPointer>
#include <QtDBus/QDBusAbstractAdaptor>
#include <QtDBus/QDBusObjectPath>
namespace vx {
class NodePrototype;
namespace io {
class Operation;
class RunFilterOperation;
} // namespace io
class Exception;
class ExternalOperationAdaptorImpl;
class VOXIEBACKEND_EXPORT ExternalOperation : public vx::RefCountedObject {
Q_OBJECT
REFCOUNTEDOBJ_DECL(ExternalOperation)
friend class ExternalOperationAdaptorImpl;
QPointer<vx::Client> client = nullptr;
QSharedPointer<vx::io::Operation> operation_;
protected:
// TODO: Get rid of this / replace it by operation()->isFinished()?
bool isFinished = false;
void checkClient();
virtual void cleanup();
public:
explicit ExternalOperation(
const QSharedPointer<vx::io::Operation>& operation);
~ExternalOperation() override;
QWeakPointer<QSharedPointer<ExternalOperation>> initialReference;
virtual QString action() = 0;
virtual QString name() = 0;
const QSharedPointer<vx::io::Operation>& operation() const {
return operation_;
}
bool isClaimed();
Q_SIGNALS:
void error(const vx::Exception& error);
// Emitted when the operation is claimed
void claimed();
};
// TODO: Should probably be moved to ExtensionImporter / ExtensionExporter
class ExternalOperationImportAdaptorImpl;
class VOXIEBACKEND_EXPORT ExternalOperationImport : public ExternalOperation {
Q_OBJECT
REFCOUNTEDOBJ_DECL(ExternalOperationImport)
friend class ExternalOperationImportAdaptorImpl;
QString filename_;
QMap<QString, QDBusVariant> properties_;
QString name_;
public:
explicit ExternalOperationImport(
const QSharedPointer<vx::io::Operation>& operation,
const QString& filename, const QMap<QString, QDBusVariant>& properties,
const QString& name);
~ExternalOperationImport() override;
QString action() override;
QString name() override;
const QString& filename() { return filename_; }
const QMap<QString, QDBusVariant>& properties() { return properties_; }
Q_SIGNALS:
void finished(const QSharedPointer<vx::Data>& data);
};
class ExternalOperationExportAdapterImpl;
class VOXIEBACKEND_EXPORT ExternalOperationExport : public ExternalOperation {
Q_OBJECT
REFCOUNTEDOBJ_DECL(ExternalOperationExport)
friend class ExternalOperationExportAdaptorImpl;
QString filename_;
QString name_;
QSharedPointer<vx::Data> data_;
public:
explicit ExternalOperationExport(
const QSharedPointer<vx::io::Operation>& operation,
const QString& filename, const QString& name,
const QSharedPointer<vx::Data>& data);
~ExternalOperationExport() override;
QString action() override;
QString name() override;
// TODO: data
const QString& filename() { return filename_; }
const QSharedPointer<vx::Data>& data() { return data_; }
Q_SIGNALS:
void finished();
};
} // namespace vx
| voxie-viewer/voxie | src/VoxieBackend/Component/ExternalOperation.hpp | C++ | mit | 4,192 |
var models = require('../models');
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
console.log(req.session);
res.render('layout');
});
module.exports = router; | NUSPartTime/NUSPartTime | routes/index.js | JavaScript | mit | 248 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>unicoq: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.1 / unicoq - 1.0.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
unicoq
<small>
1.0.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-02-24 17:13:48 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-24 17:13:48 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
authors: [ "Matthieu Sozeau <[email protected]>" "Beta Ziliani <[email protected]>" ]
dev-repo: "git+https://github.com/unicoq/unicoq.git"
homepage: "https://github.com/unicoq/unicoq"
bug-reports: "https://github.com/unicoq/unicoq/issues"
license: "MIT"
build: [
["coq_makefile" "-f" "Make" "-o" "Makefile"]
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Unicoq"]
depends: [
"ocaml"
"coq" {>= "8.5.0" & < "8.6~" & != "8.5.2~camlp4"}
]
synopsis: "An enhanced unification algorithm for Coq"
flags: light-uninstall
url {
src: "https://github.com/unicoq/unicoq/archive/v1.0.tar.gz"
checksum: "md5=3473aadc43e9fce82775fe3888347f93"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-unicoq.1.0.0 coq.8.7.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1).
The following dependencies couldn't be met:
- coq-unicoq -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-unicoq.1.0.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.06.1-2.0.5/released/8.7.1/unicoq/1.0.0.html | HTML | mit | 6,726 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `FromUtf8Error` struct in crate `collections`.">
<meta name="keywords" content="rust, rustlang, rust-lang, FromUtf8Error">
<title>collections::string::FromUtf8Error - Rust</title>
<link rel="stylesheet" type="text/css" href="../../main.css">
<link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<a href='../../collections/index.html'><img src='http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a>
<p class='location'><a href='../index.html'>collections</a>::<wbr><a href='index.html'>string</a></p><script>window.sidebarCurrent = {name: 'FromUtf8Error', ty: 'struct', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press 'S' to search, '?' for more options..."
type="search">
</div>
</form>
</nav>
<section id='main' class="content struct">
<h1 class='fqn'><span class='in-band'>Struct <a href='../index.html'>collections</a>::<wbr><a href='index.html'>string</a>::<wbr><a class='struct' href=''>FromUtf8Error</a><wbr><a class='stability Stable' title=''>Stable</a></span><span class='out-of-band'><span id='render-detail'>
<a id="collapse-all" href="#">[-]</a> <a id="expand-all" href="#">[+]</a>
</span><a id='src-26993' href='../../src/collections/string.rs.html#45-48'>[src]</a></span></h1>
<pre class='rust struct'>pub struct FromUtf8Error {
// some fields omitted
}</pre><div class='docblock'><p>A possible error value from the <code>String::from_utf8</code> function.</p>
</div><h2 id='methods'>Methods</h2><h3 class='impl'><a class='stability Unstable' title='Unstable'></a><code>impl <a class='struct' href='../../collections/string/struct.FromUtf8Error.html' title='collections::string::FromUtf8Error'>FromUtf8Error</a></code></h3><div class='impl-items'><h4 id='method.into_bytes' class='method'><a class='stability Stable' title='Stable'></a><code>fn <a href='#method.into_bytes' class='fnname'>into_bytes</a>(self) -> <a class='struct' href='../../collections/vec/struct.Vec.html' title='collections::vec::Vec'>Vec</a><<a href='../../core/primitive.u8.html'>u8</a>></code></h4>
<div class='docblock'><p>Consume this error, returning the bytes that were attempted to make a
<code>String</code> with.</p>
</div><h4 id='method.utf8_error' class='method'><a class='stability Stable' title='Stable'></a><code>fn <a href='#method.utf8_error' class='fnname'>utf8_error</a>(&self) -> <a class='enum' href='../../collections/str/enum.Utf8Error.html' title='collections::str::Utf8Error'>Utf8Error</a></code></h4>
<div class='docblock'><p>Access the underlying UTF8-error that was the cause of this error.</p>
</div></div><h2 id='implementations'>Trait Implementations</h2><h3 class='impl'><a class='stability Stable' title='Stable'></a><code>impl <a class='trait' href='../../collections/fmt/trait.Display.html' title='collections::fmt::Display'>Display</a> for <a class='struct' href='../../collections/string/struct.FromUtf8Error.html' title='collections::string::FromUtf8Error'>FromUtf8Error</a></code></h3><div class='impl-items'><h4 id='method.fmt' class='method'><a class='stability Stable' title='Stable'></a><code>fn <a href='#method.fmt' class='fnname'>fmt</a>(&self, f: &mut <a class='struct' href='../../collections/fmt/struct.Formatter.html' title='collections::fmt::Formatter'>Formatter</a>) -> <a class='type' href='../../collections/fmt/type.Result.html' title='collections::fmt::Result'>Result</a></code></h4>
</div><h3 class='impl'><a class='stability Stable' title='Stable'></a><code>impl <a class='trait' href='../../core/error/trait.Error.html' title='core::error::Error'>Error</a> for <a class='struct' href='../../collections/string/struct.FromUtf8Error.html' title='collections::string::FromUtf8Error'>FromUtf8Error</a></code></h3><div class='impl-items'><h4 id='method.description' class='method'><a class='stability Unstable' title='Unstable: the exact API of this trait may change'></a><code>fn <a href='#method.description' class='fnname'>description</a>(&self) -> &<a href='../primitive.str.html'>str</a></code></h4>
<h4 id='method.cause' class='tymethod'><a class='stability Unstable' title='Unstable: the exact API of this trait may change'></a><code>fn <a href='#tymethod.cause' class='fnname'>cause</a>(&self) -> <a class='enum' href='../../core/option/enum.Option.html' title='core::option::Option'>Option</a><&<a class='trait' href='../../core/error/trait.Error.html' title='core::error::Error'>Error</a>></code></h4>
</div><h3 id='derived_implementations'>Derived Implementations </h3><h3 class='impl'><a class='stability Stable' title='Stable'></a><code>impl <a class='trait' href='../../collections/fmt/trait.Debug.html' title='collections::fmt::Debug'>Debug</a> for <a class='struct' href='../../collections/string/struct.FromUtf8Error.html' title='collections::string::FromUtf8Error'>FromUtf8Error</a></code></h3><div class='impl-items'><h4 id='method.fmt' class='method'><a class='stability Stable' title='Stable'></a><code>fn <a href='#method.fmt' class='fnname'>fmt</a>(&self, __arg_0: &mut <a class='struct' href='../../collections/fmt/struct.Formatter.html' title='collections::fmt::Formatter'>Formatter</a>) -> <a class='type' href='../../collections/fmt/type.Result.html' title='collections::fmt::Result'>Result</a></code></h4>
</div></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div class="shortcuts">
<h1>Keyboard shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>typedef</code> (or
<code>tdef</code>).
</p>
</div>
</div>
<script>
window.rootPath = "../../";
window.currentCrate = "collections";
window.playgroundUrl = "http://play.rust-lang.org/";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script src="../../playpen.js"></script>
<script async src="../../search-index.js"></script>
</body>
</html> | ArcherSys/ArcherSys | Rust/share/doc/rust/html/collections/string/struct.FromUtf8Error.html | HTML | mit | 7,777 |
*
{
margin: 0;
padding: 0;
}
body
{
margin: 0;
padding: 0;
font: 12px Arial, Helvetica, sans-serif;
color: #333;
background: #fff url(images/bg_body.jpg) repeat-x;
}
img
{
border: none;
}
p
{
margin: 0;
padding: 8px 0;
}
a, object, a:focus
{
outline: none;
}
h1, h2, h3, h4
{
margin: 0;
padding: 0;
}
a
{
text-decoration: none;
}
a:hover
{
text-decoration: underline;
}
iframe
{
width: 464px;
height: 171px;
border: #aa9e87 solid 1px;
}
.actualidad
{
float: left;
width: 305px;
margin: 0 13px 0 0;
color: #0a72a9;
font-size: 11px;
position: relative;
}
.actualidad a
{
color: #0a72a9;
font-size: 14px;
}
.actualidad h4
{
margin: 0 0 4px 0;
}
.alignDcha
{
float: right;
position: relative;
right: -24px;
}
.ampliada
{
float: left;
padding: 0 0 14px 0;
}
.ampliada img
{
}
.anular
{
border: none;
background: #a1a1a1;
color: #fffefe;
font-size: 10px;
height: 17px;
line-height: 17px;
width: 114px;
cursor: hand;
cursor: pointer;
}
.ajuste
{
width: 1064px;
margin: 0 auto;
overflow: visible;
}
.ajusteCarrito
{
width: 656px;
margin: 0 auto;
overflow: hidden;
background: url(images/bg_carrito_int.jpg) no-repeat;
padding: 0 0 0 332px;
}
.ajusteContacto
{
width: 988px;
margin: 0 auto;
overflow: hidden;
padding: 17px 0;
}
.ajusteIndex
{
width: 965px;
margin: 0 auto;
overflow: hidden;
position: relative;
height: 214px;
padding: 0 0 0 23px;
}
.ajustePie
{
width: 988px;
margin: 0 auto;
overflow: hidden;
position: relative;
height: 249px;
}
.azulBold
{
color: #0a72a9;
font-weight: bold;
}
.banner
{
float: left;
padding: 11px 0;
}
.barraLisa
{
width: 100%;
background: #f2f2f2;
border-top: #adadad solid 1px;
border-bottom: #bbb solid 1px;
overflow: hidden;
padding: 10px 0 9px 0;
}
.barraLisa2
{
width: 100%;
background: #f2f2f2;
border-top: #adadad solid 1px;
border-bottom: #bbb solid 1px;
overflow: hidden;
}
.barraLisaInt
{
width: 988px;
margin: 0 auto;
overflow: hidden;
padding: 10px 0 9px 0;
background: url(images/bg_lisa2.gif) right top no-repeat;
}
.blanco, a.blanco
{
color: #fff;
}
.borde
{
border-bottom: #b2b2b2 solid 1px;
height: 3px;
overflow: hidden;
}
.bordeDcha
{
border-right: #505456 solid 1px;
}
.bqPortada
{
float: left;
width: 941px;
margin: 0 0 0 22px;
padding: 7px 0 10px 0;
}
.bordeGris
{
border-bottom: #bbb solid 1px;
padding: 11px 0;
float: left;
width: 100%;
margin: 0 0 15px 0;
}
.btCol2
{
width: 133px !important;
height: 24px;
color: #fff !important;
font-weight: bold;
border: none !important;
background: url(images/bt_col2.jpg) no-repeat !important;
font-size: 11px !important;
margin: 17px 0 0 0 !important;
line-height: 24px;
padding: 0 !important;
cursor: hand;
cursor: pointer;
}
.buscador
{
width: 798px;
margin: 0 0 0 19px;
overflow: hidden;
height: 32px;
background: url(images/bg_buscador.gif) 0px 16px no-repeat;
padding: 8px 0 0 162px;
}
.buscador input, .buscador select
{
float: left;
color: #999;
font: 13px Arial, Helvetica, sans-serif;
border: #e3e3e3 solid 1px;
background: #f8f8f8;
margin: 0 13px 0 0;
}
.buscador input
{
height: 16px;
padding: 2px 8px;
width: 289px;
}
.buscador select
{
height: 22px;
width: 305px;
}
.buscar
{
width: 69px !important;
height: 24px !important;
border: none !important;
background: url(images/buscar.jpg) no-repeat !important;
}
.cabeCarrito
{
float: left;
width: 676px;
height: 46px;
overflow: hidden;
text-align: right;
background: url(images/carrito.gif) 517px 0px no-repeat;
}
/*
.cabecera
{
width: 982px;
margin: 0 auto;
overflow: hidden;
background: url(images/bg_cabecera.jpg) 490px 45px no-repeat;
padding: 12px 0 0 6px;
height: 79px;
}
*/
.cabecera
{
width: 982px;
margin: 0 auto;
overflow: hidden;
background: url(images/bg_cabecera.png) 470px 10px no-repeat;
padding: 12px 0 0 6px;
height: 79px;
}
.cancelar
{
border: none !important;
background: url(images/bg_cancelar.jpg) no-repeat !important;
color: #fff !important;
font-size: 11px !important;
font-weight: bold;
height: 24px;
line-height: 24px;
width: 87px !important;
margin: 12px 16px 20px 0 !important;
padding: 0 !important;
cursor: hand;
cursor: pointer;
}
.carrito
{
width: 100%;
background: url(images/bg_carrito.jpg) repeat-x;
height: 111px;
overflow: hidden;
}
.carritoDcha
{
float: left;
width: 143px;
background: url(images/bg_carrito_dcha.gif) 9px 16px no-repeat;
padding: 38px 0 0 16px;
font-weight: bold;
font-size: 12px;
color: #044364;
}
.carritoDcha input
{
float: left;
width: 80px;
height: 24px;
background: url(images/comprar.gif) no-repeat;
margin: 6px 0 0 0;
border: none;
cursor: hand;
cursor: pointer;
}
.carritoScroll
{
float: left;
width: 476px;
height: 100px;
border-right: #bbb solid 1px;
border-left: #bbb solid 1px;
overflow-x: hidden;
overflow-y: auto;
padding: 11px 0 0 0;
font-size: 11px;
}
.carritoScroll table
{
border-top: #bbb solid 1px;
}
.carritoScroll td
{
margin: 0;
padding: 2px 0 2px 12px;
border-bottom: #bbb solid 1px;
}
.col1
{
float: left;
width: 478px;
padding: 12px 0 0 0;
}
.col2
{
float: left;
width: 306px;
padding: 12px 0 0 0;
}
.col2 h4
{
color: #044364;
font-size: 30px;
}
.col2 input
{
font-size: 13px;
color: #333;
background: #e9e9e9;
border: #ababab solid 1px;
width: 130px;
margin: 3px 0;
}
.col2 select
{
font-size: 13px;
color: #333;
background: #e9e9e9;
border: #ababab solid 1px;
width: 209px;
margin: 3px 0;
}
.contacto
{
float: left;
width: 422px;
padding: 0 65px 0 0;
font-size: 11px;
color: #666;
}
.contacto a
{
color: #f93;
font-weight: bold;
}
.contacto strong
{
color: #999;
}
.contacto input, .contacto select, .contacto textarea
{
font: 11px Arial, Helvetica, sans-serif;
color: #999;
border: #aaa solid 1px;
padding: 2px;
margin: 0 0 2px 0;
}
.contacto h3
{
color: #f93;
font-size: 26px;
font-family: "Trebuchet MS";
letter-spacing: -1px;
padding: 20px 0 5px 0;
}
.contContacto
{
float: left;
width: 975px;
background: url(images/bg_contacta.gif) repeat-y;
padding: 0 0 0 13px;
overflow: hidden;
}
.contTiendas
{
float: left;
width: 988px;
background: url(images/bg_tiendas.gif) repeat-y;
overflow: hidden;
}
.dcha
{
float: left;
width: 802px;
padding: 9px 0 12px 13px;
}
#dipro
{
position: absolute;
right: 0px;
top: 155px;
}
.direccion
{
float: left;
width: 148px;
padding: 25px 11px 0 13px;
}
.disponibilidad
{
float: left;
margin: 4px 4px 0 0;
}
.div1
{
float: left;
width: 448px;
height: 253px;
border-right: #bbb solid 1px;
margin: 0 0 0 27px;
padding: 7px 15px 0 0;
}
.div2
{
float: left;
width: 490px;
height: 253px;
overflow: hidden;
padding: 7px 0 0 0;
position: relative;
}
.enviar
{
color: #000 !important;
background: #eee;
font-size: 12px !important;
}
.fichaG
{
float: left;
width: 291px;
height: 140px;
background: #e5e5e5;
padding: 6px 6px 0 6px;
border: #d9d9d9 solid 1px;
margin: 0 13px 13px 0;
font-family: Tahoma, sans-serif;
color: #044364;
font-size: 11px;
position: relative;
}
.fichaG a
{
color: #044364;
font-size: 13px;
font-weight: bold;
}
.fichaG h4 a
{
text-transform:uppercase;
font-size:10px
}
.fichaG h4
{
padding: 4px 0 4px 0;
}
.fichaP
{
float: left;
width: 132px;
height: 193px;
border: #d9d9d9 solid 1px;
background: url(images/bg_ficha.jpg) bottom repeat-x;
margin: 0 13px 13px 0;
padding: 6px 6px 0 6px;
font-family: Tahoma, sans-serif;
color: #044364;
font-size: 11px;
}
.fichaP h4 a{font-size:10px!important;
text-transform:uppercase;}
.fichaP a
{
color: #044364;
font-size: 13px;
font-weight: bold;
float: left;
width: 100%;
margin: 4px 0;
}
.productos .fichaP
{
height: 207px;
padding: 4px 6px 0 6px;
margin: 0 13px 11px 0;
}
.fichaSlide
{
float: left;
width: 471px;
height: 214px;
overflow: hidden;
background: url(images/bg_ficha_slide.gif) bottom right no-repeat;
position: relative;
font-family: "Trebuchet MS";
}
.fichaSlide img
{
position: absolute;
left: 0px;
}
.fichaSlide table
{
position: absolute;
left: 211px;
width: 246px;
}
.flashContenedor
{
width: 100%;
background: url(images/bg_flash.jpg) repeat-x;
height: 214px;
overflow: hidden;
padding: 3px 0;
}
#flechaD
{
position: absolute;
left: 479px;
top: 123px;
background: url(images/flecha_dcha.gif) no-repeat;
width: 11px;
height: 22px;
}
#flechaD2
{
position: absolute;
left: 360px;
top: 1px;
background: url(images/flecha_dcha.gif) no-repeat;
width: 11px;
height: 22px;
}
#flechaD3
{
position: absolute;
left: 963px;
top: 46px;
width: 16px;
height: 114px;
border-left: #bbb solid 1px;
padding: 54px 0 0 6px;
}
#flechaD:hover, #flechaD2:hover
{
background: url(images/flecha_dcha_on.gif) no-repeat;
}
#flechaI
{
position: absolute;
left: 0px;
top: 123px;
background: url(images/flecha_izda.gif) no-repeat;
width: 11px;
height: 22px;
}
#flechaI2
{
position: absolute;
left: 337px;
top: 1px;
background: url(images/flecha_izda.gif) no-repeat;
width: 11px;
height: 22px;
}
#flechaI:hover, #flechaI2:hover
{
background: url(images/flecha_izda_on.gif) no-repeat;
}
#flechaI3
{
position: absolute;
left: 0px;
top: 46px;
width: 22px;
height: 114px;
border-right: #bbb solid 1px;
padding: 54px 0 0 0;
}
.flotante
{
background: #fff;
padding: 40px 60px;
}
.flotante h1
{
color: #044364;
border-bottom: #ccc solid 1px;
padding: 5px 0;
font-size: 28px;
margin: 10px 0;
}
.flotante ul
{
padding: 0;
margin: 5px 0 5px 35px;
}
.flotante strong
{
color: #ff9933;
font-size: 14px;
}
.flotante a
{
color: #ff9933;
font-weight: bold;
}
.fontSize20
{
font-size: 20px;
font-weight: bold;
}
.fontSize10
{
font-size: 10px;
}
.fontSize12
{
font-size: 12px;
}
.fontSize16
{
font-size: 16px;
}
.gastos
{
border: #ccc solid 1px;
border-collapse: collapse;
margin: 20px 0;
}
.gastos td
{
border: #ccc solid 1px;
border-collapse: collapse;
padding: 4px;
}
.gastos .cabe
{
background: #7e7a7a;
color: #fff;
font-weight: bold;
font-size: 14px;
}
.horario
{
float: left;
width: 146px;
border-right: #575656 solid 1px;
height: 161px;
padding: 25px 0 0 0;
}
.imageA
{
float: left;
padding: 6px;
border: #d9d9d9 solid 1px;
margin: 0 8px 0 0;
min-width: 140px;
min-height: 105px;
}
.imageA img
{
border: #d9d9d9 solid 1px;
/*width: 140px;*/
}
.imageG
{
border: #d9d9d9 solid 1px;
width: 140px;
height: 130px;
float: left;
margin: 0 11px 0 0;
}
.imageG a
{
margin: 0 !important;
}
.imageG img
{
width: 140px;
height: 130px;
}
.imageP
{
border: #b7b7b7 solid 1px;
border-bottom: #ff3900 solid 3px;
width: 130px;
height: 130px;
position: relative;
overflow: hidden;
}
.imageP img
{
position: absolute;
left: -5px;
top: -1px;
min-height: 130px;
}
.interior100
{
width: 100%;
height: 41px;
background: url(images/interior100.jpg) repeat-x;
overflow: hidden;
}
.interior100 h2
{
margin: 0;
padding: 0 0 0 11px;
line-height: 41px;
color: #999;
font-size: 26px;
letter-spacing: -1px;
}
.interiorCarrito
{
float: left;
width: 787px;
padding: 10px 0 16px 15px;
overflow: hidden;
position: relative;
background: url(images/bg_carrito2.gif) no-repeat;
margin: 29px 0 0 0;
}
.carritoVacio
{
float: left;
width: 787px;
padding: 10px 0 16px 15px;
overflow: hidden;
position: relative;
margin: 29px 0 0 0;
display: none;
}
.izda
{
float: left;
width: 171px;
}
.leerMas
{
position: absolute;
width: 54px;
height: 24px;
background: url(images/leer_mas.jpg) no-repeat;
left: 160px;
top: 100px;
}
.legales
{
position: absolute;
bottom: 8px;
left: 27px;
width: 782px;
height: 27px;
background: url(images/bg_legales.jpg) no-repeat;
text-align: center;
color: #999;
line-height: 25px;
}
.legales a
{
color: #999 !important;
}
.listado
{
float: left;
width: 220px;
border-top: #d9d9d9 solid 1px;
margin: 0 7px 10px 0;
}
.listado ul
{
margin: 0;
padding: 0;
}
.listado li
{
margin: 0;
padding: 0;
list-style: none;
}
.listado a
{
color: #0a72a9;
font-size: 11px;
font-weight: normal;
padding: 5px 0 4px 5px;
width: 215px;
border-bottom: #d9d9d9 solid 1px;
float: left;
}
.listado a:hover
{
color: #fff;
text-decoration: none;
background: #f93;
}
.logoInferior
{
float: left;
width: 158px;
border-right: #575656 solid 1px;
height: 141px;
padding: 25px 0 0 15px;
}
.menu
{
/*float: left;*/
width: 1064px;
margin: 0 auto;
height: 57px;
border-left: #bbb solid 1px;
}
.menu a
{
float: left;
height: 56px;
}
#m_0
{
width: 65px;
background: url(images/m_0.jpg) no-repeat;
}
#m_0:hover
{
background: url(images/m_0_on.jpg) no-repeat;
}
#m_1
{
width: 115px;
background: url(images/m_1.jpg) no-repeat;
}
#m_1:hover
{
background: url(images/m_1_on.jpg) no-repeat;
}
#m_2
{
width: 131px;
background: url(images/m_2.jpg) no-repeat;
}
#m_2:hover
{
background: url(images/m_2_on.jpg) no-repeat;
}
#m_3
{
/* width: 75px;*/
width:69px;
background: url(images/m_3.jpg) no-repeat;
}
#m_3:hover
{
background: url(images/m_3_on.jpg) no-repeat;
}
#m_4
{
/*width: 101px;*/
width:84px;
background: url(images/m_4.jpg) no-repeat;
}
#m_4:hover
{
background: url(images/m_4_on.jpg) no-repeat;
}
#m_5
{
/*width: 127px;*/
width: 139px;
background: url(images/m_5.jpg) no-repeat;
}
#m_5:hover
{
background: url(images/m_5_on.jpg) no-repeat;
}
#m_6
{
/*width: 137px;*/
width: 164px;
background: url(images/m_6.jpg) no-repeat;
}
#m_6:hover
{
background: url(images/m_6_on.jpg) no-repeat;
}
#m_7
{
/*width: 88px;*/
width: 90px;
background: url(images/m_7.jpg) no-repeat;
}
#m_7:hover
{
background: url(images/m_7_on.jpg) no-repeat;
}
#m_8
{
/*width: 80px;*/
width: 79px;
background: url(images/m_8.jpg) no-repeat;
}
#m_8:hover
{
background: url(images/m_8_on.jpg) no-repeat;
}
#m_9
{
/*width: 80px;*/
width: 75px;
background: url(images/m_9.jpg) no-repeat;
}
#m_9:hover
{
background: url(images/m_9_on.jpg) no-repeat;
}
#m_10
{
width: 101px;
background: url(images/m_10.jpg) no-repeat;
}
#m_10:hover
{
background: url(images/m_10_on.jpg) no-repeat;
}
#m_11
{
width: 84px;
background: url(images/m_11.jpg) no-repeat;
}
#m_11:hover
{
background: url(images/m_11_on.jpg) no-repeat;
}
.menu100
{
width: 100%;
background: url(images/bg_menu.gif) repeat-x;
}
.menuLateral
{
float: left;
width: 171px;
border: #bbb solid 1px;
border-top: none;
border-bottom: none;
background: #f2f2f2;
}
.menuLateral a
{
float: left;
width: 157px;
font-size: 11px;
color: #0a72a9;
padding: 9px 0 6px 14px;
border-bottom: #adadad solid 1px;
background: #f2f2f2;
}
.menuLateral a:hover
{
text-decoration: none;
background: #0a72a9;
color: #fff;
}
.miniaturas
{
float: left;
width: 100%;
padding: 10px 0;
}
.miniaturas img
{
float: left;
margin: 0 10px 10px 0;
border: #bbb solid 1px;
}
.negro14
{
color: #000;
font-size: 14px;
}
.nombre
{
height: 88px;
vertical-align: bottom;
color: #999;
font-size: 30px;
font-weight: bold;
line-height: 26px;
padding: 0 0 4px 0;
}
.nombre a
{
color: #999;
}
.nombre a:hover
{
text-decoration: none;
color: #0a72a9;
}
.noticias
{
float: left;
width: 468px;
padding: 0 25px 0 0;
font-size: 14px;
color: #666;
}
.noticias a
{
color: #f93;
font-weight: bold;
}
.noticias .pag
{
float: left;
width: 100%;
border-bottom: #bbb solid 1px;
background: #f2f2f2;
text-align: center;
height: 39px;
line-height: 39px;
color: #f93;
font-weight: bold;
}
.noticias h2
{
font-size: 14px;
margin: 0;
padding: 0 0 8px 0;
border-bottom: #bbb solid 1px;
color: #f93;
}
.pag a
{
margin: 0 4px;
}
.noticiaListado
{
float: left;
width: 442px;
height: 500px;
padding: 0 13px;
border-bottom: #bbb solid 1px;
}
.noticiaListado img
{
width: 118px!important;
}
.noticias img
{
float: left;
margin: 12px 12px 12px 0;
width: 240px;
}
.display
{
float: left;
width: 171px;
border-bottom: #adadad solid 1px;
padding: 0 0 14px 0;
background: #fff;
display: none;
}
.display a
{
float: left;
color: #333;
font-weight: normal;
padding: 1px 0 0 14px;
background: #fff;
}
.display a:hover
{
font-weight: bold;
background: #f2f2f2;
color: #333;
}
.paginacion
{
float: left;
width: 100%;
padding: 0 0 10px 0;
color: #0a72a9;
font-weight: bold;
font-size: 11px;
}
.paginacion a
{
color: #0a72a9;
}
.pag1
{
float: left;
width: 29%;
}
.pag2
{
float: left;
width: 40%;
text-align: center;
}
.pag3
{
float: left;
width: 29%;
text-align: right;
}
.pasafotos
{
float: left;
width: 478px;
overflow: hidden;
position: relative;
}
.pie
{
min-width: 100%;
height: 244px;
background: url(images/bg_pie.gif) repeat-x;
overflow: hidden;
padding: 22px 0 0 0;
color: #666;
font-size: 11px;
}
.pie strong
{
color: #999;
}
.pie a
{
color: #666;
}
.precio
{
float: left;
width: 100%;
text-align: center;
font-size: 12px;
font-weight: bold;
}
.precioDetalle
{
float: left;
width: 100%;
background: url(images/bg_precio.gif) 0px 21px no-repeat;
padding: 42px 0 11px 0;
border-bottom: #bbb solid 1px;
}
.fichaSlide .precioDetalle
{
border: none;
background: url(images/bg_precio.gif) no-repeat;
padding: 25px 0 0 0;
}
.precioNew
{
position: absolute;
left: 158px;
top: 115px;
color: #044364;
font: 14px "Trebuchet MS";
}
.precioOld
{
position: absolute;
left: 158px;
top: 95px;
font: 14px "Trebuchet MS";
}
.marca
{
color: #c5bdbd!important;
font: 14px "Trebuchet MS"!important;
}
.precioDetalle .precioNew, .precioDetalle .precioOld
{
float: left;
position: relative;
left: 0;
top: 0;
width: 100%;
}
.precioDetalle .precioNew
{
font-size: 22px;
font-weight: bold;
}
.fichaSlide .precioOld
{
color: #044364;
}
.precioOld2
{
color: #b2b2b2;
text-decoration: line-through;
}
.productos
{
float: left;
width: 100%;
padding: 19px 0 16px 0;
overflow: hidden;
height: auto;
}
.rojo
{
color: #d80e21;
}
.ruta
{
float: left;
width: 100%;
height: 20px;
font-size: 11px;
color: #999;
font-weight: bold;
}
.sinBorde
{
border: none !important;
background: none !important;
}
.sinMargen
{
margin: 0;
}
.slider
{
position: absolute;
width: 464px;
height: 201px;
overflow: hidden;
left: 13px;
top: 44px;
}
.slider2
{
float: left;
width: 465px;
height: 201px;
overflow: hidden;
padding: 6px 0 0 0;
position: relative;
}
.sliderIndex
{
float: left;
width: 940px;
height: 214px;
background:#FFF;
overflow: hidden;
position: relative;
}
#sliderInt, #sliderInt2, #sliderInt3
{
position: absolute;
}
#sliderInt td, #sliderInt2 td
{
width: 157px;
overflow: hidden;
}
#sliderInt3 td
{
width: 470px;
overflow: hidden;
}
#sliderInt3 ul
{
margin: 0;
padding: 0;
}
#sliderInt3 li
{
float: left;
margin: 0;
padding: 0;
width: 471px;
overflow: hidden;
position: relative;
}
.tablaCabe
{
color: #505456;
font-size: 10px;
margin: 0 0 3px 0;
}
.tablaCabe a
{
color: #0a72a9;
}
.tablaCabe input
{
width: 35px;
margin: 0 4px 0 0;
color: #333;
border: #ababab solid 1px;
font-size: 11px;
}
.tachado
{
text-decoration: line-through;
font-size: 18px;
font-weight: bold;
color:#F00;
}
.tdGris1
{
border-right: #fff solid 1px;
padding: 0 0 0 8px;
height: 27px;
background: #f2f2f2;
border-top: #fff solid 3px;
border-bottom: #fff solid 1px;
color: #212223;
font-size: 11px;
}
.tdGris2
{
border-right: #fff solid 1px;
background: #f2f2f2;
border-top: #fff solid 3px;
border-bottom: #fff solid 1px;
color: #212223;
font-size: 11px;
}
.tdGris3
{
background: #f2f2f2;
border-top: #fff solid 3px;
border-bottom: #fff solid 1px;
color: #212223;
font-size: 11px;
}
.tfnoInferior
{
float: left;
width: 160px;
padding: 32px 0 0 12px;
}
.tiendas
{
float: left;
width: 493px;
}
.tiendas a
{
float: left;
margin: 0 5px 5px 0;
padding: 3px;
border: #ccc solid 1px;
width: 62px;
}
.tiendas .grande
{
margin: 0 4px 0 0;
border: none;
padding: 0;
float: left;
width: 317px;
height: 228px;
}
.tiendas a:hover
{
background: #f60;
}
.titulo
{
float: left;
width: 100%;
text-align: right;
position: relative;
overflow: hidden;
font-size: 11px;
color: #044364;
height: 33px;
padding: 7px 0 0 0;
}
.titulo a
{
color: #044364;
}
.titulo img
{
position: absolute;
left: 0px;
top: 0px;
}
.tusDatos
{
float: left;
width: 787px;
overflow: hidden;
padding: 54px 0 0 0;
margin: 18px 0 0 0;
background: url(images/tus_datos.gif) no-repeat;
display: none;
}
.campo
{
color: #333;
background: #e9e9e9;
border: #ababab solid 1px;
font-size: 11px;
width: 290px;
padding: 2px;
margin:0 0 4px 0;
}
.selectCampo
{
color: #333;
background: #e9e9e9;
border: #ababab solid 1px;
font-size: 11px;
width: 290px;
padding: 2px;
margin:0 0 4px 0;
}
.check
{
color: #333;
padding: 2px;
margin:2px;
}
.div2 .titulo
{
width: 460px;
margin: 0 0 0 13px;
padding: 7px 17px 0 0;
}
.tramitar
{
border: none !important;
background: url(images/bg_tramitar.jpg) no-repeat !important;
color: #fff !important;
font-size: 11px !important;
font-weight: bold;
height: 24px;
line-height: 24px;
width: 126px !important;
margin: 12px 0 20px 0 !important;
padding: 0 !important;
cursor: hand;
cursor: pointer;
}
a.naranjaBold, .naranjaBold
{
color: #ff9933;
font-weight: bold;
}
.w348
{
width: 348px;
}
.w206
{
width: 206px;
}
.w56
{
width: 56px;
}
.error-message, label.error { color: red; display: block; }
.banner_home{ float:left; margin:0 ; width:456px; height:168px; padding:0 20px 0 0; border-right:1px solid #bbb; margin: 0 10px 0 0 }
.banner_home img{ border: 3px solid #bbb; width: 443px; height: 162px}
.newsletter{ float:left; margin:0 ; width:446px; height:168px; }
.banner-content
{
width:442px;
height:288px;
background:url(images/banner-horarios.jpg) no-repeat;
position:absolute;
top:-288px;
left:25%;
z-index:9997;
cursor:pointer;
}
a#cerrarBanner{background: url(images/close.png) no-repeat; display:block; width:23px; height:23px; position:relative; z-index: 9998; top:3px; right:-410px; }
.banner-content {
width: 436px;
height: 283px;
background: url(images/banner-horarios.jpg) no-repeat;
position: absolute;
top: -300px;
left: 35%;
z-index: 9997;
-webkit-box-shadow: 1px 1px 12px 3px #525252;
box-shadow: 1px 1px 12px 3px #525252;
}
.scroll {
overflow-y: scroll;
}
| DAWalbertofdez/ProyectoMarcAlbertoDani | morenito.css | CSS | mit | 23,855 |
<html><body>
<h4>Windows 10 x64 (19041.388)</h4><br>
<h2>_IO_APIC_REGISTERS</h2>
<font face="arial"> +0x000 RegisterIndex : Uint4B<br>
+0x004 Reserved1 : [3] Uint4B<br>
+0x010 RegisterValue : Uint4B<br>
+0x014 Reserved2 : [11] Uint4B<br>
+0x040 EndOfInterrupt : Uint4B<br>
</font></body></html> | epikcraw/ggool | public/Windows 10 x64 (19041.388)/_IO_APIC_REGISTERS.html | HTML | mit | 338 |
import os
import logging
from django.core.management.base import BaseCommand
from django.core.mail import send_mail
from django.template.loader import get_template
from workshops.models import Badge, Person, Role
logger = logging.getLogger()
class Command(BaseCommand):
help = 'Report instructors activity.'
def add_arguments(self, parser):
parser.add_argument(
'--send-out-for-real', action='store_true', default=False,
help='Send information to the instructors.',
)
parser.add_argument(
'--no-may-contact-only', action='store_true', default=False,
help='Include instructors not willing to be contacted.',
)
parser.add_argument(
'--django-mailing', action='store_true', default=False,
help='Use Django mailing system. This requires some environmental '
'variables to be set, see `settings.py`.',
)
parser.add_argument(
'-s', '--sender', action='store',
default='[email protected]',
help='E-mail used in "from:" field.',
)
def foreign_tasks(self, tasks, person, roles):
"""List of other instructors' tasks, per event."""
return [
task.event.task_set.filter(role__in=roles)
.exclude(person=person)
.select_related('person')
for task in tasks
]
def fetch_activity(self, may_contact_only=True):
roles = Role.objects.filter(name__in=['instructor', 'helper'])
instructor_badges = Badge.objects.instructor_badges()
instructors = Person.objects.filter(badges__in=instructor_badges)
instructors = instructors.exclude(email__isnull=True)
if may_contact_only:
instructors = instructors.exclude(may_contact=False)
# let's get some things faster
instructors = instructors.select_related('airport') \
.prefetch_related('task_set', 'lessons',
'award_set', 'badges')
# don't repeat the records
instructors = instructors.distinct()
result = []
for person in instructors:
tasks = person.task_set.filter(role__in=roles) \
.select_related('event', 'role')
record = {
'person': person,
'lessons': person.lessons.all(),
'instructor_awards': person.award_set.filter(
badge__in=person.badges.instructor_badges()
),
'tasks': zip(tasks,
self.foreign_tasks(tasks, person, roles)),
}
result.append(record)
return result
def make_message(self, record):
tmplt = get_template('mailing/instructor_activity.txt')
return tmplt.render(context=record)
def subject(self, record):
# in future we can vary the subject depending on the record details
return 'Updating your Software Carpentry information'
def recipient(self, record):
return record['person'].email
def send_message(self, subject, message, sender, recipient, for_real=False,
django_mailing=False):
if for_real:
if django_mailing:
send_mail(subject, message, sender, [recipient])
else:
command = 'mail -s "{subject}" -r {sender} {recipient}'.format(
subject=subject,
sender=sender,
recipient=recipient,
)
writer = os.popen(command, 'w')
writer.write(message)
writer.close()
if self.verbosity >= 2:
# write only a header
self.stdout.write('-' * 40 + '\n')
self.stdout.write('To: {}\n'.format(recipient))
self.stdout.write('Subject: {}\n'.format(subject))
self.stdout.write('From: {}\n'.format(sender))
if self.verbosity >= 3:
# write whole message out
self.stdout.write(message + '\n')
def handle(self, *args, **options):
# default is dummy run - only actually send mail if told to
send_for_real = options['send_out_for_real']
# by default include only instructors who have `may_contact==True`
no_may_contact_only = options['no_may_contact_only']
# use mailing options from settings.py or the `mail` system command?
django_mailing = options['django_mailing']
# verbosity option is added by Django
self.verbosity = int(options['verbosity'])
sender = options['sender']
results = self.fetch_activity(not no_may_contact_only)
for result in results:
message = self.make_message(result)
subject = self.subject(result)
recipient = self.recipient(result)
self.send_message(subject, message, sender, recipient,
for_real=send_for_real,
django_mailing=django_mailing)
if self.verbosity >= 1:
self.stdout.write('Sent {} emails.\n'.format(len(results)))
| swcarpentry/amy | amy/workshops/management/commands/instructors_activity.py | Python | mit | 5,305 |
<?php
/*
* This file is part of the Phuri package.
*
* Copyright © 2014 Erin Millard
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eloquent\Phuri\Generic;
use Eloquent\Pathogen\Factory\PathFactoryInterface;
use Eloquent\Phuri\Generic\Parser\GenericUriComponentsInterface;
use Eloquent\Phuri\Normalization\UriNormalizerInterface;
use Eloquent\Phuri\Parameters\Factory\UriParametersFactoryInterface;
use Eloquent\Phuri\Path\Factory\UriPathFactory;
use Eloquent\Phuri\UriInterface;
use Eloquent\Phuri\Validation\Exception\InvalidUriComponentExceptionInterface;
/**
* An abstract base class for implementing generic URIs.
*/
abstract class AbstractGenericUri implements GenericUriInterface
{
/**
* Construct a new generic URI.
*
* @param GenericUriComponentsInterface $components The URI components.
*
* @throws InvalidUriComponentExceptionInterface If any of the components are invalid.
*/
public function __construct(GenericUriComponentsInterface $components)
{
$this->username = $components->username();
$this->password = $components->password();
$this->host = $components->host();
$this->port = $components->port();
$this->path = $components->path();
$this->fragment = $components->fragment();
if (null === $components->queryParameters()) {
$this->hasQueryDelimiter = false;
$this->queryParameters = static::queryParametersFactory()
->createEmpty();
} else {
$this->hasQueryDelimiter = true;
$this->queryParameters = static::queryParametersFactory()
->createFromEncodedPairs($components->queryParameters());
}
}
// Implementation of GenericUriInterface ===================================
/**
* Returns true if this URI has a username.
*
* This method will return false for URIs with empty string usernames.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.2.1
*
* @return boolean True if this URI has a username.
*/
public function hasUsername()
{
return null !== $this->encodedUsername() &&
'' !== $this->encodedUsername();
}
/**
* Get the username.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.2.1
*
* @return string|null The username, or null if there is no username.
*/
public function username()
{
if (null === $this->encodedUsername()) {
return null;
}
return static::encoder()->decode($this->encodedUsername());
}
/**
* Get the encoded username.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.2.1
*
* @return string|null The encoded username, or null if there is no username.
*/
public function encodedUsername()
{
return $this->username;
}
/**
* Returns true if this URI has a password.
*
* This method will return false for URIs with empty string passwords.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.2.1
*
* @return boolean True if this URI has a password.
*/
public function hasPassword()
{
return null !== $this->encodedPassword() &&
'' !== $this->encodedPassword();
}
/**
* Get the password.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.2.1
*
* @return string|null The password, or null if there is no password.
*/
public function password()
{
if (null === $this->encodedPassword()) {
return null;
}
return static::encoder()->decode($this->encodedPassword());
}
/**
* Get the encoded password.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.2.1
*
* @return string|null The encoded password, or null if there is no password.
*/
public function encodedPassword()
{
return $this->password;
}
/**
* Get the encoded host.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.2.2
*
* @return string|null The encoded host, or null if there is no host.
*/
public function encodedHost()
{
return $this->host;
}
/**
* Returns true if this URI has a port.
*
* This method will return false for URIs with empty string ports.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.2.3
*
* @return boolean True if this URI has a port.
*/
public function hasPort()
{
return null !== $this->encodedPort() && '' !== $this->encodedPort();
}
/**
* Get the port.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.2.3
*
* @return integer|null The port, or null if there is no port, or the port is an empty string.
*/
public function port()
{
if ($this->hasPort()) {
return intval($this->encodedPort());
}
return null;
}
/**
* Get the encoded port.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.2.3
*
* @return string|null The encoded port, or null if there is no port.
*/
public function encodedPort()
{
return $this->port;
}
/**
* Returns true if this URI has a path.
*
* This method will return false for URIs with empty string paths.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.3
*
* @return boolean True if this URI has a path.
*/
public function hasPath()
{
return '' !== $this->path();
}
/**
* Get the path.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.3
*
* @return string The path.
*/
public function path()
{
return static::encoder()->decode($this->encodedPath());
}
/**
* Get the encoded path.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.3
*
* @return string The encoded path.
*/
public function encodedPath()
{
return $this->path;
}
/**
* Get the path as a path object.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.3
*
* @return UriPathInterface The path.
*/
public function pathObject()
{
return static::pathFactory()->create($this->path());
}
/**
* Returns true if this URI has a query.
*
* This method will return false for URIs with empty string queries.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.4
*
* @return boolean True if this URI has a query.
*/
public function hasQuery()
{
return !$this->queryParameters()->isEmpty();
}
/**
* Get the query.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.4
*
* @return string|null The query, or null if there is no query.
*/
public function query()
{
if ($this->hasQueryDelimiter()) {
return static::encoder()->decode($this->encodedQuery());
}
return null;
}
/**
* Get the encoded query.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.4
*
* @return string|null The encoded query, or null if there is no query.
*/
public function encodedQuery()
{
if ($this->hasQueryDelimiter()) {
return $this->queryParameters()->string();
}
return null;
}
/**
* Get the query parameters.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.4
*
* @return UriParametersInterface The query parameters.
*/
public function queryParameters()
{
return $this->queryParameters;
}
/**
* Returns true if this URI has a fragment.
*
* This method will return false for URIs with empty string fragments.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.5
*
* @return boolean True if this URI has a fragment.
*/
public function hasFragment()
{
return null !== $this->encodedFragment() &&
'' !== $this->encodedFragment();
}
/**
* Get the fragment.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.5
*
* @return string|null The fragment, or null if there is no fragment.
*/
public function fragment()
{
if (null === $this->encodedFragment()) {
return null;
}
return static::encoder()->decode($this->encodedFragment());
}
/**
* Get the encoded fragment.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.5
*
* @return string|null The encoded fragment, or null if there is no fragment.
*/
public function encodedFragment()
{
return $this->fragment;
}
/**
* Get the fragment parameters.
*
* @link http://tools.ietf.org/html/rfc3986#section-3.5
*
* @return UriParametersInterface The fragment parameters.
*/
public function fragmentParameters()
{
if (null === $this->encodedFragment()) {
return static::queryParametersFactory()->createEmpty();
}
return static::queryParametersFactory()
->createFromString($this->encodedFragment());
}
// Implementation of UriInterface ==========================================
/**
* Return a normalized version of this URI.
*
* @return UriInterface A normalized version of this URI.
*/
public function normalize()
{
return static::normalizer()->normalize($this);
}
/**
* Get a string representation of this URI.
*
* @return string A string representation of this URI.
*/
public function __toString()
{
return $this->string();
}
// Implementation details ==================================================
/**
* Returns true if this URI has a query delimiter.
*
* @return boolean True if this URI has a query delimiter.
*/
public function hasQueryDelimiter()
{
return $this->hasQueryDelimiter;
}
/**
* Get the most appropriate factory for this type of URI.
*
* @return Factory\GenericUriFactoryInterface The factory.
*/
protected static function factory()
{
return Factory\GenericUriFactory::instance();
}
/**
* Get the most appropriate path factory for this type of URI.
*
* @return PathFactoryInterface The factory.
*/
protected static function pathFactory()
{
return UriPathFactory::instance();
}
/**
* Get the most appropriate query parameters factory for this type of URI.
*
* @return UriParametersFactoryInterface The factory.
*/
protected static function queryParametersFactory()
{
return Factory\GenericUriQueryParametersFactory::instance();
}
/**
* Get the most appropriate validator for this type of URI.
*
* @return Validation\GenericUriValidatorInterface The validator.
*/
protected static function validator()
{
return Validation\GenericUriValidator::instance();
}
/**
* Get the most appropriate encoder for this type of URI.
*
* @return Encoding\GenericUriEncoderInterface The encoder.
*/
protected static function encoder()
{
return Encoding\GenericUriEncoder::instance();
}
/**
* Get the most appropriate normalizer for this type of URI.
*
* @return UriNormalizerInterface The normalizer.
*/
protected static function normalizer()
{
return Normalization\GenericUriNormalizer::instance();
}
private $username;
private $password;
private $host;
private $port;
private $path;
private $hasQueryDelimiter;
private $queryParameters;
private $fragment;
}
| ezzatron/phuri | src/Generic/AbstractGenericUri.php | PHP | mit | 12,051 |
# react-all
Use ReactJS to do cross platform StartKit
| keyfun/react-all | README.md | Markdown | mit | 54 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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 org.spongepowered.common.data.manipulator.block;
import static org.spongepowered.api.data.DataQuery.of;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.DataQuery;
import org.spongepowered.api.data.MemoryDataContainer;
import org.spongepowered.api.data.manipulator.block.SignaledOutputData;
import org.spongepowered.common.data.manipulator.AbstractIntData;
public class SpongeSignaledOutputData extends AbstractIntData<SignaledOutputData> implements SignaledOutputData {
public static final DataQuery OUTPUT_SIGNAL_STRENGTH = of("OutputSignalStrength");
public SpongeSignaledOutputData() {
super(SignaledOutputData.class, 0, 0, 15);
}
@Override
public int getOutputSignal() {
return this.getValue();
}
@Override
public SignaledOutputData setOutputSignal(int signal) {
return this.setValue(signal);
}
@Override
public SignaledOutputData copy() {
return new SpongeSignaledOutputData().setValue(this.getValue());
}
@Override
public DataContainer toContainer() {
return new MemoryDataContainer().set(OUTPUT_SIGNAL_STRENGTH, this.getValue());
}
}
| gabizou/SpongeCommon | src/main/java/org/spongepowered/common/data/manipulator/block/SpongeSignaledOutputData.java | Java | mit | 2,441 |
// Copyright (c) 2013 Raphael Estrada
// License: The MIT License - see "LICENSE" file for details
// Author URL: http://www.galaktor.net
// Author E-Mail: [email protected]
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AutofacExtensions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Raphael Estrada")]
[assembly: AssemblyProduct("AutofacExtensions")]
[assembly: AssemblyCopyright("Copyright (c) Raphael Estrada 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("31dee9f1-b44b-4a04-89cf-d17ea82953ef")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")] | galaktor/autofac-extensions | Properties/AssemblyInfo.cs | C# | mit | 1,633 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.mgmt.core.exceptions import ARMErrorFormat
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_delete_request(
scope: str,
policy_assignment_name: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2016-12-01"
accept = "application/json, text/json"
# Construct URL
url = kwargs.pop("template_url", '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}')
path_format_arguments = {
"scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True),
"policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="DELETE",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_create_request(
scope: str,
policy_assignment_name: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2016-12-01"
accept = "application/json, text/json"
# Construct URL
url = kwargs.pop("template_url", '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}')
path_format_arguments = {
"scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True),
"policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_get_request(
scope: str,
policy_assignment_name: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2016-12-01"
accept = "application/json, text/json"
# Construct URL
url = kwargs.pop("template_url", '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}')
path_format_arguments = {
"scope": _SERIALIZER.url("scope", scope, 'str', skip_quote=True),
"policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_for_resource_group_request(
resource_group_name: str,
subscription_id: str,
*,
filter: Optional[str] = None,
**kwargs: Any
) -> HttpRequest:
api_version = "2016-12-01"
accept = "application/json, text/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
if filter is not None:
query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str', skip_quote=True)
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_for_resource_request(
resource_group_name: str,
resource_provider_namespace: str,
parent_resource_path: str,
resource_type: str,
resource_name: str,
subscription_id: str,
*,
filter: Optional[str] = None,
**kwargs: Any
) -> HttpRequest:
api_version = "2016-12-01"
accept = "application/json, text/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments')
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
"resourceProviderNamespace": _SERIALIZER.url("resource_provider_namespace", resource_provider_namespace, 'str'),
"parentResourcePath": _SERIALIZER.url("parent_resource_path", parent_resource_path, 'str', skip_quote=True),
"resourceType": _SERIALIZER.url("resource_type", resource_type, 'str', skip_quote=True),
"resourceName": _SERIALIZER.url("resource_name", resource_name, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
if filter is not None:
query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str')
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_list_request(
subscription_id: str,
*,
filter: Optional[str] = None,
**kwargs: Any
) -> HttpRequest:
api_version = "2016-12-01"
accept = "application/json, text/json"
# Construct URL
url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments')
path_format_arguments = {
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
if filter is not None:
query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str')
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_delete_by_id_request(
policy_assignment_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2016-12-01"
accept = "application/json, text/json"
# Construct URL
url = kwargs.pop("template_url", '/{policyAssignmentId}')
path_format_arguments = {
"policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, 'str', skip_quote=True),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="DELETE",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_create_by_id_request(
policy_assignment_id: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpRequest:
content_type = kwargs.pop('content_type', None) # type: Optional[str]
api_version = "2016-12-01"
accept = "application/json, text/json"
# Construct URL
url = kwargs.pop("template_url", '/{policyAssignmentId}')
path_format_arguments = {
"policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, 'str', skip_quote=True),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
if content_type is not None:
header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=url,
params=query_parameters,
headers=header_parameters,
json=json,
content=content,
**kwargs
)
def build_get_by_id_request(
policy_assignment_id: str,
**kwargs: Any
) -> HttpRequest:
api_version = "2016-12-01"
accept = "application/json, text/json"
# Construct URL
url = kwargs.pop("template_url", '/{policyAssignmentId}')
path_format_arguments = {
"policyAssignmentId": _SERIALIZER.url("policy_assignment_id", policy_assignment_id, 'str', skip_quote=True),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class PolicyAssignmentsOperations(object):
"""PolicyAssignmentsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.resource.policy.v2016_12_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def delete(
self,
scope: str,
policy_assignment_name: str,
**kwargs: Any
) -> Optional["_models.PolicyAssignment"]:
"""Deletes a policy assignment.
:param scope: The scope of the policy assignment.
:type scope: str
:param policy_assignment_name: The name of the policy assignment to delete.
:type policy_assignment_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PolicyAssignment, or the result of cls(response)
:rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment or None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.PolicyAssignment"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_request(
scope=scope,
policy_assignment_name=policy_assignment_name,
template_url=self.delete.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PolicyAssignment', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'} # type: ignore
@distributed_trace
def create(
self,
scope: str,
policy_assignment_name: str,
parameters: "_models.PolicyAssignment",
**kwargs: Any
) -> "_models.PolicyAssignment":
"""Creates a policy assignment.
Policy assignments are inherited by child resources. For example, when you apply a policy to a
resource group that policy is assigned to all resources in the group.
:param scope: The scope of the policy assignment.
:type scope: str
:param policy_assignment_name: The name of the policy assignment.
:type policy_assignment_name: str
:param parameters: Parameters for the policy assignment.
:type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PolicyAssignment, or the result of cls(response)
:rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyAssignment"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'PolicyAssignment')
request = build_create_request(
scope=scope,
policy_assignment_name=policy_assignment_name,
content_type=content_type,
json=_json,
template_url=self.create.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('PolicyAssignment', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'} # type: ignore
@distributed_trace
def get(
self,
scope: str,
policy_assignment_name: str,
**kwargs: Any
) -> "_models.PolicyAssignment":
"""Gets a policy assignment.
:param scope: The scope of the policy assignment.
:type scope: str
:param policy_assignment_name: The name of the policy assignment to get.
:type policy_assignment_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PolicyAssignment, or the result of cls(response)
:rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyAssignment"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_request(
scope=scope,
policy_assignment_name=policy_assignment_name,
template_url=self.get.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('PolicyAssignment', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'} # type: ignore
@distributed_trace
def list_for_resource_group(
self,
resource_group_name: str,
filter: Optional[str] = None,
**kwargs: Any
) -> Iterable["_models.PolicyAssignmentListResult"]:
"""Gets policy assignments for the resource group.
:param resource_group_name: The name of the resource group that contains policy assignments.
:type resource_group_name: str
:param filter: The filter to apply on the operation.
:type filter: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PolicyAssignmentListResult or the result of
cls(response)
:rtype:
~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignmentListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyAssignmentListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_for_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
filter=filter,
template_url=self.list_for_resource_group.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_for_resource_group_request(
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
filter=filter,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments'} # type: ignore
@distributed_trace
def list_for_resource(
self,
resource_group_name: str,
resource_provider_namespace: str,
parent_resource_path: str,
resource_type: str,
resource_name: str,
filter: Optional[str] = None,
**kwargs: Any
) -> Iterable["_models.PolicyAssignmentListResult"]:
"""Gets policy assignments for a resource.
:param resource_group_name: The name of the resource group containing the resource. The name is
case insensitive.
:type resource_group_name: str
:param resource_provider_namespace: The namespace of the resource provider.
:type resource_provider_namespace: str
:param parent_resource_path: The parent resource path.
:type parent_resource_path: str
:param resource_type: The resource type.
:type resource_type: str
:param resource_name: The name of the resource with policy assignments.
:type resource_name: str
:param filter: The filter to apply on the operation.
:type filter: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PolicyAssignmentListResult or the result of
cls(response)
:rtype:
~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignmentListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyAssignmentListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_for_resource_request(
resource_group_name=resource_group_name,
resource_provider_namespace=resource_provider_namespace,
parent_resource_path=parent_resource_path,
resource_type=resource_type,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
filter=filter,
template_url=self.list_for_resource.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_for_resource_request(
resource_group_name=resource_group_name,
resource_provider_namespace=resource_provider_namespace,
parent_resource_path=parent_resource_path,
resource_type=resource_type,
resource_name=resource_name,
subscription_id=self._config.subscription_id,
filter=filter,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_for_resource.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments'} # type: ignore
@distributed_trace
def list(
self,
filter: Optional[str] = None,
**kwargs: Any
) -> Iterable["_models.PolicyAssignmentListResult"]:
"""Gets all the policy assignments for a subscription.
:param filter: The filter to apply on the operation.
:type filter: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PolicyAssignmentListResult or the result of
cls(response)
:rtype:
~azure.core.paging.ItemPaged[~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignmentListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyAssignmentListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
filter=filter,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
subscription_id=self._config.subscription_id,
filter=filter,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("PolicyAssignmentListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments'} # type: ignore
@distributed_trace
def delete_by_id(
self,
policy_assignment_id: str,
**kwargs: Any
) -> "_models.PolicyAssignment":
"""Deletes a policy assignment by ID.
When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for
subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for
resource groups, and
'/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}'
for resources.
:param policy_assignment_id: The ID of the policy assignment to delete. Use the format
'/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
:type policy_assignment_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PolicyAssignment, or the result of cls(response)
:rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyAssignment"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_delete_by_id_request(
policy_assignment_id=policy_assignment_id,
template_url=self.delete_by_id.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('PolicyAssignment', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
delete_by_id.metadata = {'url': '/{policyAssignmentId}'} # type: ignore
@distributed_trace
def create_by_id(
self,
policy_assignment_id: str,
parameters: "_models.PolicyAssignment",
**kwargs: Any
) -> "_models.PolicyAssignment":
"""Creates a policy assignment by ID.
Policy assignments are inherited by child resources. For example, when you apply a policy to a
resource group that policy is assigned to all resources in the group. When providing a scope
for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions,
'/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups,
and
'/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}'
for resources.
:param policy_assignment_id: The ID of the policy assignment to create. Use the format
'/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
:type policy_assignment_id: str
:param parameters: Parameters for policy assignment.
:type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PolicyAssignment, or the result of cls(response)
:rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyAssignment"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'PolicyAssignment')
request = build_create_by_id_request(
policy_assignment_id=policy_assignment_id,
content_type=content_type,
json=_json,
template_url=self.create_by_id.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('PolicyAssignment', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create_by_id.metadata = {'url': '/{policyAssignmentId}'} # type: ignore
@distributed_trace
def get_by_id(
self,
policy_assignment_id: str,
**kwargs: Any
) -> "_models.PolicyAssignment":
"""Gets a policy assignment by ID.
When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for
subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for
resource groups, and
'/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}'
for resources.
:param policy_assignment_id: The ID of the policy assignment to get. Use the format
'/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
:type policy_assignment_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PolicyAssignment, or the result of cls(response)
:rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyAssignment"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_get_by_id_request(
policy_assignment_id=policy_assignment_id,
template_url=self.get_by_id.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('PolicyAssignment', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_by_id.metadata = {'url': '/{policyAssignmentId}'} # type: ignore
| Azure/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/v2016_12_01/operations/_policy_assignments_operations.py | Python | mit | 38,695 |
class CreateDocuments < ActiveRecord::Migration[5.0]
def change
create_table :documents do |t|
t.integer :product_id, null: false
t.string :type, null: false
t.string :url, null: false
t.timestamps
end
end
end
| unasuke/proconist.net | db/migrate/20160610084904_create_documents.rb | Ruby | mit | 265 |
@font-face {
font-family: 'icomoon';
src: url('../fonts/icomoon.eot');
src: url('../fonts/icomoon.eot?#iefix') format('embedded-opentype'),
url('../fonts/icomoon.woff') format('woff'),
url('../fonts/icomoon.ttf') format('truetype'),
url('../fonts/icomoon.svg#icomoon') format('svg');
font-weight: normal;
font-style: normal;
}
/* Windows Chrome ugly fix http://stackoverflow.com/questions/13674808/chrome-svg-font-rendering-breaks-layout/14345363#14345363 */
@media screen and (-webkit-min-device-pixel-ratio:0) {
@font-face {
font-family: 'icomoon';
src: url('../fonts/icomoon.svg#icomoon') format('svg');
};
}
a, li {-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}
/* CSS général appliqué quelque soit la taille de l'écran */
.nav ul {
max-width: 100%;
margin: 0;
padding: 0;
list-style: none;
font-size: 1.5em;
font-weight: 300;
}
.nav li span {display: block;}
.nav a {
display: block;
padding-top:8px;
color: rgba(249, 249, 249, .9);
text-decoration: none;
-webkit-transition: color .5s, background .5s, height .5s;
-moz-transition: color .5s, background .5s, height .5s;
-o-transition: color .5s, background .5s, height .5s;
-ms-transition: color .5s, background .5s, height .5s;
transition: color .5s, background .5s, height .5s;
}
/* Remove the blue Webkit background when element is tapped */
a, button {-webkit-tap-highlight-color: rgba(0,0,0,0);}
/* Hover effect for the whole navigation to make the hovered item stand out */
.no-touch .nav ul:hover a {color: rgba(249, 249, 249, .5);}
.no-touch .nav ul:hover a:hover {color: rgba(249, 249, 249, 0.99);}
/* Couleur de fond aux différents éléments du menu de navigation */
.nav li:nth-child(6n+1) {background: rgb(208, 101, 3);}
.nav li:nth-child(6n+2) {background: rgb(233, 147, 26);}
.nav li:nth-child(6n+3) {background: rgb(22, 145, 190);}
.nav li:nth-child(6n+4) {background: rgb(22, 107, 162);}
.nav li:nth-child(6n+5) {background: rgb(27, 54, 71);}
.nav li:nth-child(6n+6) {background: rgb(21, 40, 54);}
/* Pour les écrans au-delà de 800px */
@media (min-width: 50em) {
/* Les fonds d'écran s'étirent à 100% sur leur axe horizontal */
.bg1, .bg2, .bg3, .bg4 {background-size:100% auto;}
/* Les éléments du menu s'alignent sur l'horizontal */
.nav li {
float: left;
width: 20%;
text-align: center;
-webkit-transition: border .5s;
-moz-transition: border .5s;
-o-transition: border .5s;
-ms-transition: border .5s;
transition: border .5s;
}
.nav a {display: block;width: auto;}
/* hover, focus et active : ils ajoutent une bordure colorée aux éléments */
.no-touch .nav li:nth-child(6n+1) a:hover,
.no-touch .nav li:nth-child(6n+1) a:active,
.no-touch .nav li:nth-child(6n+1) a:focus {
border-bottom: 4px solid rgb(174, 78, 1);
}
.no-touch .nav li:nth-child(6n+2) a:hover,
.no-touch .nav li:nth-child(6n+2) a:active,
.no-touch .nav li:nth-child(6n+2) a:focus {
border-bottom: 4px solid rgb(191, 117, 20);
}
.no-touch .nav li:nth-child(6n+3) a:hover,
.no-touch .nav li:nth-child(6n+3) a:active,
.no-touch .nav li:nth-child(6n+3) a:focus {
border-bottom: 4px solid rgb(12, 110, 149);
}
.no-touch .nav li:nth-child(6n+4) a:hover,
.no-touch .nav li:nth-child(6n+4) a:active,
.no-touch .nav li:nth-child(6n+4) a:focus {
border-bottom: 4px solid rgb(10, 75, 117);
}
.no-touch .nav li:nth-child(6n+5) a:hover,
.no-touch .nav li:nth-child(6n+5) a:active,
.no-touch .nav li:nth-child(6n+5) a:focus {
border-bottom: 4px solid rgb(16, 34, 44);
}
.no-touch .nav li:nth-child(6n+6) a:hover,
.no-touch .nav li:nth-child(6n+6) a:active,
.no-touch .nav li:nth-child(6n+6) a:focus {
border-bottom: 4px solid rgb(9, 18, 25);
}
/* Possibilité d'animer la hauteur des onglets : là elle est fixe */
.nav a,
.no-touch .nav a:hover ,
.nav a:active ,
.nav a:focus {
height: 2.2em;
}
}
@media (min-width: 50em) and (max-width: 61.250em) {
/* Size and font adjustments to make it fit into the screen*/
.nav ul {font-size: 1.2em;}
}
/* Version tablette et mobile */
/* Disposition générale */
@media (max-width: 49.938em) {
/* Bordure colorée */
.no-touch .nav ul li:nth-child(6n+1) a:hover,
.no-touch .nav ul li:nth-child(6n+1) a:active,
.no-touch .nav ul li:nth-child(6n+1) a:focus {
background: rgb(227, 119, 20);
}
.no-touch .nav li:nth-child(6n+2) a:hover,
.no-touch .nav li:nth-child(6n+2) a:active,
.no-touch .nav li:nth-child(6n+2) a:focus {
background: rgb(245, 160, 41);
}
.no-touch .nav li:nth-child(6n+3) a:hover,
.no-touch .nav li:nth-child(6n+3) a:active,
.no-touch .nav li:nth-child(6n+3) a:focus {
background: rgb(44, 168, 219);
}
.no-touch .nav li:nth-child(6n+4) a:hover,
.no-touch .nav li:nth-child(6n+4) a:active,
.no-touch .nav li:nth-child(6n+4) a:focus {
background: rgb(31, 120, 176);
}
.no-touch .nav li:nth-child(6n+5) a:hover,
.no-touch .nav li:nth-child(6n+5) a:active,
.no-touch .nav li:nth-child(6n+5) a:focus {
background: rgb(39, 70, 90);
}
.no-touch .nav li:nth-child(6n+6) a:hover,
.no-touch .nav li:nth-child(6n+6) a:active,
.no-touch .nav li:nth-child(6n+6) a:focus {
background: rgb(32, 54, 68);
}
.nav ul li {
-webkit-transition: background 0.5s;
-moz-transition: background 0.5s;
-o-transition: background 0.5s;
-ms-transition: background 0.5s;
transition: background 0.5s;
}
}
/* Propriétés CSS spécifiques au mode "Colonnes 2x3" */
@media (min-width:32.5em) and (max-width: 49.938em) {
/* Les fonds d'écran s'étirent à 100% sur leur axe horizontal */
.bg1,.bg2,.bg3,.bg4{background-size:auto 100%;}
/* Creating the 2 column layout using floating elements once again */
.nav li {display: block;float: left;width: 50%;}
/* Adding some padding to make the elements look nicer*/
.nav a {padding: 0.8em;}
/* Displaying the icons on the left, and the text on the right side using inlin-block*/
.nav li span {display: inline-block;}
}
/* Styling the toggle menu link and hiding it */
.nav .navtoogle{
display: none;
width: 100%;
padding: 0.5em 0.5em 0.8em;
font-family: 'Lato',Calibri,Arial,sans-serif;
font-weight: normal;
text-align: left;
color: rgb(7, 16, 15);
font-size: 1.2em;
background: none;
border: none;
border-bottom: 4px solid rgb(221, 221, 221);
cursor: pointer;
}
/* Adapter la taille de police pour les petits écrans*/
@media (min-width: 32.5em) and (max-width: 38.688em) {
.nav li span {
font-size: 0.9em;
}
}
/* Version mobile */
@media (max-width: 32.438em) {
/* Les fonds d'écran s'étirent à 100% sur leur axe horizontal */
.bg1,.bg2,.bg3,.bg4{background-size:auto 100%;}
/* Unhiding the styled menu link */
.nav .navtoogle{margin: 0;display: block;}
/* Animating the height of the navigation when the button is clicked */
/* When JavaScript is disabled, we hide the menu */
.no-js .nav ul {max-height: 30em;overflow: hidden;}
/* When JavaScript is enabled, we hide the menu */
.js .nav ul {max-height: 0em;overflow: hidden;}
/* Displaying the menu when the user has clicked on the button*/
.js .nav .active + ul {
max-height: 30em;
overflow: hidden;
-webkit-transition: max-height .4s;
-moz-transition: max-height .4s;
-o-transition: max-height .4s;
-ms-transition: max-height .4s;
transition: max-height .4s;
}
/* Adapting the layout of the menu for smaller screens : icon on the left and text on the right*/
.nav li span {display: inline-block;height: 100%;}
.nav a {padding: 0.5em;}
/* Ajout d'une bordure gauche de 8px avec une couleur différente pour chaque élément */
.nav li:nth-child(6n+1) {border-left: 8px solid rgb(174, 78, 1);}
.nav li:nth-child(6n+2) {border-left: 8px solid rgb(191, 117, 20);}
.nav li:nth-child(6n+3) {border-left: 8px solid rgb(13, 111, 150);}
.nav li:nth-child(6n+4) {border-left: 8px solid rgb(10, 75, 117);}
.nav li:nth-child(6n+5) {border-left: 8px solid rgb(16, 34, 44);}
.nav li:nth-child(6n+6) {border-left: 8px solid rgb(9, 18, 25);}
/* make the nav bigger on touch screens */
.touch .nav a {padding: 0.8em;}
}
| fedeB-IT-dept/fedeB_website | rescue/css/component.css | CSS | mit | 8,064 |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 25 16:20:12 2015
@author: Balázs Hidasi
@lastmodified: Loreto Parisi (loretoparisi at gmail dot com)
"""
import sys
import os
import numpy as np
import pandas as pd
import datetime as dt
# To redirect output to file
class Logger(object):
def __init__(self, filename="Default.log"):
self.terminal = sys.stdout
self.log = open(filename, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
sys.stdout = Logger( os.environ['HOME' ] + '/theano.log' )
PATH_TO_ORIGINAL_DATA = os.environ['HOME'] + '/'
PATH_TO_PROCESSED_DATA = os.environ['HOME'] + '/'
data = pd.read_csv(PATH_TO_ORIGINAL_DATA + 'yoochoose-clicks.dat', sep=',', header=None, usecols=[0,1,2], dtype={0:np.int32, 1:str, 2:np.int64})
data.columns = ['SessionId', 'TimeStr', 'ItemId']
data['Time'] = data.TimeStr.apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%fZ').timestamp()) #This is not UTC. It does not really matter.
del(data['TimeStr'])
session_lengths = data.groupby('SessionId').size()
data = data[np.in1d(data.SessionId, session_lengths[session_lengths>1].index)]
item_supports = data.groupby('ItemId').size()
data = data[np.in1d(data.ItemId, item_supports[item_supports>=5].index)]
session_lengths = data.groupby('SessionId').size()
data = data[np.in1d(data.SessionId, session_lengths[session_lengths>=2].index)]
tmax = data.Time.max()
session_max_times = data.groupby('SessionId').Time.max()
session_train = session_max_times[session_max_times < tmax-86400].index
session_test = session_max_times[session_max_times >= tmax-86400].index
train = data[np.in1d(data.SessionId, session_train)]
test = data[np.in1d(data.SessionId, session_test)]
test = test[np.in1d(test.ItemId, train.ItemId)]
tslength = test.groupby('SessionId').size()
test = test[np.in1d(test.SessionId, tslength[tslength>=2].index)]
print('Full train set\n\tEvents: {}\n\tSessions: {}\n\tItems: {}'.format(len(train), train.SessionId.nunique(), train.ItemId.nunique()))
train.to_csv(PATH_TO_PROCESSED_DATA + 'rsc15_train_full.txt', sep='\t', index=False)
print('Test set\n\tEvents: {}\n\tSessions: {}\n\tItems: {}'.format(len(test), test.SessionId.nunique(), test.ItemId.nunique()))
test.to_csv(PATH_TO_PROCESSED_DATA + 'rsc15_test.txt', sep='\t', index=False)
tmax = train.Time.max()
session_max_times = train.groupby('SessionId').Time.max()
session_train = session_max_times[session_max_times < tmax-86400].index
session_valid = session_max_times[session_max_times >= tmax-86400].index
train_tr = train[np.in1d(train.SessionId, session_train)]
valid = train[np.in1d(train.SessionId, session_valid)]
valid = valid[np.in1d(valid.ItemId, train_tr.ItemId)]
tslength = valid.groupby('SessionId').size()
valid = valid[np.in1d(valid.SessionId, tslength[tslength>=2].index)]
print('Train set\n\tEvents: {}\n\tSessions: {}\n\tItems: {}'.format(len(train_tr), train_tr.SessionId.nunique(), train_tr.ItemId.nunique()))
train_tr.to_csv(PATH_TO_PROCESSED_DATA + 'rsc15_train_tr.txt', sep='\t', index=False)
print('Validation set\n\tEvents: {}\n\tSessions: {}\n\tItems: {}'.format(len(valid), valid.SessionId.nunique(), valid.ItemId.nunique()))
valid.to_csv(PATH_TO_PROCESSED_DATA + 'rsc15_train_valid.txt', sep='\t', index=False) | loretoparisi/docker | theano/rsc15/preprocess.py | Python | mit | 3,325 |
# lecture-02 2018-01-29
* add buttons for handouts
* add additional content related to Open GIS
* add speakerdeck integration
# lecture-02 2018-01-28
* add initial site with youtube video for lecture prep replication embedded
# lecture-02 2018-01-02
* add `NEWS_SITE.md` for tracking updates to the course site, *but site for this lecture is not live*.
| slu-soc5650/week-02 | NEWS_SITE.md | Markdown | mit | 358 |
# Rustic Pizza
A collection of pizzeria web apps,
written in Rust, with each webapp using different web frameworks.
* https://rust-lang.org
* https://rustup.rs
* https://doc.rust-lang.org/book/README.html
* https://doc.rust-lang.org/std/
* http://rustbyexample.com/index.html
* https://aturon.github.io/
* http://www.arewewebyet.org
* https://github.com/flosse/rust-web-framework-comparison
| flurdy/rustic-pizza | README.md | Markdown | mit | 394 |
<?php
namespace PSR2R\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;
use PSR2R\Tools\AbstractSniff;
use PSR2R\Tools\Traits\CommentingTrait;
use PSR2R\Tools\Traits\SignatureTrait;
/**
* Methods always need doc blocks.
* Constructor and destructor may not have one if they do not have arguments.
*/
class DocBlockSniff extends AbstractSniff {
use CommentingTrait;
use SignatureTrait;
/**
* @inheritDoc
*/
public function register(): array {
return [T_FUNCTION];
}
/**
* @inheritDoc
*/
public function process(File $phpcsFile, $stackPtr): void {
$tokens = $phpcsFile->getTokens();
$nextIndex = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, true);
if ($nextIndex === false) {
return;
}
if ($tokens[$nextIndex]['content'] === '__construct' || $tokens[$nextIndex]['content'] === '__destruct') {
$this->checkConstructorAndDestructor($phpcsFile, $stackPtr);
return;
}
// Don't mess with closures
$prevIndex = $phpcsFile->findPrevious(Tokens::$emptyTokens, $stackPtr - 1, null, true);
if (!$this->isGivenKind(Tokens::$methodPrefixes, $tokens[$prevIndex])) {
return;
}
$docBlockEndIndex = $this->findRelatedDocBlock($phpcsFile, $stackPtr);
if ($docBlockEndIndex) {
return;
}
// We only look for void methods right now
$returnType = $this->detectReturnTypeVoid($phpcsFile, $stackPtr);
if ($returnType === null) {
$phpcsFile->addError('Method does not have a doc block: ' . $tokens[$nextIndex]['content'] . '()', $nextIndex, 'DocBlockMissing');
return;
}
$fix = $phpcsFile->addFixableError('Method does not have a docblock with return void statement: ' . $tokens[$nextIndex]['content'], $nextIndex, 'ReturnVoidMissing');
if (!$fix) {
return;
}
$this->addDocBlock($phpcsFile, $stackPtr, $returnType);
}
/**
* @param \PHP_CodeSniffer\Files\File $phpcsFile
* @param int $index
* @param string $returnType
*
* @return void
*/
protected function addDocBlock(File $phpcsFile, int $index, string $returnType): void {
$tokens = $phpcsFile->getTokens();
$firstTokenOfLine = $this->getFirstTokenOfLine($tokens, $index);
$prevContentIndex = $phpcsFile->findPrevious(T_WHITESPACE, $firstTokenOfLine - 1, null, true);
if ($prevContentIndex === false) {
return;
}
if ($tokens[$prevContentIndex]['type'] === 'T_ATTRIBUTE_END') {
$firstTokenOfLine = $this->getFirstTokenOfLine($tokens, $prevContentIndex);
}
$indentation = $this->getIndentationWhitespace($phpcsFile, $index);
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->addNewlineBefore($firstTokenOfLine);
$phpcsFile->fixer->addContentBefore($firstTokenOfLine, $indentation . ' */');
$phpcsFile->fixer->addNewlineBefore($firstTokenOfLine);
$phpcsFile->fixer->addContentBefore($firstTokenOfLine, $indentation . ' * @return ' . $returnType);
$phpcsFile->fixer->addNewlineBefore($firstTokenOfLine);
$phpcsFile->fixer->addContentBefore($firstTokenOfLine, $indentation . '/**');
$phpcsFile->fixer->endChangeset();
}
/**
* @param \PHP_CodeSniffer\Files\File $phpcsFile
* @param int $stackPtr
*
* @return void
*/
protected function checkConstructorAndDestructor(File $phpcsFile, int $stackPtr): void {
$docBlockEndIndex = $this->findRelatedDocBlock($phpcsFile, $stackPtr);
if ($docBlockEndIndex) {
return;
}
$methodSignature = $this->getMethodSignature($phpcsFile, $stackPtr);
$arguments = count($methodSignature);
if (!$arguments) {
return;
}
$phpcsFile->addError('Missing doc block for method', $stackPtr, 'ConstructDesctructMissingDocBlock');
}
/**
* @param \PHP_CodeSniffer\Files\File $phpcsFile
* @param int $docBlockStartIndex
* @param int $docBlockEndIndex
*
* @return int|null
*/
protected function findDocBlockReturn(File $phpcsFile, int $docBlockStartIndex, int $docBlockEndIndex): ?int {
$tokens = $phpcsFile->getTokens();
for ($i = $docBlockStartIndex + 1; $i < $docBlockEndIndex; $i++) {
if (!$this->isGivenKind(T_DOC_COMMENT_TAG, $tokens[$i])) {
continue;
}
if ($tokens[$i]['content'] !== '@return') {
continue;
}
return $i;
}
return null;
}
/**
* For right now we only try to detect void.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile
* @param int $index
*
* @return string|null
*/
protected function detectReturnTypeVoid(File $phpcsFile, int $index): ?string {
$tokens = $phpcsFile->getTokens();
$type = 'void';
if (empty($tokens[$index]['scope_opener'])) {
return null;
}
$methodStartIndex = $tokens[$index]['scope_opener'];
$methodEndIndex = $tokens[$index]['scope_closer'];
for ($i = $methodStartIndex + 1; $i < $methodEndIndex; ++$i) {
if ($this->isGivenKind([T_FUNCTION, T_CLOSURE], $tokens[$i])) {
$endIndex = $tokens[$i]['scope_closer'];
if (!empty($tokens[$i]['nested_parenthesis'])) {
$endIndex = array_pop($tokens[$i]['nested_parenthesis']);
}
$i = $endIndex;
continue;
}
if (!$this->isGivenKind([T_RETURN], $tokens[$i])) {
continue;
}
$nextIndex = $phpcsFile->findNext(Tokens::$emptyTokens, $i + 1, null, true);
if (!$this->isGivenKind(T_SEMICOLON, $tokens[$nextIndex])) {
return null;
}
}
return $type;
}
}
| php-fig-rectified/psr2r-sniffer | PSR2R/Sniffs/Commenting/DocBlockSniff.php | PHP | mit | 5,275 |
(function() {
'use strict';
process.env.debug_sql = true;
var Class = require('ee-class')
, log = require('ee-log')
, assert = require('assert')
, fs = require('fs')
, QueryContext = require('related-query-context')
, ORM = require('related');
var TimeStamps = require('../')
, sqlStatments
, extension
, orm
, db;
// sql for test db
sqlStatments = fs.readFileSync(__dirname+'/db.postgres.sql').toString().split(';').map(function(input){
return input.trim().replace(/\n/gi, ' ').replace(/\s{2,}/g, ' ')
}).filter(function(item){
return item.length;
});
describe('Travis', function(){
it('should have set up the test db', function(done){
var config;
try {
config = require('../config.js').db
} catch(e) {
config = [{
type: 'postgres'
, schema: 'related_timestamps_test'
, database : 'test'
, hosts: [{}]
}];
}
this.timeout(5000);
orm = new ORM(config);
done();
});
it('should be able to drop & create the testing schema ('+sqlStatments.length+' raw SQL queries)', function(done){
orm.getDatabase('related_timestamps_test').getConnection('write').then((connection) => {
return new Promise((resolve, reject) => {
let exec = (index) => {
if (sqlStatments[index]) {
connection.query(new QueryContext({sql:sqlStatments[index]})).then(() => {
exec(index + 1);
}).catch(reject);
}
else resolve();
}
exec(0);
});
}).then(() => {
done();
}).catch(done);
});
});
var expect = function(val, cb){
return function(err, result){
try {
assert.equal(JSON.stringify(result), val);
} catch (err) {
return cb(err);
}
cb();
}
};
describe('The TimeStamps Extension', function() {
var oldDate;
it('should not crash when instatiated', function() {
db = orm.related_timestamps_test;
extension = new TimeStamps();
});
it('should not crash when injected into the orm', function(done) {
orm.use(extension);
orm.load(done);
});
it('should set correct timestamps when inserting a new record', function(done) {
db = orm.related_timestamps_test;
new db.event().save(function(err, evt) {
if (err) done(err);
else {
assert.notEqual(evt.created, null);
assert.notEqual(evt.updated, null);
assert.equal(evt.deleted, null);
oldDate = evt.updated;
done();
}
});
});
it('should set correct timestamps when updating a record', function(done) {
// wait, we nede a new timestamp
setTimeout(function() {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
evt.name = 'func with timestamps? no, that ain\'t fun!';
evt.save(function(err){
assert.notEqual(evt.created, null);
assert.notEqual(evt.updated, null);
assert.notEqual(evt.updated.toUTCString(), oldDate.toUTCString());
assert.equal(evt.deleted, null);
done();
});
}
});
}, 1500);
});
it('should set correct timestamps when deleting a record', function(done) {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
evt.delete(function(err) {
assert.notEqual(evt.created, null);
assert.notEqual(evt.updated, null);
assert.notEqual(evt.deleted, null);
done();
});
}
});
});
it('should not return soft deleted records when not requested', function(done) {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
assert.equal(evt, undefined);
done();
}
});
});
it('should return soft deleted records when requested', function(done) {
db.event({id:1}, ['*']).includeSoftDeleted().findOne(function(err, evt) {
if (err) done(err);
else {
assert.equal(evt.id, 1);
done();
}
});
});
it('should hard delete records when requested', function(done) {
db.event({id:1}, ['*']).includeSoftDeleted().findOne(function(err, evt) {
if (err) done(err);
else {
evt.hardDelete(function(err) {
if (err) done(err);
else {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
assert.equal(evt, undefined);
done();
}
});
}
});
}
});
});
it('should not load softdeleted references', function(done) {
new db.event({
name: 'so what'
, eventInstance: [new db.eventInstance({startdate: new Date(), deleted: new Date()})]
}).save(function(err, evt) {
if (err) done(err);
else {
db.event(['*'], {id:evt.id}).fetchEventInstance(['*']).findOne(function(err, event) {
if (err) done(err);
else {
assert.equal(event.eventInstance.length, 0);
done();
}
});
}
});
})
it ('should work when using bulk deletes', function(done) {
new db.event({name: 'bulk delete 1'}).save().then(function() {
return new db.event({name: 'bulk delete 2'}).save()
}).then(function() {
return new db.event({name: 'bulk delete 3'}).save()
}).then(function() {
return db.event('id').find();
}).then(function(records) {
if (JSON.stringify(records) !== '[{"id":2},{"id":3},{"id":4},{"id":5}]') return Promise.reject(new Error('Expected «[{"id":2},{"id":3},{"id":4},{"id":5}]», got «'+JSON.stringify(records)+'»!'))
else return db.event({
id: ORM.gt(3)
}).delete();
}).then(function() {
return db.event('id').find();
}).then(function(emptyList) {
if (JSON.stringify(emptyList) !== '[{"id":2},{"id":3}]') return Promise.reject(new Error('Expected «[{"id":2},{"id":3}]», got «'+JSON.stringify(emptyList)+'»!'))
else return db.event('id').includeSoftDeleted().find();
}).then(function(list) {
if (JSON.stringify(list) !== '[{"id":2},{"id":3},{"id":4},{"id":5}]') return Promise.reject(new Error('Expected «[{"id":2},{"id":3},{"id":4},{"id":5}]», got «'+JSON.stringify(list)+'»!'))
done();
}).catch(done);
})
});
})();
| eventEmitter/related-timestamps | test/extension.js | JavaScript | mit | 8,381 |
#!/usr/bin/env ruby
require 'tasklist'
during '2010 September' do
on '2010-09-03' do
task 'Take out garbage'
task 'Wash car'
end
on '2010-09-02' do
task 'Create tasklist DSL', '09:15:56', '', 'admin', 'done'
task 'Push tasklist to github', '09:34:00', '09:38:04', 'github'
end
end
| kevincolyar/tasklist | example.rb | Ruby | mit | 310 |
var passport = require('passport');
var WebIDStrategy = require('passport-webid').Strategy;
var tokens = require('../../util/tokens');
var ids = require('../../util/id');
var console = require('../../log');
var createError = require('http-errors');
var dateUtils = require('../../util/date');
var url = require('url');
function loadStrategy(conf, entityStorageConf) {
var auth_type = "webid";
var db = require('../../db')(conf, entityStorageConf);
var enabled = conf.enabledStrategies.filter(function (v) {
return (v === auth_type);
});
if (enabled.length === 0) {
console.log('ignoring ' + auth_type + ' strategy for user authentication. Not enabled in the configuration');
return false;
} else {
try {
passport.use(auth_type, new WebIDStrategy(
function (webid, certificate, req, done) {
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
var id = {
user_name: webid,
auth_type: auth_type
};
var oauth2ReturnToParsed = url.parse(req.session.returnTo, true).query;
console.log(" sesion in strategy " + auth_type + JSON.stringify(oauth2ReturnToParsed));
console.log(" client id from session in " + auth_type + JSON.stringify(oauth2ReturnToParsed.client_id));
console.log(" response_type for oauth2 in " + auth_type + JSON.stringify(oauth2ReturnToParsed.response_type));
var accessToken = tokens.uid(30);
var d = Date.parse(certificate.valid_to);
var default_exp = dateUtils.dateToEpochMilis(d);
db.users.findByUsernameAndAuthType(webid, auth_type, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
db.accessTokens.saveOauth2Token(accessToken, user.id, oauth2ReturnToParsed.client_id, "bearer", [conf.gateway_id], default_exp, null, oauth2ReturnToParsed.response_type, function (err) {
if (err) {
return done(err);
}
return done(null, user);
});
});
}
));
console.log('finished registering passport ' + auth_type + ' strategy');
return true;
} catch (e) {
console.log('FAIL TO register a strategy');
console.log('ERROR: error loading ' + auth_type + ' passport strategy: ' + e);
return false;
}
}
}
module.exports = loadStrategy;
| Agile-IoT/agile-idm-web-ui | lib/auth/providers/webid.js | JavaScript | mit | 3,465 |
module AwsHelpers
module ElasticLoadBalancing
class CreateTag
def initialize(elastic_load_balancing_client, load_balancer_name, tag_key, tag_value)
@elastic_load_balancing_client = elastic_load_balancing_client
@load_balancer_name = load_balancer_name
@tag_key = tag_key
@tag_value = tag_value
end
def execute
resp = @elastic_load_balancing_client.add_tags({load_balancer_names: [@load_balancer_name],
tags: [{key: @tag_key, value: @tag_value}]
})
end
end
end
end
| MYOB-Technology/aws_helpers | lib/aws_helpers/elastic_load_balancing/create_tag.rb | Ruby | mit | 652 |
export declare class Console {
private static quiet;
private static debug;
private static verbose;
static Log(text: any): void;
private static readonly Timestamp;
static Debug(text: any): void;
static Verbose(text: any): void;
static Error(text: any): void;
static Exit(reason: any): void;
}
| APEEYEDOTCOM/hapi-bells | node_modules/autorest/console.d.ts | TypeScript | mit | 328 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\CoreBundle\Command;
use Sylius\Component\Core\Model\AdminUserInterface;
use Sylius\Component\User\Repository\UserRepositoryInterface;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Webmozart\Assert\Assert;
final class SetupCommand extends AbstractInstallCommand
{
/**
* {@inheritdoc}
*/
protected function configure(): void
{
$this
->setName('sylius:install:setup')
->setDescription('Sylius configuration setup.')
->setHelp(<<<EOT
The <info>%command.name%</info> command allows user to configure basic Sylius data.
EOT
)
;
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output): void
{
$currency = $this->get('sylius.setup.currency')->setup($input, $output, $this->getHelper('question'));
$locale = $this->get('sylius.setup.locale')->setup($input, $output);
$this->get('sylius.setup.channel')->setup($locale, $currency);
$this->setupAdministratorUser($input, $output, $locale->getCode());
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @param string $localeCode
*/
protected function setupAdministratorUser(InputInterface $input, OutputInterface $output, string $localeCode): void
{
$outputStyle = new SymfonyStyle($input, $output);
$outputStyle->writeln('Create your administrator account.');
$userManager = $this->get('sylius.manager.admin_user');
$userFactory = $this->get('sylius.factory.admin_user');
try {
$user = $this->configureNewUser($userFactory->createNew(), $input, $output);
} catch (\InvalidArgumentException $exception) {
return;
}
$user->setEnabled(true);
$user->setLocaleCode($localeCode);
$userManager->persist($user);
$userManager->flush();
$outputStyle->writeln('<info>Administrator account successfully registered.</info>');
$outputStyle->newLine();
}
/**
* @param AdminUserInterface $user
* @param InputInterface $input
* @param OutputInterface $output
*
* @return AdminUserInterface
*/
private function configureNewUser(
AdminUserInterface $user,
InputInterface $input,
OutputInterface $output
): AdminUserInterface {
/** @var UserRepositoryInterface $userRepository */
$userRepository = $this->getAdminUserRepository();
if ($input->getOption('no-interaction')) {
Assert::null($userRepository->findOneByEmail('[email protected]'));
$user->setEmail('[email protected]');
$user->setUsername('sylius');
$user->setPlainPassword('sylius');
return $user;
}
$email = $this->getAdministratorEmail($input, $output);
$user->setEmail($email);
$user->setUsername($this->getAdministratorUsername($input, $output, $email));
$user->setPlainPassword($this->getAdministratorPassword($input, $output));
return $user;
}
/**
* @return Question
*/
private function createEmailQuestion(): Question
{
return (new Question('E-mail: '))
->setValidator(function ($value) {
/** @var ConstraintViolationListInterface $errors */
$errors = $this->get('validator')->validate((string) $value, [new Email(), new NotBlank()]);
foreach ($errors as $error) {
throw new \DomainException($error->getMessage());
}
return $value;
})
->setMaxAttempts(3)
;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return string
*/
private function getAdministratorEmail(InputInterface $input, OutputInterface $output): string
{
/** @var QuestionHelper $questionHelper */
$questionHelper = $this->getHelper('question');
/** @var UserRepositoryInterface $userRepository */
$userRepository = $this->getAdminUserRepository();
do {
$question = $this->createEmailQuestion();
$email = $questionHelper->ask($input, $output, $question);
$exists = null !== $userRepository->findOneByEmail($email);
if ($exists) {
$output->writeln('<error>E-Mail is already in use!</error>');
}
} while ($exists);
return $email;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @param string $email
*
* @return string
*/
private function getAdministratorUsername(InputInterface $input, OutputInterface $output, string $email): string
{
/** @var QuestionHelper $questionHelper */
$questionHelper = $this->getHelper('question');
/** @var UserRepositoryInterface $userRepository */
$userRepository = $this->getAdminUserRepository();
do {
$question = new Question('Username (press enter to use email): ', $email);
$username = $questionHelper->ask($input, $output, $question);
$exists = null !== $userRepository->findOneBy(['username' => $username]);
if ($exists) {
$output->writeln('<error>Username is already in use!</error>');
}
} while ($exists);
return $username;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return mixed
*/
private function getAdministratorPassword(InputInterface $input, OutputInterface $output)
{
/** @var QuestionHelper $questionHelper */
$questionHelper = $this->getHelper('question');
$validator = $this->getPasswordQuestionValidator();
do {
$passwordQuestion = $this->createPasswordQuestion('Choose password:', $validator);
$confirmPasswordQuestion = $this->createPasswordQuestion('Confirm password:', $validator);
$password = $questionHelper->ask($input, $output, $passwordQuestion);
$repeatedPassword = $questionHelper->ask($input, $output, $confirmPasswordQuestion);
if ($repeatedPassword !== $password) {
$output->writeln('<error>Passwords do not match!</error>');
}
} while ($repeatedPassword !== $password);
return $password;
}
/**
* @return \Closure
*/
private function getPasswordQuestionValidator(): \Closure
{
return function ($value) {
/** @var ConstraintViolationListInterface $errors */
$errors = $this->get('validator')->validate($value, [new NotBlank()]);
foreach ($errors as $error) {
throw new \DomainException($error->getMessage());
}
return $value;
};
}
/**
* @param string $message
* @param \Closure $validator
*
* @return Question
*/
private function createPasswordQuestion(string $message, \Closure $validator): Question
{
return (new Question($message))
->setValidator($validator)
->setMaxAttempts(3)
->setHidden(true)
->setHiddenFallback(false)
;
}
/**
* @return UserRepositoryInterface
*/
private function getAdminUserRepository(): UserRepositoryInterface
{
return $this->get('sylius.repository.admin_user');
}
}
| vihuvac/Sylius | src/Sylius/Bundle/CoreBundle/Command/SetupCommand.php | PHP | mit | 8,226 |
import { Nibble, UInt4 } from '../types'
/**
* Returns a Nibble (0-15) which equals the given bits.
*
* @example
* byte.write([1,0,1,0]) => 10
*
* @param {Array} nibble 4-bit unsigned integer
* @return {Number}
*/
export default (nibble: Nibble): UInt4 => {
if (!Array.isArray(nibble) || nibble.length !== 4)
throw new RangeError('invalid array length')
let result: UInt4 = 0
for (let i: number = 0; i < 4; i++) if (nibble[3 - i]) result |= 1 << i
return <UInt4>result
}
| dodekeract/bitwise | source/nibble/write.ts | TypeScript | mit | 489 |
import { Injectable } from '@angular/core';
import { DataService } from '../../../_service/dataconnect';
import { Router } from '@angular/router';
@Injectable()
export class WarehouseViewService {
constructor(private _dataserver: DataService, private _router: Router) { }
getwarehouseTransfer(req: any) {
return this._dataserver.post("getwarehouseTransfer", req);
}
} | masagatech/erpv1 | src/app/_service/warehousestock/view/view-service.ts | TypeScript | mit | 390 |
{% extends "base.html" %}
{% load static %}
{% load template_extras %}
{% block title %}Analyse{% endblock %}
{% block active_class %}analyse{% endblock %}
{% block extra_css %}
<link href="{% static 'css/select2.min.css' %}" rel="stylesheet">
<link href="{% static 'css/jquery.nouislider.css' %}" rel="stylesheet">
<link href="{% static 'css/jquery.nouislider.pips.css' %}" rel="stylesheet">
<link href='https://api.tiles.mapbox.com/mapbox.js/v2.2.1/mapbox.css' rel='stylesheet' />
{% endblock %}
{% block content %}
<h1>Search GP prescribing data</h1>
<p>Search 700 million rows of prescribing data, and get prescribing information by practice, PCN, CCG, STP or regional team. You can search for any numerator over any denominator.</p>
<p>Unsure how to create your own searches? <a target="_blank" href="{% url 'analyse' %}#numIds=0212000AA&denomIds=2.12">Try an example</a>, <a target="_blank" href="http://openprescribing.net/docs/analyse">read more</a> about how to use this tool, check our <a target="_blank" href="{% url 'faq' %}">FAQs</a> and read our <a href='https://ebmdatalab.net/prescribing-data-bnf-codes/'> what is a BNF code blog</a>.</p>
<div class="alert alert-danger" role="alert" style="margin-top: 10px;" id="old-browser">
<strong>Warning!</strong> It looks like you're using an older browser. This form may be very slow, as it has to crunch through a lot of data to render the graphs. If you can, please try again with a modern browser.
</div>
{% include '_get_in_touch.html' %}
<div id="loading-form">
<p>Loading search form...</p>
</div>
<div id="analyse-options" class="invisible">
<div class="form-row">
<div class="col left">
<span class="help" id="numerator-help" data-toggle="popover" data-trigger="hover" data-placement="auto top">See prescribing of:</span>
<div class="hidden" id="numerator-help-text">You can add BNF sections, chemicals, products or product format.<br/>For example:
<ul>
<li><em>Atorvastatin</em> will show all prescribing on the chemical, across multiple products</li>
<li><em>Lipitor (branded)</em> will show all prescribing on just that product</li>
<li><em>Lipitor_Tab 20mg</em> will show all prescribing on just that product format.</li>
</ul>
Add multiple items to see total prescribing on those items.
</div>
<!-- <span class="icon-up"></span>with a y-axis of: -->
</div>
<div class="col middle">
<select style="width: 100%" id="num" class="form-select not-searchable">
<option value="chemical" selected>drugs or BNF sections</option>
<!-- <option value="all">everything</option> -->
</select>
</div>
<div class="col right">
<div id="numIds-wrapper">
<select id="numIds" multiple="multiple" style="width: 100%"></select>
</div>
</div>
</div>
<div class="form-row">
<div class="col left">
<span class="help" id="denominator-help" data-toggle="popover" data-trigger="hover" data-placement="auto top">versus:</span>
<div class="hidden" id="denominator-help-text">Add another BNF section or drug as a comparator.<br/>Or use standardised prescribing units (STAR-PUs) as an approximate measure of prescribing need.</div>
<!-- <span class="icon-right"></span>and an x-axis of: -->
</div>
<div class="col middle">
<select style="width: 100%" id="denom" class="form-select not-searchable">
<option value="nothing" selected>nothing</option>
<option value="chemical">drugs or BNF sections</option>
<option value="total_list_size" selected>total list size</option>
<option value="star_pu.oral_antibacterials_item">STAR-PUs for antibiotics</option>
</select>
</div>
<div class="col right">
<div id="denomIds-wrapper">
<select id="denomIds" multiple="multiple" style="width: 100%"></select>
</div>
</div>
</div>
<div class="form-row">
<div class="col left">highlighting:</div>
<div class="col middle">
<select style="width: 100%" id="org" class="form-select not-searchable">
<!-- <option value="all" selected>everyone</option> -->
<option value="practice">a practice or practices</option>
<option value="CCG">a CCG or CCGs</option>
{% if pcns_enabled %}<option value="pcn">a PCN or PCNs</option>{% endif %}
<option value="stp">an STP or STPs</option>
<option value="regional_team">an NHS England Region</option>
</select>
</div>
<div class="col right">
<div id="orgIds-container" style="display: none">
<select style="width: 100%" id="orgIds" multiple="multiple">
</select>
<p class="help-block" id="org-help">Hint: add a CCG to see all its practices</p>
</div>
</div>
</div>
<p>
<a href="/docs/analyse/">Tips on using this search</a>
</p>
<div>
<button type="button" id="update" class="btn btn-primary" type="submit" data-loading-text="Fetching data..." data-loaded-text="Show me the data!">Show me the data!</button>
</div>
</div> <!-- /#analyse-options -->
<div class="loading-wrapper">
<hr/>
<img class="loading" src="{% static 'img/logo.svg' %}" onerror="this.src='{% static "img/ajax-loader.gif" %}';this.onerror=null;" title="Loading icon">
<br/>Fetching data...
</div>
<div id="error">
<hr/><p id='error-message'></p>
</div>
<div id="results">
<hr/>
{% include '_share_button.html' %}
<ul id="tabs" class="nav nav-tabs" role="tablist">
<li role="presentation" id="summary-tab" class="summary-tab active saveable">
<a href="#summary-panel" data-target="#summary-panel" aria-controls="settings" role="tab" data-toggle="tab">Show summary</a>
</li>
<li role="presentation" id="chart-tab" class="chart-tab hidden saveable">
<a href="#chart-panel" data-target="#chart-panel" aria-controls="settings" role="tab" data-toggle="tab">Time series</a>
</li>
<li role="presentation" id="map-tab" class="map-tab hidden saveable">
<a href="#map-panel" data-target="#map-panel" aria-controls="settings" role="tab" data-toggle="tab">Map</a>
</li>
<li role="presentation" id="data-tab" class="data-tab">
<a href="#data-panel" data-target="#data-panel" aria-controls="settings" role="tab" data-toggle="tab">Download CSV <span class="glyphicon glyphicon-download-alt" aria-hidden="true"></span></a>
</li>
</ul>
<div class="tab-content">
<!-- Time slider and items toggle -->
<div id="chart-options">
<div id="chart-options-wrapper">
{# Play button temporarily disabled until we fix issue #1368 #}
{#<div id="play-slider" alt="Animate time series" class="glyphicon glyphicon-play-circle"></div>#}
<div id="slider-wrapper"><div id="chart-date-slider"></div></div>
<div id="items-spending-toggle" class="btn-group btn-toggle" aria-label="Show spending or items on graph">
<button class="btn btn-default btn-sm" data-type="actual_cost">spending</button>
<button class="btn btn-info btn-sm" data-type="items">items</button>
</div>
</div>
</div>
<!-- Tab content -->
<div role="tabpanel" class="tab-pane fade in active" id="summary-panel" class="summary-tab">
<div class="chart-title-wrapper">
<div class="chart-title"></div>
<div class="chart-sub-title"></div>
</div>
<div class="chart-container">
<div id="summarychart"></div>
<div class="practice-warning">
For clarity, practice graphs and maps only show standard GP practices, and exclude non-standard settings like prisons, out-of-hours services, etc.
</div>
<div class="highcharts-attribution">
Built with <a href="http://www.highcharts.com/">Highcharts</a>
</div>
</div>
{% include '_outlier_toggle.html' %}
</div>
<div role="tabpanel" class="tab-pane fade" id="chart-panel" class="chart-tab">
<div class="chart-container">
<div id="chart"></div>
<div class="practice-warning">
For clarity, practice graphs and maps only show standard GP practices, and exclude non-standard settings like prisons, out-of-hours services, etc.
</div>
<div class="highcharts-attribution">Built with <a href="http://www.highcharts.com/">Highcharts</a></div>
</div>
{% include '_outlier_toggle.html' %}
</div>
<div role="tabpanel" class="tab-pane fade" id="map-panel" class="map-tab">
<div class="chart-title-wrapper">
<p class="chart-title"></p>
<p class="chart-sub-title"></p>
</div>
<div class="clearfix">
<div id="map-wrapper">
<div id="map"></div>
</div>
<div class="practice-warning">
For clarity, practice graphs and maps only show standard GP
practices, and exclude non-standard settings like prisons,
out-of-hours services, etc. CCG boundaries from
<a href="http://www.england.nhs.uk/resources/ccg-maps/">NHS England</a>.
Practice locations are approximate, based on postcode. Only practices
with a known location are shown here. PCN boundaries are illustrative
only.
</div>
</div>
{% include '_outlier_toggle.html' %}
</div>
<div role="tabpanel" class="tab-pane fade" id="data-panel" class="data-tab">
<p>
You are welcome to use data from this site in your academic
output with attribution. Please cite "OpenPrescribing.net, EBM
DataLab, University of Oxford, 2020" as the source for
academic attribution.</p>
<p>If you use data or images from this site online or in a
report, please link back to us. Your readers will then be able
to see live updates to the data you are interested in, and
explore other queries for themselves.</p>
<p><a id="data-link" download="data.csv" class="btn btn-info" href="#">Download as CSV <span id="data-rows-count"></span></a> </p>
</div>
</div>
<div id="js-summary-totals" class="panel panel-default" style="margin-top: 18px">
<div class="panel-heading">
Total prescribing for <em class="js-friendly-numerator"></em>
across <span class="js-orgs-description"></span>
</div>
<table class="table">
<tr>
<th></th>
<th class="text-right js-selected-month"></th>
<th class="text-right">Financial YTD (<span class="js-financial-year-range"></span>)</th>
<th class="text-right">Last 12 months (<span class="js-year-range"></span>)</th>
</tr>
<tr>
<th>Cost (£)</th>
<td class="text-right js-cost-month-total"></td>
<td class="text-right js-cost-financial-year-total"></td>
<td class="text-right js-cost-year-total"></td>
</tr>
<tr>
<th>Items</th>
<td class="text-right js-items-month-total"></td>
<td class="text-right js-items-financial-year-total"></td>
<td class="text-right js-items-year-total"></td>
</tr>
</table>
</div>
</div>
<br/>
{% include '_alert_signup_form.html' with alert_type='analyse'%}
<p>Read our notes on <a href="{% url 'faq' %}">understanding the data</a>. Found something interesting, or a bug? Get in touch: <a href="mailto:{{ SUPPORT_TO_EMAIL }}" class="feedback-show">{{ SUPPORT_TO_EMAIL}}</a></p>
{% endblock %}
{% block extra_js %}
<!--[if !IE 8]><!-->
<script src="{% static 'js/clipboard.min.js' %}"></script>
<!--<![endif]-->
{% conditional_js 'analyse-form' %}
{% endblock %}
| ebmdatalab/openprescribing | openprescribing/templates/analyse.html | HTML | mit | 11,993 |
<!doctype html>
<html class="theme-next pisces use-motion">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<meta name="google-site-verification" content="hURnC-1VtFyi-v7OYQhy-5eOj-XZW3BAIs6iqzQcQj8" />
<link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>
<link href='//fonts.googleapis.com/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.5.0" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=5.0.0" rel="stylesheet" type="text/css" />
<meta name="keywords" content="日记,情感," />
<link rel="alternate" href="/atom.xml" title="HankCoder's Space" type="application/atom+xml" />
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.0" />
<meta name="description" content="今天手贱,把笔记本的键盘弄坏了,导致电脑不能用,只好花时间把我写博客的环境搬到MAC上来了,不过还好,以前折腾的够多,这次只花了几分钟就把环境搭建好了。开始写东西了,哈哈。
今天阅读了三毛的三篇散文集:
月河
极乐鸟
雨季不再来
在很久以前,我的世界里只有那xx实战,xx源码剖析等这些书籍,但这些书籍总让人感觉很枯燥,久而久之感觉自己的思维想象空间变的很狭窄,总觉得自己的另一半大脑一直处于空闲">
<meta property="og:type" content="article">
<meta property="og:title" content="随手记20170118">
<meta property="og:url" content="http://HankCoder.github.io/2017/01/17/随手记20170118/index.html">
<meta property="og:site_name" content="HankCoder's Space">
<meta property="og:description" content="今天手贱,把笔记本的键盘弄坏了,导致电脑不能用,只好花时间把我写博客的环境搬到MAC上来了,不过还好,以前折腾的够多,这次只花了几分钟就把环境搭建好了。开始写东西了,哈哈。
今天阅读了三毛的三篇散文集:
月河
极乐鸟
雨季不再来
在很久以前,我的世界里只有那xx实战,xx源码剖析等这些书籍,但这些书籍总让人感觉很枯燥,久而久之感觉自己的思维想象空间变的很狭窄,总觉得自己的另一半大脑一直处于空闲">
<meta property="og:updated_time" content="2017-01-17T16:32:23.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="随手记20170118">
<meta name="twitter:description" content="今天手贱,把笔记本的键盘弄坏了,导致电脑不能用,只好花时间把我写博客的环境搬到MAC上来了,不过还好,以前折腾的够多,这次只花了几分钟就把环境搭建好了。开始写东西了,哈哈。
今天阅读了三毛的三篇散文集:
月河
极乐鸟
雨季不再来
在很久以前,我的世界里只有那xx实战,xx源码剖析等这些书籍,但这些书籍总让人感觉很枯燥,久而久之感觉自己的思维想象空间变的很狭窄,总觉得自己的另一半大脑一直处于空闲">
<script type="text/javascript" id="hexo.configuration">
var NexT = window.NexT || {};
var CONFIG = {
scheme: 'Pisces',
sidebar: '[object Object]',
fancybox: true,
motion: true
};
</script>
<title> 随手记20170118 | HankCoder's Space </title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-67800719-1', 'auto');
ga('send', 'pageview');
</script>
<script type="text/javascript">
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "//hm.baidu.com/hm.js?7a046e8db6a48f2ab46b7812ba612789";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
<div class="container one-collumn sidebar-position-left page-post-detail ">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">HankCoder's Space</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle">Reading The Fucking Code</p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
<nav class="site-nav">
<ul id="menu" class="menu menu-left">
<li class="menu-item menu-item-home">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-home fa-fw"></i> <br />
首页
</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories" rel="section">
<i class="menu-item-icon fa fa-th fa-fw"></i> <br />
分类
</a>
</li>
<li class="menu-item menu-item-about">
<a href="/about" rel="section">
<i class="menu-item-icon fa fa-user fa-fw"></i> <br />
关于
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives" rel="section">
<i class="menu-item-icon fa fa-archive fa-fw"></i> <br />
归档
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags" rel="section">
<i class="menu-item-icon fa fa-tags fa-fw"></i> <br />
标签
</a>
</li>
<li class="menu-item menu-item-search">
<a href="#" class="st-search-show-outputs">
<i class="menu-item-icon fa fa-search fa-fw"></i> <br />
搜索
</a>
</li>
</ul>
<div class="site-search">
<form class="site-search-form">
<input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>
<script type="text/javascript">
(function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
(w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
})(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');
_st('install', 'Eq6Hisgzq2b_MSGwmySM','2.0.0');
</script>
</div>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<div id="posts" class="posts-expand">
<article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
随手记20170118
</h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time itemprop="dateCreated" datetime="2017-01-17T23:58:11+08:00" content="2017-01-17">
2017-01-17
</time>
</span>
<span class="post-category" >
|
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="https://schema.org/Thing">
<a href="/categories/我和她的故事/" itemprop="url" rel="index">
<span itemprop="name">我和她的故事</span>
</a>
</span>
</span>
<span class="post-comments-count">
|
<a href="/2017/01/17/随手记20170118/#comments" itemprop="discussionUrl">
<span class="post-comments-count ds-thread-count" data-thread-key="2017/01/17/随手记20170118/" itemprop="commentsCount"></span>
</a>
</span>
<span id="/2017/01/17/随手记20170118/"class="leancloud_visitors" data-flag-title="随手记20170118">
|
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>今天手贱,把笔记本的键盘弄坏了,导致电脑不能用,只好花时间把我<br>写博客的环境搬到MAC上来了,不过还好,以前折腾的够多,这次只花<br>了几分钟就把环境搭建好了。开始写东西了,哈哈。</p>
<p>今天阅读了三毛的三篇散文集:</p>
<ul>
<li><strong>月河</strong></li>
<li><strong>极乐鸟</strong></li>
<li><strong>雨季不再来</strong></li>
</ul>
<p>在很久以前,我的世界里只有那xx实战,xx源码剖析等这些书籍,<br>但这些书籍总让人感觉很枯燥,久而久之感觉自己的思维想象空间变的很<br>狭窄,总觉得自己的另一半大脑一直处于空闲状态,没有装任何东西,直到<br>现在我开始阅读一些文学书籍后,我能用心去体会故事主人公的情感经历,<br>去想像他当时经历的环境,来丰富自己的想象空间,为自己的大脑填充一些<br>不一样的东西。以后我会多挑一些好的文学作品好好阅读,感觉自己以前就<br>欠缺一点什么东西,现在终于找到了。真的是很感谢你。</p>
</div>
<footer class="post-footer">
<div class="post-tags">
<a href="/tags/日记/" rel="tag">#日记</a>
<a href="/tags/情感/" rel="tag">#情感</a>
</div>
<div class="post-nav">
<div class="post-nav-next post-nav-item">
<a href="/2017/01/16/随手记20170117/" rel="next" title="随手记20170117">
<i class="fa fa-chevron-left"></i> 随手记20170117
</a>
</div>
<div class="post-nav-prev post-nav-item">
<a href="/2017/01/18/随手记20170119/" rel="prev" title="随手记20170119">
随手记20170119 <i class="fa fa-chevron-right"></i>
</a>
</div>
</div>
</footer>
</article>
<div class="post-spread">
<!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<a class="jiathis_button_tsina"></a>
<a class="jiathis_button_tqq"></a>
<a class="jiathis_button_weixin"></a>
<a class="jiathis_button_cqq"></a>
<a class="jiathis_button_douban"></a>
<a class="jiathis_button_renren"></a>
<a class="jiathis_button_qzone"></a>
<a class="jiathis_button_kaixin001"></a>
<a class="jiathis_button_copy"></a>
<a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->
</div>
</div>
</div>
<p>热评文章</p>
<div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>
<div class="comments" id="comments">
<div class="ds-thread" data-thread-key="2017/01/17/随手记20170118/"
data-title="随手记20170118" data-url="http://HankCoder.github.io/2017/01/17/随手记20170118/">
</div>
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<ul class="sidebar-nav motion-element">
<li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
文章目录
</li>
<li class="sidebar-nav-overview" data-target="site-overview">
站点概览
</li>
</ul>
<section class="site-overview sidebar-panel ">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<img class="site-author-image" itemprop="image"
src="/images/default_avatar.jpg"
alt="HankCoder" />
<p class="site-author-name" itemprop="name">HankCoder</p>
<p class="site-description motion-element" itemprop="description">Android | Linux | RD | OpenSource ...</p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives">
<span class="site-state-item-count">16</span>
<span class="site-state-item-name">日志</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<a href="/categories">
<span class="site-state-item-count">6</span>
<span class="site-state-item-name">分类</span>
</a>
</div>
<div class="site-state-item site-state-tags">
<a href="/tags">
<span class="site-state-item-count">12</span>
<span class="site-state-item-name">标签</span>
</a>
</div>
</nav>
<div class="feed-link motion-element">
<a href="/atom.xml" rel="alternate">
<i class="fa fa-rss"></i>
RSS
</a>
</div>
<div class="links-of-author motion-element">
<span class="links-of-author-item">
<a href="https://github.com/HankCoder" target="_blank">
<i class="fa fa-github"></i> GitHub
</a>
</span>
<span class="links-of-author-item">
<a href="" target="_blank">
<i class="fa fa-twitter"></i> Twitter
</a>
</span>
<span class="links-of-author-item">
<a href="" target="_blank">
<i class="fa fa-weibo"></i> Weibo
</a>
</span>
<span class="links-of-author-item">
<a href="" target="_blank">
<i class="fa fa-facebook-square"></i> Facebook
</a>
</span>
<span class="links-of-author-item">
<a href="" target="_blank">
<i class="fa fa-heartbeat"></i> JianShu
</a>
</span>
</div>
<div class="cc-license motion-element" itemprop="license">
<a href="http://creativecommons.org/licenses/by-nc-sa/4.0" class="cc-opacity" target="_blank">
<img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
</a>
</div>
<div class="links-of-author motion-element">
</div>
</section>
<section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
<div class="post-toc-indicator-top post-toc-indicator">
<i class="fa fa-angle-double-up"></i>
</div>
<div class="post-toc">
<p class="post-toc-empty">此文章未包含目录</p>
</div>
<div class="post-toc-indicator-bottom post-toc-indicator">
<i class="fa fa-angle-double-down"></i>
</div>
</section>
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright" >
© 2015 -
<span itemprop="copyrightYear">2017</span>
<span class="with-love">
<i class="icon-next-heart fa fa-leaf"></i>
</span>
<span class="author" itemprop="copyrightHolder">HankCoder</span>
</div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
</div>
</footer>
<div class="back-to-top"></div>
</div>
<script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
<script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
<script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>
<script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
<script type="text/javascript" src="/js/src/utils.js?v=5.0.0"></script>
<script type="text/javascript" src="/js/src/motion.js?v=5.0.0"></script>
<script type="text/javascript" src="/js/src/affix.js?v=5.0.0"></script>
<script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.0"></script>
<script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.0"></script>
<script type="text/javascript" id="sidebar.toc.highlight">
$(document).ready(function () {
var tocSelector = '.post-toc';
var $tocSelector = $(tocSelector);
var activeCurrentSelector = '.active-current';
$tocSelector
.on('activate.bs.scrollspy', function () {
var $currentActiveElement = $(tocSelector + ' .active').last();
removeCurrentActiveClass();
$currentActiveElement.addClass('active-current');
$tocSelector[0].scrollTop = $currentActiveElement.position().top;
})
.on('clear.bs.scrollspy', function () {
removeCurrentActiveClass();
});
function removeCurrentActiveClass () {
$(tocSelector + ' ' + activeCurrentSelector)
.removeClass(activeCurrentSelector.substring(1));
}
function processTOC () {
getTOCMaxHeight();
toggleTOCOverflowIndicators();
}
function getTOCMaxHeight () {
var height = $('.sidebar').height() -
$tocSelector.position().top -
$('.post-toc-indicator-bottom').height();
$tocSelector.css('height', height);
return height;
}
function toggleTOCOverflowIndicators () {
tocOverflowIndicator(
'.post-toc-indicator-top',
$tocSelector.scrollTop() > 0 ? 'show' : 'hide'
);
tocOverflowIndicator(
'.post-toc-indicator-bottom',
$tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
)
}
$(document).on('sidebar.motion.complete', function () {
processTOC();
});
$('body').scrollspy({ target: tocSelector });
$(window).on('resize', function () {
if ( $('.sidebar').hasClass('sidebar-active') ) {
processTOC();
}
});
onScroll($tocSelector);
function onScroll (element) {
element.on('mousewheel DOMMouseScroll', function (event) {
var oe = event.originalEvent;
var delta = oe.wheelDelta || -oe.detail;
this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
event.preventDefault();
toggleTOCOverflowIndicators();
});
}
function tocOverflowIndicator (indicator, action) {
var $indicator = $(indicator);
var opacity = action === 'show' ? 1 : 0;
$indicator.velocity ?
$indicator.velocity('stop').velocity({
opacity: opacity
}, { duration: 100 }) :
$indicator.stop().animate({
opacity: opacity
}, 100);
}
});
</script>
<script type="text/javascript" id="sidebar.nav">
$(document).ready(function () {
var html = $('html');
var TAB_ANIMATE_DURATION = 200;
var hasVelocity = $.isFunction(html.velocity);
$('.sidebar-nav li').on('click', function () {
var item = $(this);
var activeTabClassName = 'sidebar-nav-active';
var activePanelClassName = 'sidebar-panel-active';
if (item.hasClass(activeTabClassName)) {
return;
}
var currentTarget = $('.' + activePanelClassName);
var target = $('.' + item.data('target'));
hasVelocity ?
currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
target
.velocity('stop')
.velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
.addClass(activePanelClassName);
}) :
currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
currentTarget.hide();
target
.stop()
.css({'opacity': 0, 'display': 'block'})
.animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
currentTarget.removeClass(activePanelClassName);
target.addClass(activePanelClassName);
});
});
item.siblings().removeClass(activeTabClassName);
item.addClass(activeTabClassName);
});
$('.post-toc a').on('click', function (e) {
e.preventDefault();
var targetSelector = escapeSelector(this.getAttribute('href'));
var offset = $(targetSelector).offset().top;
hasVelocity ?
html.velocity('stop').velocity('scroll', {
offset: offset + 'px',
mobileHA: false
}) :
$('html, body').stop().animate({
scrollTop: offset
}, 500);
});
// Expand sidebar on post detail page by default, when post has a toc.
motionMiddleWares.sidebar = function () {
var $tocContent = $('.post-toc-content');
if (CONFIG.sidebar === 'post') {
if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
displaySidebar();
}
}
};
});
</script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.0"></script>
<script type="text/javascript">
var duoshuoQuery = {short_name:"hankcoder"};
(function() {
var ds = document.createElement('script');
ds.type = 'text/javascript';ds.async = true;
ds.id = 'duoshuo-script';
ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
ds.charset = 'UTF-8';
(document.getElementsByTagName('head')[0]
|| document.getElementsByTagName('body')[0]).appendChild(ds);
})();
</script>
<script type="text/javascript">
var duoshuo_user_ID = 13537963;
var duoshuo_admin_nickname = "博主";
</script>
<script src="/vendors/ua-parser-js/dist/ua-parser.min.js"></script>
<script src="/js/src/hook-duoshuo.js"></script>
<script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
<script>AV.initialize("KIpFhjbOqk9B6NsU6sEACyJt", "HOFTbHJmJyGsoGKssFSPrPAy");</script>
<script>
function showTime(Counter) {
var query = new AV.Query(Counter);
var entries = [];
var $visitors = $(".leancloud_visitors");
$visitors.each(function () {
entries.push( $(this).attr("id").trim() );
});
query.containedIn('url', entries);
query.find()
.done(function (results) {
var COUNT_CONTAINER_REF = '.leancloud-visitors-count';
if (results.length === 0) {
$visitors.find(COUNT_CONTAINER_REF).text(0);
return;
}
for (var i = 0; i < results.length; i++) {
var item = results[i];
var url = item.get('url');
var time = item.get('time');
var element = document.getElementById(url);
$(element).find(COUNT_CONTAINER_REF).text(time);
}
})
.fail(function (object, error) {
console.log("Error: " + error.code + " " + error.message);
});
}
function addCount(Counter) {
var $visitors = $(".leancloud_visitors");
var url = $visitors.attr('id').trim();
var title = $visitors.attr('data-flag-title').trim();
var query = new AV.Query(Counter);
query.equalTo("url", url);
query.find({
success: function(results) {
if (results.length > 0) {
var counter = results[0];
counter.fetchWhenSave(true);
counter.increment("time");
counter.save(null, {
success: function(counter) {
var $element = $(document.getElementById(url));
$element.find('.leancloud-visitors-count').text(counter.get('time'));
},
error: function(counter, error) {
console.log('Failed to save Visitor num, with error message: ' + error.message);
}
});
} else {
var newcounter = new Counter();
newcounter.set("title", title);
newcounter.set("url", url);
newcounter.set("time", 1);
newcounter.save(null, {
success: function(newcounter) {
var $element = $(document.getElementById(url));
$element.find('.leancloud-visitors-count').text(newcounter.get('time'));
},
error: function(newcounter, error) {
console.log('Failed to create');
}
});
}
},
error: function(error) {
console.log('Error:' + error.code + " " + error.message);
}
});
}
$(function() {
var Counter = AV.Object.extend("Counter");
if ($('.leancloud_visitors').length == 1) {
addCount(Counter);
} else if ($('.post-title-link').length > 1) {
showTime(Counter);
}
});
</script>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery-lazyload/1.9.5/jquery.lazyload.js"></script>
<script type="text/javascript">
$(function () {
$("#posts").find('img').lazyload({
placeholder: "/images/loading.gif",
effect: "fadeIn"
});
});
</script>
</body>
</html>
| HankCoder/BlogBackup | public/2017/01/17/随手记20170118/index.html | HTML | mit | 28,614 |
using System;
using Newtonsoft.Json;
namespace MultiSafepay.Model
{
public class Transaction
{
[JsonProperty("transaction_id")]
public string TransactionId { get; set; }
[JsonProperty("payment_type")]
public string PaymentType { get; set; }
[JsonProperty("order_id")]
public string OrderId { get; set; }
[JsonProperty("status")]
public string TransactionStatus { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("created")]
public DateTime? CreatedDate { get; set; }
[JsonProperty("order_status")]
public string OrderStatus { get; set; }
[JsonProperty("amount")]
public int Amount { get; set; }
[JsonProperty("currency")]
public string CurrencyCode { get; set; }
[JsonProperty("customer")]
public Customer Customer { get; set; }
[JsonProperty("payment_details")]
public PaymentDetails PaymentDetails { get; set; }
}
} | MultiSafepay/.Net | Src/MultiSafepay/Model/Transaction.cs | C# | mit | 1,056 |
require 'spec_helper'
describe MWS::Report do
describe ".method_missing" do
describe ".get_report_list" do
let(:valid_args){
{
key: "ThisIsSigningKey",
endpoint: "mws.amazonservices.com",
params: {
"AWSAccessKeyId" => "AccessKeyIdString",
"SellerId" => "SellerIdString",
"ReportTypeList" => ["_GET_FLAT_FILE_ORDERS_DATA_"],
"Acknowledged" => false,
"MaxCount" => 100
}
}
}
before do
response = double("request")
expect(response).to receive(:body).and_return("BodyString")
request = double("request")
expect(request).to receive(:execute).and_return(response)
expect(MWS::Request).to receive(:new).and_return(request)
end
subject { described_class.get_report_list(valid_args) }
it { is_expected.to be_a String }
end
end
end
| s-osa/marketplace_web_service | spec/mws/report_spec.rb | Ruby | mit | 929 |
require 'resolv'
module Geocoder
class IpAddress < String
def loopback?
valid? and !!(self == "0.0.0.0" or self.match(/\A127\./) or self == "::1")
end
def valid?
!!((self =~ Resolv::IPv4::Regex) || (self =~ Resolv::IPv6::Regex))
end
end
end
| tiramizoo/geocoder | lib/geocoder/ip_address.rb | Ruby | mit | 275 |
const chai = require('chai');
const expect = chai.expect;
const ComplexArray = require('../complex-array/complex-array');
function assertArrayEquals(first, second) {
const message = `${first} != ${second}`;
first.forEach((item, i) => {
expect(item).to.equal(second[i], message);
});
}
describe('Complex Array', () => {
describe('Consructor', () => {
it('should construct from a number', () => {
const a = new ComplexArray(10);
expect(a).to.exist;
expect(a.real.length).to.equal(10);
expect(a.imag.length).to.equal(10);
expect(a.real[0]).to.equal(0);
expect(a.imag[0]).to.equal(0);
});
it('should construct from a number with a type', () => {
const a = new ComplexArray(10, Int32Array);
expect(a.ArrayType).to.equal(Int32Array);
expect(a.real.length).to.equal(10);
expect(a.imag.length).to.equal(10);
expect(a.real[0]).to.equal(0);
expect(a.imag[0]).to.equal(0);
});
it('should contruct from a real array', () => {
const a = new ComplexArray([1, 2]);
assertArrayEquals([1, 2], a.real);
assertArrayEquals([0, 0], a.imag);
});
it('should contruct from a real array with a type', () => {
const a = new ComplexArray([1, 2], Int32Array);
expect(a.ArrayType).to.equal(Int32Array)
assertArrayEquals([1, 2], a.real);
assertArrayEquals([0, 0], a.imag);
});
it('should contruct from another complex array', () => {
const a = new ComplexArray(new ComplexArray([1, 2]));
assertArrayEquals([1, 2], a.real);
assertArrayEquals([0, 0], a.imag);
});
});
describe('`map` method', () => {
it('should alter all values', () => {
const a = new ComplexArray([1, 2]).map((value, i) => {
value.real *= 10;
value.imag = i;
});
assertArrayEquals([10, 20], a.real);
assertArrayEquals([0, 1], a.imag);
});
});
describe('`forEach` method', () => {
it('should touch every value', () => {
const a = new ComplexArray([1, 2]);
a.imag[0] = 4;
a.imag[1] = 8;
let sum = 0;
a.forEach((value, i) => {
sum += value.real;
sum += value.imag;
});
expect(sum).to.equal(15);
});
});
describe('`conjugate` method', () => {
it('should multiply a number', () => {
const a = new ComplexArray([1, 2]);
a.imag[0] = 1;
a.imag[1] = -2;
const b = a.conjugate();
assertArrayEquals([1, 2], b.real);
assertArrayEquals([-1, 2], b.imag);
});
});
describe('`magnitude` method', () => {
it('should give the an array of magnitudes', () => {
const a = new ComplexArray([1, 3]);
a.imag[0] = 0;
a.imag[1] = 4;
assertArrayEquals([1, 5], a.magnitude());
});
it('should return an iterable ArrayType object', () => {
const a = new ComplexArray([1, 2]);
let sum = 0;
a.magnitude().forEach((value, i) => {
sum += value;
});
expect(sum).to.equal(3);
});
});
});
| JoeKarlsson/data-structures | test/complex-array.spec.js | JavaScript | mit | 3,055 |
/*
* Copyright (C) 2011 by Jakub Lekstan <[email protected]>
*
* 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.
*/
#include <v8.h>
#include <node.h>
#include <sys/time.h>
#include <sys/resource.h>
int globalWho = RUSAGE_SELF;
static v8::Handle<v8::Value> get_r_usage(const v8::Arguments& args){
v8::HandleScope scope;
int localWho = globalWho;
if(args.Length() != 0){
bool isError = false;
if(args[0]->IsNumber()){
v8::Local<v8::Integer> iWho = v8::Local<v8::Integer>::Cast(args[0]);
localWho = (int)(iWho->Int32Value());
if(localWho != RUSAGE_SELF && localWho != RUSAGE_CHILDREN){
isError = true;
}
}else{
isError = true;
}
if(isError){
return v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument must be either a RUSAGE_SELF or RUSAGE_CHILDREN")));
}
}
rusage rusagedata;
int status = getrusage(localWho, &rusagedata);
if(status != 0){
scope.Close(v8::Null());
}
v8::Local<v8::Object> data = v8::Object::New();
data->Set(v8::String::New("ru_utime.tv_sec"), v8::Number::New(rusagedata.ru_utime.tv_sec));
data->Set(v8::String::New("ru_utime.tv_usec"), v8::Number::New(rusagedata.ru_utime.tv_usec));
data->Set(v8::String::New("ru_stime.tv_sec"), v8::Number::New(rusagedata.ru_stime.tv_sec));
data->Set(v8::String::New("ru_stime.tv_usec"), v8::Number::New(rusagedata.ru_stime.tv_usec));
data->Set(v8::String::New("ru_maxrss"), v8::Number::New(rusagedata.ru_maxrss));
data->Set(v8::String::New("ru_ixrss"), v8::Number::New(rusagedata.ru_ixrss));
data->Set(v8::String::New("ru_idrss"), v8::Number::New(rusagedata.ru_idrss));
data->Set(v8::String::New("ru_isrss"), v8::Number::New(rusagedata.ru_isrss));
data->Set(v8::String::New("ru_minflt"), v8::Number::New(rusagedata.ru_minflt));
data->Set(v8::String::New("ru_majflt"), v8::Number::New(rusagedata.ru_majflt));
data->Set(v8::String::New("ru_nswap"), v8::Number::New(rusagedata.ru_nswap));
data->Set(v8::String::New("ru_inblock"), v8::Number::New(rusagedata.ru_inblock));
data->Set(v8::String::New("ru_oublock"), v8::Number::New(rusagedata.ru_oublock));
data->Set(v8::String::New("ru_msgsnd"), v8::Number::New(rusagedata.ru_msgsnd));
data->Set(v8::String::New("ru_msgrcv"), v8::Number::New(rusagedata.ru_msgrcv));
data->Set(v8::String::New("ru_nsignals"), v8::Number::New(rusagedata.ru_nsignals));
data->Set(v8::String::New("ru_nvcsw"), v8::Number::New(rusagedata.ru_nvcsw));
data->Set(v8::String::New("ru_nivcsw"), v8::Number::New(rusagedata.ru_nivcsw));
return scope.Close(data);
}
static v8::Handle<v8::Value> usage_cycles(const v8::Arguments& args){
v8::HandleScope scope;
rusage rusagedata;
int status = getrusage(globalWho, &rusagedata);
if(status != 0){
return scope.Close(v8::Null());
}
return scope.Close(v8::Number::New(rusagedata.ru_utime.tv_sec * 1e6 + rusagedata.ru_utime.tv_usec));
}
static v8::Handle<v8::Value> who(const v8::Arguments& args){
v8::HandleScope scope;
if(args.Length() != 0 && args[0]->IsNumber()){
v8::Local<v8::Integer> iWho = v8::Local<v8::Integer>::Cast(args[0]);
int localWho = (int)(iWho->Int32Value());
if(localWho != RUSAGE_SELF && localWho != RUSAGE_CHILDREN){
return v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument must be either a RUSAGE_SELF or RUSAGE_CHILDREN")));
}
globalWho = localWho;
return scope.Close(v8::True());
}else{
return scope.Close(v8::False());
}
}
extern "C" void init (v8::Handle<v8::Object> target){
v8::HandleScope scope;
NODE_SET_METHOD(target, "get", get_r_usage);
NODE_SET_METHOD(target, "cycles", usage_cycles);
NODE_SET_METHOD(target, "who", who);
target->Set(v8::String::New("RUSAGE_SELF"), v8::Number::New(RUSAGE_SELF));
target->Set(v8::String::New("RUSAGE_CHILDREN"), v8::Number::New(RUSAGE_CHILDREN));
}
| kuebk/node-rusage | src/node-rusage.cc | C++ | mit | 4,830 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package config;
import interfaces.*;
import java.sql.*;
import java.util.logging.*;
import javax.swing.*;
/**
*
* @author Luis G
*/
public class Connector {
public Connector() {
}
protected boolean getData(String query, Callback callback) {
ResultSet rs = null;
Connection conn = null;
Statement stmt = null;
boolean isNull = false;
try {
connect();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/escuela", "root", "");
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
for (int i = 0; rs.next(); i++) {
callback.callback(rs, i);
}
stmt.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex);
}
return isNull;
}
protected ResultSet getData(String query) {
ResultSet rs = null;
Connection conn = null;
Statement stmt = null;
try {
connect();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/escuela", "root", "");
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
} catch (Exception e) {
System.out.println(e);
}
return rs;
}
protected int executeQuery(String query) {
int id = -1;
try {
connect();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/escuela", "root", "");
Statement stmt = conn.createStatement();
id = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
id = rs.getInt(1);
}
stmt.close();
conn.close();
} catch (SQLException e) {
Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, e);
switch (e.getErrorCode()) {
case 1062:
JOptionPane.showMessageDialog(null, "Ese correo ya esta registrado", "error", 0);
break;
case 1054:
JOptionPane.showMessageDialog(null, "El registro no existe", "error", 0);
break;
default:
JOptionPane.showMessageDialog(null, "A ocurrido un error " + e, "error", 0);
System.out.println(e);
break;
}
}
return id;
}
private void connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
}
}
}
| Luis-Gdx/escuela | Topicos Avanzados de Programacion/Tabla/Tabla con base de datos y login/src/config/Connector.java | Java | mit | 2,950 |
<?php
/*
* This file is part of NodalFlow.
* (c) Fabrice de Stefanis / https://github.com/fab2s/NodalFlow
* This source file is licensed under the MIT license which you will
* find in the LICENSE file or at https://opensource.org/licenses/MIT
*/
namespace fab2s\NodalFlow\Nodes;
use fab2s\NodalFlow\Flows\FlowInterface;
use fab2s\NodalFlow\NodalFlowException;
/**
* Class BranchNode
*/
class BranchNode extends PayloadNodeAbstract implements BranchNodeInterface
{
/**
* This Node is a Branch
*
* @var bool
*/
protected $isAFlow = true;
/**
* @var FlowInterface
*/
protected $payload;
/**
* Instantiate the BranchNode
*
* @param FlowInterface $payload
* @param bool $isAReturningVal
*
* @throws NodalFlowException
*/
public function __construct(FlowInterface $payload, bool $isAReturningVal)
{
// branch Node does not (yet) support traversing
parent::__construct($payload, $isAReturningVal, false);
}
/**
* Execute the BranchNode
*
* @param mixed|null $param
*
* @return mixed
*/
public function exec($param = null)
{
// in the branch case, we actually exec a Flow
return $this->payload->exec($param);
}
}
| fab2s/NodalFlow | src/Nodes/BranchNode.php | PHP | mit | 1,307 |
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20161127192427) do
create_table "cities", force: :cascade do |t|
t.string "name"
t.integer "state_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["state_id"], name: "index_cities_on_state_id"
end
create_table "countries", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "states", force: :cascade do |t|
t.string "name"
t.integer "country_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["country_id"], name: "index_states_on_country_id"
end
create_table "zone_members", force: :cascade do |t|
t.integer "zone_id"
t.integer "country_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["country_id"], name: "index_zone_members_on_country_id"
t.index ["zone_id"], name: "index_zone_members_on_zone_id"
end
create_table "zones", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| tiagoamaro/dynamic-form-reform | db/schema.rb | Ruby | mit | 1,926 |
<!--Navigation bar-->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" [routerLink]="['/']">Club Membership</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li><a [routerLink]="['/']">ABOUT</a></li>
<li><a [routerLink]="['/']">SERVICES</a></li>
<li><a [routerLink]="['/']">CLUBS</a></li>
<li><a [routerLink]="['/']">FORM</a></li>
</ul>
</div>
</div>
</nav> | muronchik/clubmembership-angular | src/app/components/nav/nav-custom.component.html | HTML | mit | 803 |
Ubench [](https://travis-ci.org/devster/ubench)
======
Ubench is a PHP micro library for benchmark
> https://github.com/devster/ubench
Installation
------------
### Old school ###
require `src/Ubench.php` in your project.
### Composer ###
Add this to your composer.json
```json
{
"require": {
"devster/ubench": "~2.0.0"
}
}
```
Usage
-----
```php
require_once 'src/Ubench.php';
$bench = new Ubench;
$bench->start();
// Execute some code
$bench->end();
// Get elapsed time and memory
echo $bench->getTime(); // 156ms or 1.123s
echo $bench->getTime(true); // elapsed microtime in float
echo $bench->getTime(false, '%d%s'); // 156ms or 1s
echo $bench->getMemoryPeak(); // 152B or 90.00Kb or 15.23Mb
echo $bench->getMemoryPeak(true); // memory peak in bytes
echo $bench->getMemoryPeak(false, '%.3f%s'); // 152B or 90.152Kb or 15.234Mb
// Returns the memory usage at the end mark
echo $bench->getMemoryUsage(); // 152B or 90.00Kb or 15.23Mb
// Runs `Ubench::start()` and `Ubench::end()` around a callable
// Accepts a callable as the first parameter. Any additional parameters will be passed to the callable.
$result = $bench->run(function ($x) {
return $x;
}, 1);
echo $bench->getTime();
```
License
-------
Ubench is licensed under the MIT License
| GCModeller-Cloud/php-dotnet | Framework/Debugger/Ubench/README.md | Markdown | mit | 1,357 |
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "NSObject.h"
@class NSMutableDictionary, NSString;
// Not exported
@interface GQZArchive : NSObject
{
NSMutableDictionary *mEntries;
id <GQZArchiveInputStream> mInput;
_Bool mIsEncrypted;
NSString *mFilename;
}
- (id)filename;
- (_Bool)isEncrypted;
- (id)entryNames;
- (id)entryWithName:(id)arg1;
- (void)dealloc;
- (id)initWithData:(id)arg1 collapseCommonRootDirectory:(_Bool)arg2;
- (id)initWithPath:(id)arg1 collapseCommonRootDirectory:(_Bool)arg2;
@end
| matthewsot/CocoaSharp | Headers/PrivateFrameworks/iWorkImport/GQZArchive.h | C | mit | 628 |
/*
* mysplit.c - Another handy routine for testing your tiny shell
*
* usage: mysplit <n>
* Fork a child that spins for <n> seconds in 1-second chunks.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
int main(int argc, char **argv)
{
int i, secs;
if (argc != 2) {
fprintf(stderr, "Usage: %s <n>\n", argv[0]);
exit(0);
}
secs = atoi(argv[1]);
if (fork() == 0) { /* child */
for (i=0; i < secs; i++)
sleep(1);
exit(0);
}
/* parent waits for child to terminate */
wait(NULL);
exit(0);
}
| heapsters/shelldon | routines/mysplit.c | C | mit | 640 |
/*
* Copyright (c) 1982, 1986, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)fs.h 8.13 (Berkeley) 3/21/95
* $FreeBSD: src/sys/ufs/ffs/fs.h,v 1.39 2003/02/22 00:19:26 mckusick Exp $
*/
#ifndef _UFS_FFS_FS_H_
#define _UFS_FFS_FS_H_
/*
* Each disk drive contains some number of filesystems.
* A filesystem consists of a number of cylinder groups.
* Each cylinder group has inodes and data.
*
* A filesystem is described by its super-block, which in turn
* describes the cylinder groups. The super-block is critical
* data and is replicated in each cylinder group to protect against
* catastrophic loss. This is done at `newfs' time and the critical
* super-block data does not change, so the copies need not be
* referenced further unless disaster strikes.
*
* For filesystem fs, the offsets of the various blocks of interest
* are given in the super block as:
* [fs->fs_sblkno] Super-block
* [fs->fs_cblkno] Cylinder group block
* [fs->fs_iblkno] Inode blocks
* [fs->fs_dblkno] Data blocks
* The beginning of cylinder group cg in fs, is given by
* the ``cgbase(fs, cg)'' macro.
*
* Depending on the architecture and the media, the superblock may
* reside in any one of four places. For tiny media where every block
* counts, it is placed at the very front of the partition. Historically,
* UFS1 placed it 8K from the front to leave room for the disk label and
* a small bootstrap. For UFS2 it got moved to 64K from the front to leave
* room for the disk label and a bigger bootstrap, and for really piggy
* systems we check at 256K from the front if the first three fail. In
* all cases the size of the superblock will be SBLOCKSIZE. All values are
* given in byte-offset form, so they do not imply a sector size. The
* SBLOCKSEARCH specifies the order in which the locations should be searched.
*/
#define SBLOCK_FLOPPY 0
#define SBLOCK_UFS1 8192
#define SBLOCK_UFS2 65536
#define SBLOCK_PIGGY 262144
#define SBLOCKSIZE 8192
#define SBLOCKSEARCH \
{ SBLOCK_UFS2, SBLOCK_UFS1, SBLOCK_FLOPPY, SBLOCK_PIGGY, -1 }
/*
* Max number of fragments per block. This value is NOT tweakable.
*/
#define MAXFRAG 8
/*
* Addresses stored in inodes are capable of addressing fragments
* of `blocks'. File system blocks of at most size MAXBSIZE can
* be optionally broken into 2, 4, or 8 pieces, each of which is
* addressable; these pieces may be DEV_BSIZE, or some multiple of
* a DEV_BSIZE unit.
*
* Large files consist of exclusively large data blocks. To avoid
* undue wasted disk space, the last data block of a small file may be
* allocated as only as many fragments of a large block as are
* necessary. The filesystem format retains only a single pointer
* to such a fragment, which is a piece of a single large block that
* has been divided. The size of such a fragment is determinable from
* information in the inode, using the ``blksize(fs, ip, lbn)'' macro.
*
* The filesystem records space availability at the fragment level;
* to determine block availability, aligned fragments are examined.
*/
/*
* MINBSIZE is the smallest allowable block size.
* In order to insure that it is possible to create files of size
* 2^32 with only two levels of indirection, MINBSIZE is set to 4096.
* MINBSIZE must be big enough to hold a cylinder group block,
* thus changes to (struct cg) must keep its size within MINBSIZE.
* Note that super blocks are always of size SBSIZE,
* and that both SBSIZE and MAXBSIZE must be >= MINBSIZE.
*/
#define MINBSIZE 4096
/*
* The path name on which the filesystem is mounted is maintained
* in fs_fsmnt. MAXMNTLEN defines the amount of space allocated in
* the super block for this name.
*/
#define MAXMNTLEN 468
/*
* The volume name for this filesystem is maintained in fs_volname.
* MAXVOLLEN defines the length of the buffer allocated.
*/
#define MAXVOLLEN 32
/*
* There is a 128-byte region in the superblock reserved for in-core
* pointers to summary information. Originally this included an array
* of pointers to blocks of struct csum; now there are just a few
* pointers and the remaining space is padded with fs_ocsp[].
*
* NOCSPTRS determines the size of this padding. One pointer (fs_csp)
* is taken away to point to a contiguous array of struct csum for
* all cylinder groups; a second (fs_maxcluster) points to an array
* of cluster sizes that is computed as cylinder groups are inspected,
* and the third points to an array that tracks the creation of new
* directories. A fourth pointer, fs_active, is used when creating
* snapshots; it points to a bitmap of cylinder groups for which the
* free-block bitmap has changed since the snapshot operation began.
*/
#define NOCSPTRS ((128 / sizeof(void *)) - 4)
/*
* A summary of contiguous blocks of various sizes is maintained
* in each cylinder group. Normally this is set by the initial
* value of fs_maxcontig. To conserve space, a maximum summary size
* is set by FS_MAXCONTIG.
*/
#define FS_MAXCONTIG 16
/*
* MINFREE gives the minimum acceptable percentage of filesystem
* blocks which may be free. If the freelist drops below this level
* only the superuser may continue to allocate blocks. This may
* be set to 0 if no reserve of free blocks is deemed necessary,
* however throughput drops by fifty percent if the filesystem
* is run at between 95% and 100% full; thus the minimum default
* value of fs_minfree is 5%. However, to get good clustering
* performance, 10% is a better choice. hence we use 10% as our
* default value. With 10% free space, fragmentation is not a
* problem, so we choose to optimize for time.
*/
#define MINFREE 8
#define DEFAULTOPT FS_OPTTIME
/*
* Grigoriy Orlov <[email protected]> has done some extensive work to fine
* tune the layout preferences for directories within a filesystem.
* His algorithm can be tuned by adjusting the following parameters
* which tell the system the average file size and the average number
* of files per directory. These defaults are well selected for typical
* filesystems, but may need to be tuned for odd cases like filesystems
* being used for sqiud caches or news spools.
*/
#define AVFILESIZ 16384 /* expected average file size */
#define AFPDIR 64 /* expected number of files per directory */
/*
* The maximum number of snapshot nodes that can be associated
* with each filesystem. This limit affects only the number of
* snapshot files that can be recorded within the superblock so
* that they can be found when the filesystem is mounted. However,
* maintaining too many will slow the filesystem performance, so
* having this limit is a good idea.
*/
#define FSMAXSNAP 20
/*
* Used to identify special blocks in snapshots:
*
* BLK_NOCOPY - A block that was unallocated at the time the snapshot
* was taken, hence does not need to be copied when written.
* BLK_SNAP - A block held by another snapshot that is not needed by this
* snapshot. When the other snapshot is freed, the BLK_SNAP entries
* are converted to BLK_NOCOPY. These are needed to allow fsck to
* identify blocks that are in use by other snapshots (which are
* expunged from this snapshot).
*/
#define BLK_NOCOPY ((ufs2_daddr_t)(1))
#define BLK_SNAP ((ufs2_daddr_t)(2))
/*
* Sysctl values for the fast filesystem.
*/
#define FFS_ADJ_REFCNT 1 /* adjust inode reference count */
#define FFS_ADJ_BLKCNT 2 /* adjust inode used block count */
#define FFS_BLK_FREE 3 /* free range of blocks in map */
#define FFS_DIR_FREE 4 /* free specified dir inodes in map */
#define FFS_FILE_FREE 5 /* free specified file inodes in map */
#define FFS_SET_FLAGS 6 /* set filesystem flags */
#define FFS_MAXID 7 /* number of valid ffs ids */
/*
* Command structure passed in to the filesystem to adjust filesystem values.
*/
#define FFS_CMD_VERSION 0x19790518 /* version ID */
struct fsck_cmd {
int32_t version; /* version of command structure */
int32_t handle; /* reference to filesystem to be changed */
int64_t value; /* inode or block number to be affected */
int64_t size; /* amount or range to be adjusted */
int64_t spare; /* reserved for future use */
};
/*
* Per cylinder group information; summarized in blocks allocated
* from first cylinder group data blocks. These blocks have to be
* read in from fs_csaddr (size fs_cssize) in addition to the
* super block.
*/
struct csum {
int32_t cs_ndir; /* number of directories */
int32_t cs_nbfree; /* number of free blocks */
int32_t cs_nifree; /* number of free inodes */
int32_t cs_nffree; /* number of free frags */
};
struct csum_total {
int64_t cs_ndir; /* number of directories */
int64_t cs_nbfree; /* number of free blocks */
int64_t cs_nifree; /* number of free inodes */
int64_t cs_nffree; /* number of free frags */
int64_t cs_numclusters; /* number of free clusters */
int64_t cs_spare[3]; /* future expansion */
};
/*
* Super block for an FFS filesystem.
*/
struct fs {
int32_t fs_firstfield; /* historic filesystem linked list, */
int32_t fs_unused_1; /* used for incore super blocks */
int32_t fs_sblkno; /* offset of super-block in filesys */
int32_t fs_cblkno; /* offset of cyl-block in filesys */
int32_t fs_iblkno; /* offset of inode-blocks in filesys */
int32_t fs_dblkno; /* offset of first data after cg */
int32_t fs_old_cgoffset; /* cylinder group offset in cylinder */
int32_t fs_old_cgmask; /* used to calc mod fs_ntrak */
int32_t fs_old_time; /* last time written */
int32_t fs_old_size; /* number of blocks in fs */
int32_t fs_old_dsize; /* number of data blocks in fs */
int32_t fs_ncg; /* number of cylinder groups */
int32_t fs_bsize; /* size of basic blocks in fs */
int32_t fs_fsize; /* size of frag blocks in fs */
int32_t fs_frag; /* number of frags in a block in fs */
/* these are configuration parameters */
int32_t fs_minfree; /* minimum percentage of free blocks */
int32_t fs_old_rotdelay; /* num of ms for optimal next block */
int32_t fs_old_rps; /* disk revolutions per second */
/* these fields can be computed from the others */
int32_t fs_bmask; /* ``blkoff'' calc of blk offsets */
int32_t fs_fmask; /* ``fragoff'' calc of frag offsets */
int32_t fs_bshift; /* ``lblkno'' calc of logical blkno */
int32_t fs_fshift; /* ``numfrags'' calc number of frags */
/* these are configuration parameters */
int32_t fs_maxcontig; /* max number of contiguous blks */
int32_t fs_maxbpg; /* max number of blks per cyl group */
/* these fields can be computed from the others */
int32_t fs_fragshift; /* block to frag shift */
int32_t fs_fsbtodb; /* fsbtodb and dbtofsb shift constant */
int32_t fs_sbsize; /* actual size of super block */
int32_t fs_spare1[2]; /* old fs_csmask */
/* old fs_csshift */
int32_t fs_nindir; /* value of NINDIR */
int32_t fs_inopb; /* value of INOPB */
int32_t fs_old_nspf; /* value of NSPF */
/* yet another configuration parameter */
int32_t fs_optim; /* optimization preference, see below */
int32_t fs_old_npsect; /* # sectors/track including spares */
int32_t fs_old_interleave; /* hardware sector interleave */
int32_t fs_old_trackskew; /* sector 0 skew, per track */
int32_t fs_id[2]; /* unique filesystem id */
/* sizes determined by number of cylinder groups and their sizes */
int32_t fs_old_csaddr; /* blk addr of cyl grp summary area */
int32_t fs_cssize; /* size of cyl grp summary area */
int32_t fs_cgsize; /* cylinder group size */
int32_t fs_spare2; /* old fs_ntrak */
int32_t fs_old_nsect; /* sectors per track */
int32_t fs_old_spc; /* sectors per cylinder */
int32_t fs_old_ncyl; /* cylinders in filesystem */
int32_t fs_old_cpg; /* cylinders per group */
int32_t fs_ipg; /* inodes per group */
int32_t fs_fpg; /* blocks per group * fs_frag */
/* this data must be re-computed after crashes */
struct csum fs_old_cstotal; /* cylinder summary information */
/* these fields are cleared at mount time */
int8_t fs_fmod; /* super block modified flag */
int8_t fs_clean; /* filesystem is clean flag */
int8_t fs_ronly; /* mounted read-only flag */
int8_t fs_old_flags; /* old FS_ flags */
u_char fs_fsmnt[MAXMNTLEN]; /* name mounted on */
u_char fs_volname[MAXVOLLEN]; /* volume name */
u_int64_t fs_swuid; /* system-wide uid */
int32_t fs_pad; /* due to alignment of fs_swuid */
/* these fields retain the current block allocation info */
int32_t fs_cgrotor; /* last cg searched */
void *fs_ocsp[NOCSPTRS]; /* padding; was list of fs_cs buffers */
u_int8_t *fs_contigdirs; /* # of contiguously allocated dirs */
struct csum *fs_csp; /* cg summary info buffer for fs_cs */
int32_t *fs_maxcluster; /* max cluster in each cyl group */
u_int *fs_active; /* used by snapshots to track fs */
int32_t fs_old_cpc; /* cyl per cycle in postbl */
int32_t fs_maxbsize; /* maximum blocking factor permitted */
int64_t fs_sparecon64[17]; /* old rotation block list head */
int64_t fs_sblockloc; /* byte offset of standard superblock */
struct csum_total fs_cstotal; /* cylinder summary information */
ufs_time_t fs_time; /* last time written */
int64_t fs_size; /* number of blocks in fs */
int64_t fs_dsize; /* number of data blocks in fs */
ufs2_daddr_t fs_csaddr; /* blk addr of cyl grp summary area */
int64_t fs_pendingblocks; /* blocks in process of being freed */
int32_t fs_pendinginodes; /* inodes in process of being freed */
int32_t fs_snapinum[FSMAXSNAP];/* list of snapshot inode numbers */
int32_t fs_avgfilesize; /* expected average file size */
int32_t fs_avgfpdir; /* expected # of files per directory */
int32_t fs_save_cgsize; /* save real cg size to use fs_bsize */
int32_t fs_sparecon32[26]; /* reserved for future constants */
int32_t fs_flags; /* see FS_ flags below */
int32_t fs_contigsumsize; /* size of cluster summary array */
int32_t fs_maxsymlinklen; /* max length of an internal symlink */
int32_t fs_old_inodefmt; /* format of on-disk inodes */
u_int64_t fs_maxfilesize; /* maximum representable file size */
int64_t fs_qbmask; /* ~fs_bmask for use with 64-bit size */
int64_t fs_qfmask; /* ~fs_fmask for use with 64-bit size */
int32_t fs_state; /* validate fs_clean field */
int32_t fs_old_postblformat; /* format of positional layout tables */
int32_t fs_old_nrpos; /* number of rotational positions */
int32_t fs_spare5[2]; /* old fs_postbloff */
/* old fs_rotbloff */
int32_t fs_magic; /* magic number */
};
/* Sanity checking. */
#ifdef CTASSERT
CTASSERT(sizeof(struct fs) == 1376);
#endif
/*
* Filesystem identification
*/
#define FS_UFS1_MAGIC 0x011954 /* UFS1 fast filesystem magic number */
#define FS_UFS2_MAGIC 0x19540119 /* UFS2 fast filesystem magic number */
#define FS_OKAY 0x7c269d38 /* superblock checksum */
#define FS_42INODEFMT -1 /* 4.2BSD inode format */
#define FS_44INODEFMT 2 /* 4.4BSD inode format */
/*
* Preference for optimization.
*/
#define FS_OPTTIME 0 /* minimize allocation time */
#define FS_OPTSPACE 1 /* minimize disk fragmentation */
/*
* Filesystem flags.
*
* The FS_UNCLEAN flag is set by the kernel when the filesystem was
* mounted with fs_clean set to zero. The FS_DOSOFTDEP flag indicates
* that the filesystem should be managed by the soft updates code.
* Note that the FS_NEEDSFSCK flag is set and cleared only by the
* fsck utility. It is set when background fsck finds an unexpected
* inconsistency which requires a traditional foreground fsck to be
* run. Such inconsistencies should only be found after an uncorrectable
* disk error. A foreground fsck will clear the FS_NEEDSFSCK flag when
* it has successfully cleaned up the filesystem. The kernel uses this
* flag to enforce that inconsistent filesystems be mounted read-only.
* The FS_INDEXDIRS flag when set indicates that the kernel maintains
* on-disk auxiliary indexes (such as B-trees) for speeding directory
* accesses. Kernels that do not support auxiliary indicies clear the
* flag to indicate that the indicies need to be rebuilt (by fsck) before
* they can be used.
*
* FS_ACLS indicates that ACLs are administratively enabled for the
* file system, so they should be loaded from extended attributes,
* observed for access control purposes, and be administered by object
* owners. FS_MULTILABEL indicates that the TrustedBSD MAC Framework
* should attempt to back MAC labels into extended attributes on the
* file system rather than maintain a single mount label for all
* objects.
*/
#define FS_UNCLEAN 0x01 /* filesystem not clean at mount */
#define FS_DOSOFTDEP 0x02 /* filesystem using soft dependencies */
#define FS_NEEDSFSCK 0x04 /* filesystem needs sync fsck before mount */
#define FS_INDEXDIRS 0x08 /* kernel supports indexed directories */
#define FS_ACLS 0x10 /* file system has ACLs enabled */
#define FS_MULTILABEL 0x20 /* file system is MAC multi-label */
#define FS_FLAGS_UPDATED 0x80 /* flags have been moved to new location */
/*
* Macros to access bits in the fs_active array.
*/
#define ACTIVECGNUM(fs, cg) ((fs)->fs_active[(cg) / (NBBY * sizeof(int))])
#define ACTIVECGOFF(cg) (1 << ((cg) % (NBBY * sizeof(int))))
/*
* The size of a cylinder group is calculated by CGSIZE. The maximum size
* is limited by the fact that cylinder groups are at most one block.
* Its size is derived from the size of the maps maintained in the
* cylinder group and the (struct cg) size.
*/
#define CGSIZE(fs) \
/* base cg */ (sizeof(struct cg) + sizeof(int32_t) + \
/* old btotoff */ (fs)->fs_old_cpg * sizeof(int32_t) + \
/* old boff */ (fs)->fs_old_cpg * sizeof(u_int16_t) + \
/* inode map */ howmany((fs)->fs_ipg, NBBY) + \
/* block map */ howmany((fs)->fs_fpg, NBBY) +\
/* if present */ ((fs)->fs_contigsumsize <= 0 ? 0 : \
/* cluster sum */ (fs)->fs_contigsumsize * sizeof(int32_t) + \
/* cluster map */ howmany(fragstoblks(fs, (fs)->fs_fpg), NBBY)))
/*
* The minimal number of cylinder groups that should be created.
*/
#define MINCYLGRPS 4
/*
* Convert cylinder group to base address of its global summary info.
*/
#define fs_cs(fs, indx) fs_csp[indx]
/*
* Cylinder group block for a filesystem.
*/
#define CG_MAGIC 0x090255
struct cg {
int32_t cg_firstfield; /* historic cyl groups linked list */
int32_t cg_magic; /* magic number */
int32_t cg_old_time; /* time last written */
int32_t cg_cgx; /* we are the cgx'th cylinder group */
int16_t cg_old_ncyl; /* number of cyl's this cg */
int16_t cg_old_niblk; /* number of inode blocks this cg */
int32_t cg_ndblk; /* number of data blocks this cg */
struct csum cg_cs; /* cylinder summary information */
int32_t cg_rotor; /* position of last used block */
int32_t cg_frotor; /* position of last used frag */
int32_t cg_irotor; /* position of last used inode */
int32_t cg_frsum[MAXFRAG]; /* counts of available frags */
int32_t cg_old_btotoff; /* (int32) block totals per cylinder */
int32_t cg_old_boff; /* (u_int16) free block positions */
int32_t cg_iusedoff; /* (u_int8) used inode map */
int32_t cg_freeoff; /* (u_int8) free block map */
int32_t cg_nextfreeoff; /* (u_int8) next available space */
int32_t cg_clustersumoff; /* (u_int32) counts of avail clusters */
int32_t cg_clusteroff; /* (u_int8) free cluster map */
int32_t cg_nclusterblks; /* number of clusters this cg */
int32_t cg_niblk; /* number of inode blocks this cg */
int32_t cg_initediblk; /* last initialized inode */
int32_t cg_sparecon32[3]; /* reserved for future use */
ufs_time_t cg_time; /* time last written */
int64_t cg_sparecon64[3]; /* reserved for future use */
u_int8_t cg_space[1]; /* space for cylinder group maps */
/* actually longer */
};
/*
* Macros for access to cylinder group array structures
*/
#define cg_chkmagic(cgp) ((cgp)->cg_magic == CG_MAGIC)
#define cg_inosused(cgp) \
((u_int8_t *)((u_int8_t *)(cgp) + (cgp)->cg_iusedoff))
#define cg_blksfree(cgp) \
((u_int8_t *)((u_int8_t *)(cgp) + (cgp)->cg_freeoff))
#define cg_clustersfree(cgp) \
((u_int8_t *)((u_int8_t *)(cgp) + (cgp)->cg_clusteroff))
#define cg_clustersum(cgp) \
((int32_t *)((u_int8_t *)(cgp) + (cgp)->cg_clustersumoff))
/*
* Turn filesystem block numbers into disk block addresses.
* This maps filesystem blocks to device size blocks.
*/
#define fsbtodb(fs, b) ((b) << (fs)->fs_fsbtodb)
#define dbtofsb(fs, b) ((b) >> (fs)->fs_fsbtodb)
/*
* Cylinder group macros to locate things in cylinder groups.
* They calc filesystem addresses of cylinder group data structures.
*/
#define cgbase(fs, c) (((ufs2_daddr_t)(fs)->fs_fpg) * (c))
#define cgdmin(fs, c) (cgstart(fs, c) + (fs)->fs_dblkno) /* 1st data */
#define cgimin(fs, c) (cgstart(fs, c) + (fs)->fs_iblkno) /* inode blk */
#define cgsblock(fs, c) (cgstart(fs, c) + (fs)->fs_sblkno) /* super blk */
#define cgtod(fs, c) (cgstart(fs, c) + (fs)->fs_cblkno) /* cg block */
#define cgstart(fs, c) \
((fs)->fs_magic == FS_UFS2_MAGIC ? cgbase(fs, c) : \
(cgbase(fs, c) + (fs)->fs_old_cgoffset * ((c) & ~((fs)->fs_old_cgmask))))
/*
* Macros for handling inode numbers:
* inode number to filesystem block offset.
* inode number to cylinder group number.
* inode number to filesystem block address.
*/
#define ino_to_cg(fs, x) ((x) / (fs)->fs_ipg)
#define ino_to_fsba(fs, x) \
((ufs2_daddr_t)(cgimin(fs, ino_to_cg(fs, x)) + \
(blkstofrags((fs), (((x) % (fs)->fs_ipg) / INOPB(fs))))))
#define ino_to_fsbo(fs, x) ((x) % INOPB(fs))
/*
* Give cylinder group number for a filesystem block.
* Give cylinder group block number for a filesystem block.
*/
#define dtog(fs, d) ((d) / (fs)->fs_fpg)
#define dtogd(fs, d) ((d) % (fs)->fs_fpg)
/*
* Extract the bits for a block from a map.
* Compute the cylinder and rotational position of a cyl block addr.
*/
#define blkmap(fs, map, loc) \
(((map)[(loc) / NBBY] >> ((loc) % NBBY)) & (0xff >> (NBBY - (fs)->fs_frag)))
/*
* The following macros optimize certain frequently calculated
* quantities by using shifts and masks in place of divisions
* modulos and multiplications.
*/
#define blkoff(fs, loc) /* calculates (loc % fs->fs_bsize) */ \
((loc) & (fs)->fs_qbmask)
#define fragoff(fs, loc) /* calculates (loc % fs->fs_fsize) */ \
((loc) & (fs)->fs_qfmask)
#define lfragtosize(fs, frag) /* calculates ((off_t)frag * fs->fs_fsize) */ \
(((off_t)(frag)) << (fs)->fs_fshift)
#define lblktosize(fs, blk) /* calculates ((off_t)blk * fs->fs_bsize) */ \
(((off_t)(blk)) << (fs)->fs_bshift)
/* Use this only when `blk' is known to be small, e.g., < NDADDR. */
#define smalllblktosize(fs, blk) /* calculates (blk * fs->fs_bsize) */ \
((blk) << (fs)->fs_bshift)
#define lblkno(fs, loc) /* calculates (loc / fs->fs_bsize) */ \
((loc) >> (fs)->fs_bshift)
#define numfrags(fs, loc) /* calculates (loc / fs->fs_fsize) */ \
((loc) >> (fs)->fs_fshift)
#define blkroundup(fs, size) /* calculates roundup(size, fs->fs_bsize) */ \
(((size) + (fs)->fs_qbmask) & (fs)->fs_bmask)
#define fragroundup(fs, size) /* calculates roundup(size, fs->fs_fsize) */ \
(((size) + (fs)->fs_qfmask) & (fs)->fs_fmask)
#define fragstoblks(fs, frags) /* calculates (frags / fs->fs_frag) */ \
((frags) >> (fs)->fs_fragshift)
#define blkstofrags(fs, blks) /* calculates (blks * fs->fs_frag) */ \
((blks) << (fs)->fs_fragshift)
#define fragnum(fs, fsb) /* calculates (fsb % fs->fs_frag) */ \
((fsb) & ((fs)->fs_frag - 1))
#define blknum(fs, fsb) /* calculates rounddown(fsb, fs->fs_frag) */ \
((fsb) &~ ((fs)->fs_frag - 1))
/*
* Determine the number of available frags given a
* percentage to hold in reserve.
*/
#define freespace(fs, percentreserved) \
(blkstofrags((fs), (fs)->fs_cstotal.cs_nbfree) + \
(fs)->fs_cstotal.cs_nffree - \
(((off_t)((fs)->fs_dsize)) * (percentreserved) / 100))
/*
* Determining the size of a file block in the filesystem.
*/
#define blksize(fs, ip, lbn) \
(((lbn) >= NDADDR || (ip)->i_size >= smalllblktosize(fs, (lbn) + 1)) \
? (fs)->fs_bsize \
: (fragroundup(fs, blkoff(fs, (ip)->i_size))))
#define sblksize(fs, size, lbn) \
(((lbn) >= NDADDR || (size) >= ((lbn) + 1) << (fs)->fs_bshift) \
? (fs)->fs_bsize \
: (fragroundup(fs, blkoff(fs, (size)))))
/*
* Number of inodes in a secondary storage block/fragment.
*/
#define INOPB(fs) ((fs)->fs_inopb)
#define INOPF(fs) ((fs)->fs_inopb >> (fs)->fs_fragshift)
/*
* Number of indirects in a filesystem block.
*/
#define NINDIR(fs) ((fs)->fs_nindir)
extern int inside[], around[];
extern u_char *fragtbl[];
#endif
| nathansamson/OMF | external/frisbee/imagezip/ffs/fs.h | C | mit | 26,375 |
\hypertarget{dir_a39a2e34196bbb4cf212587eee358088}{}\section{C\+:/\+Users/\+Tim-\/\+Mobil/\+Documents/\+Arduino/libraries/\+N\+B\+H\+X711/src Directory Reference}
\label{dir_a39a2e34196bbb4cf212587eee358088}\index{C\+:/\+Users/\+Tim-\/\+Mobil/\+Documents/\+Arduino/libraries/\+N\+B\+H\+X711/src Directory Reference@{C\+:/\+Users/\+Tim-\/\+Mobil/\+Documents/\+Arduino/libraries/\+N\+B\+H\+X711/src Directory Reference}}
\subsection*{Files}
\begin{DoxyCompactItemize}
\item
file \hyperlink{_n_b_h_x711_8cpp}{N\+B\+H\+X711.\+cpp}
\item
file \hyperlink{_n_b_h_x711_8h}{N\+B\+H\+X711.\+h}
\end{DoxyCompactItemize}
| whandall/NBHX711 | doc/latex/dir_a39a2e34196bbb4cf212587eee358088.tex | TeX | mit | 611 |
<?PHP
/**
* password view.
*
* includes form for username and email to send password to user.
*
*/
?>
<div id="content_area">
<div class="row" id="login"> <!--login box-->
<div class="col-xs-24" >
<?php
//begins the login form.
echo form_open(base_url().'Account/password');
//display error messages
if (isset($message_display))
{
echo $message_display;
}
if (isset($error_message))
{
echo "<div class='alert alert-danger text-center' role='alert'>";
echo $error_message;
echo validation_errors();
echo "</div>"; //display error_msg
}
//login form itself
echo '<h5 class="text-center">Provide your username and email address.</h5>';
?>
<label>Username :</label>
<p>
<input type="text" name="username" id="name" placeholder="username"/>
</p>
<label>Email :</label>
<p>
<input type="email" name="email" id="email" placeholder="[email protected]"/>
</p>
<!-- End of the form, begin submit button -->
<div class='submit_button_container text-center'>
<button type="submit" class="btn btn-primary btn-center" name="submit"/>Get Password</button>
<!--Link to retrieve username -->
<div style="padding-top:10px">
<?php echo anchor('Account/username','Forgot Username?') ?>
</div>
</div><!-- end submit button container -->
<?php echo form_close(); ?>
</div> <!-- end login div -->
</div>
</div><!-- end content_area div -->
</div>
<?PHP
/*End of file login.php*/
/*Location: ./application/veiws/Account/password.php*/ | rshanecole/TheFFFL | views/account/password.php | PHP | mit | 2,088 |
using System;
using System.Threading;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace vplan
{
public class PrefManager
{
NSUserDefaults locstore = new NSUserDefaults();
bool notified = false;
public PrefManager ()
{
refresh ();
}
protected void refresh () {
locstore.Synchronize ();
}
public int getInt (string key) {
int val;
val = locstore.IntForKey (key);
return val;
}
public string getString (string key) {
string val;
val = locstore.StringForKey (key);
return val;
}
public void setInt (string key, int val) {
locstore.SetInt (val, key);
refresh ();
}
public void setString (string key, string val) {
locstore.SetString (val, key);
refresh ();
}
}
}
| reknih/informant-ios | vplan/vplan.Kit/PrefManager.cs | C# | mit | 743 |
/*
DISKSPD
Copyright(c) Microsoft Corporation
All rights reserved.
MIT License
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.
*/
#include "StdAfx.h"
#include "XmlResultParser.UnitTests.h"
#include "Common.h"
#include "xmlresultparser.h"
#include <stdlib.h>
#include <vector>
using namespace WEX::TestExecution;
using namespace WEX::Logging;
using namespace std;
namespace UnitTests
{
void XmlResultParserUnitTests::Test_ParseResults()
{
Profile profile;
TimeSpan timeSpan;
Target target;
XmlResultParser parser;
Results results;
results.fUseETW = false;
double fTime = 120.0;
results.ullTimeCount = PerfTimer::SecondsToPerfTime(fTime);
// First group has 1 core
SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION systemProcessorInfo = {};
systemProcessorInfo.UserTime.QuadPart = static_cast<LONGLONG>(fTime * 30 * 100000);
systemProcessorInfo.IdleTime.QuadPart = static_cast<LONGLONG>(fTime * 45 * 100000);
systemProcessorInfo.KernelTime.QuadPart = static_cast<LONGLONG>(fTime * 70 * 100000);
results.vSystemProcessorPerfInfo.push_back(systemProcessorInfo);
// Second group has a maximum of 4 cores with 2 active
SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION zeroSystemProcessorInfo = { 0 };
zeroSystemProcessorInfo.UserTime.QuadPart = static_cast<LONGLONG>(fTime * 0 * 100000);
zeroSystemProcessorInfo.IdleTime.QuadPart = static_cast<LONGLONG>(fTime * 100 * 100000);
zeroSystemProcessorInfo.KernelTime.QuadPart = static_cast<LONGLONG>(fTime * 100 * 100000);
results.vSystemProcessorPerfInfo.push_back(zeroSystemProcessorInfo);
results.vSystemProcessorPerfInfo.push_back(zeroSystemProcessorInfo);
results.vSystemProcessorPerfInfo.push_back(zeroSystemProcessorInfo);
results.vSystemProcessorPerfInfo.push_back(zeroSystemProcessorInfo);
// TODO: multiple target cases, full profile/result variations
target.SetPath("testfile1.dat");
target.SetCacheMode(TargetCacheMode::DisableOSCache);
target.SetWriteThroughMode(WriteThroughMode::On);
target.SetThroughputIOPS(1000);
timeSpan.AddTarget(target);
timeSpan.SetCalculateIopsStdDev(true);
TargetResults targetResults;
targetResults.sPath = "testfile1.dat";
targetResults.ullFileSize = 10 * 1024 * 1024;
targetResults.ullReadBytesCount = 4 * 1024 * 1024;
targetResults.ullReadIOCount = 6;
targetResults.ullWriteBytesCount = 2 * 1024 * 1024;
targetResults.ullWriteIOCount = 10;
targetResults.ullBytesCount = targetResults.ullReadBytesCount + targetResults.ullWriteBytesCount;
targetResults.ullIOCount = targetResults.ullReadIOCount + targetResults.ullWriteIOCount;
// TODO: Histogram<float> readLatencyHistogram;
// TODO: Histogram<float> writeLatencyHistogram;
// TODO: IoBucketizer writeBucketizer;
targetResults.readBucketizer.Initialize(1000, timeSpan.GetDuration());
for (size_t i = 0; i < timeSpan.GetDuration(); i++)
{
// add an io halfway through the bucket's time interval
targetResults.readBucketizer.Add(i*1000 + 500, 0);
}
ThreadResults threadResults;
threadResults.vTargetResults.push_back(targetResults);
results.vThreadResults.push_back(threadResults);
vector<Results> vResults;
vResults.push_back(results);
// just throw away the computername and reset the timestamp - for the ut, it's
// as useful (and simpler) to verify statics as anything else. Reconstruct
// processor topo to a fixed example as well.
SystemInformation system;
system.ResetTime();
system.sComputerName.clear();
system.processorTopology._ulProcCount = 5;
system.processorTopology._ulActiveProcCount = 3;
system.processorTopology._vProcessorGroupInformation.clear();
system.processorTopology._vProcessorGroupInformation.emplace_back((BYTE)1, (BYTE)1, (WORD)0, (KAFFINITY)0x1);
system.processorTopology._vProcessorGroupInformation.emplace_back((BYTE)4, (BYTE)2, (WORD)1, (KAFFINITY)0x6);
system.processorTopology._vProcessorNumaInformation.clear();
system.processorTopology._vProcessorNumaInformation.emplace_back((DWORD)0, (WORD)0, (KAFFINITY)0x1);
system.processorTopology._vProcessorNumaInformation.emplace_back((DWORD)1, (WORD)1, (KAFFINITY)0x6);
ProcessorSocketInformation socket;
socket._vProcessorMasks.emplace_back((WORD)0, (KAFFINITY)0x1);
socket._vProcessorMasks.emplace_back((WORD)1, (KAFFINITY)0x6);
system.processorTopology._vProcessorSocketInformation.clear();
system.processorTopology._vProcessorSocketInformation.push_back(socket);
system.processorTopology._vProcessorHyperThreadInformation.clear();
system.processorTopology._vProcessorHyperThreadInformation.emplace_back((WORD)0, (KAFFINITY)0x1);
system.processorTopology._vProcessorHyperThreadInformation.emplace_back((WORD)1, (KAFFINITY)0x6);
// finally, add the timespan to the profile and dump.
profile.AddTimeSpan(timeSpan);
string sResults = parser.ParseResults(profile, system, vResults);
// stringify random text, quoting "'s and adding newline/preserving tabs
// gc some.txt |% { write-host $("`"{0}\n`"" -f $($_ -replace "`"","\`"" -replace "`t","\t")) }
const char *pcszExpectedOutput = \
"<Results>\n"
" <System>\n"
" <ComputerName></ComputerName>\n"
" <Tool>\n"
" <Version>" DISKSPD_NUMERIC_VERSION_STRING "</Version>\n"
" <VersionDate>" DISKSPD_DATE_VERSION_STRING "</VersionDate>\n"
" </Tool>\n"
" <RunTime></RunTime>\n"
" <ProcessorTopology>\n"
" <Group Group=\"0\" MaximumProcessors=\"1\" ActiveProcessors=\"1\" ActiveProcessorMask=\"0x1\"/>\n"
" <Group Group=\"1\" MaximumProcessors=\"4\" ActiveProcessors=\"2\" ActiveProcessorMask=\"0x6\"/>\n"
" <Node Node=\"0\" Group=\"0\" Processors=\"0x1\"/>\n"
" <Node Node=\"1\" Group=\"1\" Processors=\"0x6\"/>\n"
" <Socket>\n"
" <Group Group=\"0\" Processors=\"0x1\"/>\n"
" <Group Group=\"1\" Processors=\"0x6\"/>\n"
" </Socket>\n"
" <HyperThread Group=\"0\" Processors=\"0x1\"/>\n"
" <HyperThread Group=\"1\" Processors=\"0x6\"/>\n"
" </ProcessorTopology>\n"
" </System>\n"
" <Profile>\n"
" <Progress>0</Progress>\n"
" <ResultFormat>text</ResultFormat>\n"
" <Verbose>false</Verbose>\n"
" <TimeSpans>\n"
" <TimeSpan>\n"
" <CompletionRoutines>false</CompletionRoutines>\n"
" <MeasureLatency>false</MeasureLatency>\n"
" <CalculateIopsStdDev>true</CalculateIopsStdDev>\n"
" <DisableAffinity>false</DisableAffinity>\n"
" <Duration>10</Duration>\n"
" <Warmup>5</Warmup>\n"
" <Cooldown>0</Cooldown>\n"
" <ThreadCount>0</ThreadCount>\n"
" <RequestCount>0</RequestCount>\n"
" <IoBucketDuration>1000</IoBucketDuration>\n"
" <RandSeed>0</RandSeed>\n"
" <Targets>\n"
" <Target>\n"
" <Path>testfile1.dat</Path>\n"
" <BlockSize>65536</BlockSize>\n"
" <BaseFileOffset>0</BaseFileOffset>\n"
" <SequentialScan>false</SequentialScan>\n"
" <RandomAccess>false</RandomAccess>\n"
" <TemporaryFile>false</TemporaryFile>\n"
" <UseLargePages>false</UseLargePages>\n"
" <DisableOSCache>true</DisableOSCache>\n"
" <WriteThrough>true</WriteThrough>\n"
" <WriteBufferContent>\n"
" <Pattern>sequential</Pattern>\n"
" </WriteBufferContent>\n"
" <ParallelAsyncIO>false</ParallelAsyncIO>\n"
" <StrideSize>65536</StrideSize>\n"
" <InterlockedSequential>false</InterlockedSequential>\n"
" <ThreadStride>0</ThreadStride>\n"
" <MaxFileSize>0</MaxFileSize>\n"
" <RequestCount>2</RequestCount>\n"
" <WriteRatio>0</WriteRatio>\n"
" <Throughput unit=\"IOPS\">1000</Throughput>\n"
" <ThreadsPerFile>1</ThreadsPerFile>\n"
" <IOPriority>3</IOPriority>\n"
" <Weight>1</Weight>\n"
" </Target>\n"
" </Targets>\n"
" </TimeSpan>\n"
" </TimeSpans>\n"
" </Profile>\n"
" <TimeSpan>\n"
" <TestTimeSeconds>120.00</TestTimeSeconds>\n"
" <ThreadCount>1</ThreadCount>\n"
" <RequestCount>0</RequestCount>\n"
" <ProcCount>3</ProcCount>\n"
" <CpuUtilization>\n"
" <CPU>\n"
" <Group>0</Group>\n"
" <Id>0</Id>\n"
" <UsagePercent>55.00</UsagePercent>\n"
" <UserPercent>30.00</UserPercent>\n"
" <KernelPercent>25.00</KernelPercent>\n"
" <IdlePercent>45.00</IdlePercent>\n"
" </CPU>\n"
" <CPU>\n"
" <Group>1</Group>\n"
" <Id>1</Id>\n"
" <UsagePercent>0.00</UsagePercent>\n"
" <UserPercent>0.00</UserPercent>\n"
" <KernelPercent>0.00</KernelPercent>\n"
" <IdlePercent>100.00</IdlePercent>\n"
" </CPU>\n"
" <CPU>\n"
" <Group>1</Group>\n"
" <Id>2</Id>\n"
" <UsagePercent>0.00</UsagePercent>\n"
" <UserPercent>0.00</UserPercent>\n"
" <KernelPercent>0.00</KernelPercent>\n"
" <IdlePercent>100.00</IdlePercent>\n"
" </CPU>\n"
" <Average>\n"
" <UsagePercent>18.33</UsagePercent>\n"
" <UserPercent>10.00</UserPercent>\n"
" <KernelPercent>8.33</KernelPercent>\n"
" <IdlePercent>81.67</IdlePercent>\n"
" </Average>\n"
" </CpuUtilization>\n"
" <Iops>\n"
" <ReadIopsStdDev>0.000</ReadIopsStdDev>\n"
" <IopsStdDev>0.000</IopsStdDev>\n"
" <Bucket SampleMillisecond=\"1000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"2000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"3000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"4000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"5000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"6000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"7000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"8000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"9000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"10000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" </Iops>\n"
" <Thread>\n"
" <Id>0</Id>\n"
" <Target>\n"
" <Path>testfile1.dat</Path>\n"
" <BytesCount>6291456</BytesCount>\n"
" <FileSize>10485760</FileSize>\n"
" <IOCount>16</IOCount>\n"
" <ReadBytes>4194304</ReadBytes>\n"
" <ReadCount>6</ReadCount>\n"
" <WriteBytes>2097152</WriteBytes>\n"
" <WriteCount>10</WriteCount>\n"
" <Iops>\n"
" <ReadIopsStdDev>0.000</ReadIopsStdDev>\n"
" <IopsStdDev>0.000</IopsStdDev>\n"
" <Bucket SampleMillisecond=\"1000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"2000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"3000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"4000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"5000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"6000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"7000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"8000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"9000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" <Bucket SampleMillisecond=\"10000\" Read=\"1\" Write=\"0\" Total=\"1\" ReadMinLatencyMilliseconds=\"0.000\" ReadMaxLatencyMilliseconds=\"0.000\" ReadAvgLatencyMilliseconds=\"0.000\" ReadLatencyStdDev=\"0.000\" WriteMinLatencyMilliseconds=\"0.000\" WriteMaxLatencyMilliseconds=\"0.000\" WriteAvgLatencyMilliseconds=\"0.000\" WriteLatencyStdDev=\"0.000\"/>\n"
" </Iops>\n"
" </Target>\n"
" </Thread>\n"
" </TimeSpan>\n"
"</Results>";
#if 0
HANDLE h;
DWORD written;
h = CreateFileW(L"g:\\xmlresult-received.txt", GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
WriteFile(h, sResults.c_str(), (DWORD)sResults.length(), &written, NULL);
VERIFY_ARE_EQUAL(sResults.length(), written);
CloseHandle(h);
h = CreateFileW(L"g:\\xmlresult-expected.txt", GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
WriteFile(h, pcszExpectedOutput, (DWORD)strlen(pcszExpectedOutput), &written, NULL);
VERIFY_ARE_EQUAL((DWORD)strlen(pcszExpectedOutput), written);
CloseHandle(h);
printf("--\n%s\n", sResults.c_str());
printf("-------------------------------------------------\n");
printf("--\n%s\n", pcszExpectedOutput);
#endif
VERIFY_ARE_EQUAL(0, strcmp(sResults.c_str(), pcszExpectedOutput));
}
void XmlResultParserUnitTests::Test_ParseProfile()
{
Profile profile;
XmlResultParser parser;
TimeSpan timeSpan;
Target target;
timeSpan.AddTarget(target);
profile.AddTimeSpan(timeSpan);
string s = parser.ParseProfile(profile);
const char *pcszExpectedOutput = "<Profile>\n"
" <Progress>0</Progress>\n"
" <ResultFormat>text</ResultFormat>\n"
" <Verbose>false</Verbose>\n"
" <TimeSpans>\n"
" <TimeSpan>\n"
" <CompletionRoutines>false</CompletionRoutines>\n"
" <MeasureLatency>false</MeasureLatency>\n"
" <CalculateIopsStdDev>false</CalculateIopsStdDev>\n"
" <DisableAffinity>false</DisableAffinity>\n"
" <Duration>10</Duration>\n"
" <Warmup>5</Warmup>\n"
" <Cooldown>0</Cooldown>\n"
" <ThreadCount>0</ThreadCount>\n"
" <RequestCount>0</RequestCount>\n"
" <IoBucketDuration>1000</IoBucketDuration>\n"
" <RandSeed>0</RandSeed>\n"
" <Targets>\n"
" <Target>\n"
" <Path></Path>\n"
" <BlockSize>65536</BlockSize>\n"
" <BaseFileOffset>0</BaseFileOffset>\n"
" <SequentialScan>false</SequentialScan>\n"
" <RandomAccess>false</RandomAccess>\n"
" <TemporaryFile>false</TemporaryFile>\n"
" <UseLargePages>false</UseLargePages>\n"
" <WriteBufferContent>\n"
" <Pattern>sequential</Pattern>\n"
" </WriteBufferContent>\n"
" <ParallelAsyncIO>false</ParallelAsyncIO>\n"
" <StrideSize>65536</StrideSize>\n"
" <InterlockedSequential>false</InterlockedSequential>\n"
" <ThreadStride>0</ThreadStride>\n"
" <MaxFileSize>0</MaxFileSize>\n"
" <RequestCount>2</RequestCount>\n"
" <WriteRatio>0</WriteRatio>\n"
" <Throughput>0</Throughput>\n"
" <ThreadsPerFile>1</ThreadsPerFile>\n"
" <IOPriority>3</IOPriority>\n"
" <Weight>1</Weight>\n"
" </Target>\n"
" </Targets>\n"
" </TimeSpan>\n"
" </TimeSpans>\n"
"</Profile>\n";
//VERIFY_ARE_EQUAL(pcszExpectedOutput, s.c_str());
VERIFY_ARE_EQUAL(strlen(pcszExpectedOutput), s.length());
VERIFY_IS_TRUE(!strcmp(pcszExpectedOutput, s.c_str()));
}
void XmlResultParserUnitTests::Test_ParseTargetProfile()
{
Target target;
string sResults;
char pszExpectedOutput[4096];
int nWritten;
const char *pcszOutputTemplate = \
"<Target>\n"
" <Path>testfile1.dat</Path>\n"
" <BlockSize>65536</BlockSize>\n"
" <BaseFileOffset>0</BaseFileOffset>\n"
" <SequentialScan>false</SequentialScan>\n"
" <RandomAccess>false</RandomAccess>\n"
" <TemporaryFile>false</TemporaryFile>\n"
" <UseLargePages>false</UseLargePages>\n"
" <DisableOSCache>true</DisableOSCache>\n"
" <WriteThrough>true</WriteThrough>\n"
" <WriteBufferContent>\n"
" <Pattern>sequential</Pattern>\n"
" </WriteBufferContent>\n"
" <ParallelAsyncIO>false</ParallelAsyncIO>\n"
" <StrideSize>65536</StrideSize>\n"
" <InterlockedSequential>false</InterlockedSequential>\n"
" <ThreadStride>0</ThreadStride>\n"
" <MaxFileSize>0</MaxFileSize>\n"
" <RequestCount>2</RequestCount>\n"
" <WriteRatio>0</WriteRatio>\n"
" <Throughput%s>%s</Throughput>\n" // 2 param
" <ThreadsPerFile>1</ThreadsPerFile>\n"
" <IOPriority>3</IOPriority>\n"
" <Weight>1</Weight>\n"
"</Target>\n";
target.SetPath("testfile1.dat");
target.SetCacheMode(TargetCacheMode::DisableOSCache);
target.SetWriteThroughMode(WriteThroughMode::On);
// Base case - no limit
nWritten = sprintf_s(pszExpectedOutput, sizeof(pszExpectedOutput),
pcszOutputTemplate, "", "0");
VERIFY_IS_GREATER_THAN(nWritten, 0);
sResults = target.GetXml(0);
VERIFY_ARE_EQUAL(sResults, pszExpectedOutput);
// IOPS - with units
target.SetThroughputIOPS(1000);
nWritten = sprintf_s(pszExpectedOutput, sizeof(pszExpectedOutput),
pcszOutputTemplate, " unit=\"IOPS\"", "1000");
VERIFY_IS_GREATER_THAN(nWritten, 0);
sResults = target.GetXml(0);
VERIFY_ARE_EQUAL(sResults, pszExpectedOutput);
// BPMS - not specified with units in output
target.SetThroughput(1000);
nWritten = sprintf_s(pszExpectedOutput, sizeof(pszExpectedOutput),
pcszOutputTemplate, "", "1000");
VERIFY_IS_GREATER_THAN(nWritten, 0);
sResults = target.GetXml(0);
VERIFY_ARE_EQUAL(sResults, pszExpectedOutput);
}
} | microsoft/diskspd | UnitTests/XmlResultParser/XmlResultParser.UnitTests.cpp | C++ | mit | 26,838 |
/** @jsx h */
import h from '../../helpers/h'
export const schema = {
blocks: {
paragraph: {
marks: [{ type: 'bold' }, { type: 'underline' }],
},
},
}
export const input = (
<value>
<document>
<paragraph>
one <i>two</i> three
</paragraph>
</document>
</value>
)
export const output = (
<value>
<document>
<paragraph>one two three</paragraph>
</document>
</value>
)
| ashutoshrishi/slate | packages/slate/test/schema/custom/node-mark-invalid-default.js | JavaScript | mit | 437 |
/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
*
* Google CDN, Latest jQuery
* To use the default WordPress version of jQuery, go to lib/config.php and
* remove or comment out: add_theme_support('jquery-cdn');
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Sage = {
// All pages
'common': {
init: function() {
// JavaScript to be fired on all pages
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
},
// Home page
'home': {
init: function() {
// JavaScript to be fired on the home page
},
finalize: function() {
// JavaScript to be fired on the home page, after the init JS
}
},
// About us page, note the change from about-us to about_us.
'about_us': {
init: function() {
// JavaScript to be fired on the about us page
}
}
};
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var fire;
var namespace = Sage;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};
// Load Events
$(document).ready(UTIL.loadEvents);
})(jQuery); // Fully reference jQuery after this point.
$(document).ready(function(){
$("#sidebar-home ul li").addClass( "col-md-3 col-sm-6" );
$("#sidebar-home div").addClass( "clearfix" );
});
| erikkowalski/hoe-sage-8.1.0 | assets/scripts/main.js | JavaScript | mit | 2,737 |
#pragma once
#include "interface/types.h"
inline uintptr_t get_return_address()
{
uintptr_t ret;
asm volatile("movq 8(%%rbp), %0" : "=r"(ret) : : "memory");
return ret;
} | stmobo/Kraftwerk | os/include/arch/x86-64/debug.h | C | mit | 174 |
import {bootstrap} from '@angular/platform-browser-dynamic';
import {ROUTER_PROVIDERS} from '@angular/router-deprecated';
import {HTTP_PROVIDERS} from '@angular/http';
import {AppComponent} from './app.component';
import {LoggerService} from './blocks/logger.service';
bootstrap(AppComponent, [
LoggerService, ROUTER_PROVIDERS, HTTP_PROVIDERS
]);
| IMAMBAKS/data_viz_pa | app/main.ts | TypeScript | mit | 352 |
package org.apache.shiro.grails.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.apache.shiro.authz.Permission;
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PermissionRequired {
Class<? extends Permission> type();
/**
* The name of the role required to be granted this authorization.
*/
String target() default "*";
String actions() default "";
}
| putin266/Vote | target/work/plugins/shiro-1.2.1/src/java/org/apache/shiro/grails/annotations/PermissionRequired.java | Java | mit | 572 |
local r = require('restructure')
local ArrayT = r.Array
describe('Array', function()
describe('decode', function()
it( 'should decode fixed length', function()
local stream = r.DecodeStream.new(string.char(1, 2, 3, 4, 5))
local array = ArrayT.new(r.uint8, 4)
assert.are.same({1, 2, 3, 4}, array:decode(stream))
end)
it( 'should decode fixed amount of bytes', function()
local stream = r.DecodeStream.new(string.char(1, 2, 3, 4, 5))
local array = ArrayT.new(r.uint16, 4, 'bytes')
assert.are.same({258, 772}, array:decode(stream))
end)
it( 'should decode length from parent key', function()
local stream = r.DecodeStream.new(string.char(1, 2, 3, 4, 5))
local array = ArrayT.new(r.uint8, 'len')
assert.are.same({1, 2, 3, 4}, array:decode(stream, { len = 4 }))
end)
it( 'should decode amount of bytes from parent key', function()
local stream = r.DecodeStream.new(string.char(1, 2, 3, 4, 5))
local array = ArrayT.new(r.uint16, 'len', 'bytes')
assert.are.same({258, 772}, array:decode(stream, { len = 4 }))
end)
it( 'should decode length as number before array', function()
local stream = r.DecodeStream.new(string.char(4, 1, 2, 3, 4, 5))
local array = ArrayT.new(r.uint8, r.uint8)
local val = array:decode(stream)
local exp = {1,2,3,4}
for i, v in ipairs(val) do
assert.are_equal(exp[i], v)
end
end)
it( 'should decode amount of bytes as number before array', function()
local stream = r.DecodeStream.new(string.char(4, 1, 2, 3, 4, 5))
local array = ArrayT.new(r.uint16, r.uint8, 'bytes')
local val = array:decode(stream)
local exp = {258, 772}
for i, v in ipairs(val) do
assert.are_equal(exp[i], v)
end
end)
it( 'should decode length from function', function()
local stream = r.DecodeStream.new(string.char(1, 2, 3, 4, 5))
local array = ArrayT.new(r.uint8, function() return 4 end)
assert.are.same({1, 2, 3, 4}, array:decode(stream))
end)
it( 'should decode amount of bytes from function', function()
local stream = r.DecodeStream.new(string.char(1, 2, 3, 4, 5))
local array = ArrayT.new(r.uint16, function() return 4 end, 'bytes')
assert.are.same({258, 772}, array:decode(stream))
end)
it( 'should decode to the end of the parent if no length is given', function()
local stream = r.DecodeStream.new(string.char(1, 2, 3, 4, 5))
local array = ArrayT.new(r.uint8)
assert.are.same({1, 2, 3, 4}, array:decode(stream, {_length = 4, _startOffset = 0}))
end)
it( 'should decode to the end of the stream if no parent and length is given', function()
local stream = r.DecodeStream.new(string.char(1, 2, 3, 4))
local array = ArrayT.new(r.uint8)
assert.are.same({1, 2, 3, 4}, array:decode(stream))
end)
end)
describe('size', function()
it( 'should use array length', function()
local array = ArrayT.new(r.uint8, 10)
assert.are_equal(4, array:size({1, 2, 3, 4}))
end)
it( 'should add size of length field before string', function()
local array = ArrayT.new(r.uint8, r.uint8)
assert.are_equal(5, array:size({1, 2, 3, 4}))
end)
it( 'should use defined length if no value given', function()
local array = ArrayT.new(r.uint8, 10)
assert.are_equal(10, array:size())
end)
end)
describe('encode', function()
it( 'should encode using array length', function()
local stream = r.EncodeStream.new()
local array = ArrayT.new(r.uint8, 10)
array:encode(stream, {1, 2, 3, 4})
assert.are.same((string.char(1, 2, 3, 4)), stream:getContents())
end)
it( 'should encode length as number before array', function()
local stream = r.EncodeStream.new()
local array = ArrayT.new(r.uint8, r.uint8)
array:encode(stream, {1, 2, 3, 4})
assert.are.same((string.char(4, 1, 2, 3, 4)), stream:getContents())
end)
it( 'should add pointers after array if length is encoded at start', function()
local stream = r.EncodeStream.new()
local array = ArrayT.new(r.Pointer.new(r.uint8, r.uint8), r.uint8)
array:encode(stream, {1, 2, 3, 4})
assert.are.same((string.char(4,5, 6, 7, 8, 1, 2, 3, 4)), stream:getContents())
end)
end)
end) | deepakjois/luarestructure | spec/Array_spec.lua | Lua | mit | 4,372 |
using Academy.Core.Contracts;
using Academy.Commands.Adding;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Academy.Tests.Commands.Mocks;
namespace Academy.Tests.Commands.AddingTests.AddStudentToSeasonCommandTests
{
[TestFixture]
public class Constructor_Should
{
[Test]
public void ThrowArgumentNullException_WhenPassedFactoryIsNull()
{
// Arrange
var engineMock = new Mock<IEngine>();
// Act & Assert
Assert.Throws<ArgumentNullException>(() => new AddStudentToSeasonCommand(null, engineMock.Object));
}
[Test]
public void ThrowArgumentNullException_WhenPassedEngineIsNull()
{
// Arrange
var factoryMock = new Mock<IAcademyFactory>();
// Act & Assert
Assert.Throws<ArgumentNullException>(() => new AddStudentToSeasonCommand(factoryMock.Object, null));
}
[Test]
public void AssignCorrectValueToFactory_WhenPassedDependenciesAreNotNull()
{
// Arrange
var factoryMock = new Mock<IAcademyFactory>();
var engineMock = new Mock<IEngine>();
// Act
var command = new AddStudentToSeasonCommandMock(factoryMock.Object, engineMock.Object);
// Assert
Assert.AreSame(factoryMock.Object, command.AcademyFactory);
}
[Test]
public void AssignCorrectValueToEngine_WhenPassedDependenciesAreNotNull()
{
// Arrange
var factoryMock = new Mock<IAcademyFactory>();
var engineMock = new Mock<IEngine>();
// Act
var command = new AddStudentToSeasonCommandMock(factoryMock.Object, engineMock.Object);
// Assert
Assert.AreSame(engineMock.Object, command.Engine);
}
}
}
| TelerikAcademy/Unit-Testing | Topics/04. Workshops/Workshop (Students)/Academy/Workshop/Academy.Tests/Commands/Adding/AddStudentToSeasonCommandTests/Constructor_Should.cs | C# | mit | 2,040 |
module.exports = {
before: [function () {
console.log('global beforeAll1');
}, 'alias1'],
'alias1': 'alias2',
'alias2': function () {
console.log('global beforeAll2');
},
'One': function () {
this.sum = 1;
},
'plus one': function () {
this.sum += 1;
},
'equals two': function () {
if (this.sum !== 2) {
throw new Error(this.sum + ' !== 2');
}
}
}; | twolfson/doubleshot | test/test_files/complex_global_hooks/content.js | JavaScript | mit | 399 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Submission 121</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0">
<img src="gallery/submissions/121.jpg" height="400">
</body>
</html>
| heyitsgarrett/envelopecollective | gallery_submission.php-id=121.html | HTML | mit | 367 |
puppet-roundcube
================
## Overview
Install and configure roundcube with optional apache/mysql configuration.
* `roundcube` : Main define for the roundcube.
## Examples
Typical user with apache and mysql configuration :
roundcube { 'webmail.example.com':
docroot => '/var/www/webmail.example.com',
mysql_username => 'webmail',
mysql_password => 'password',
mysql_dbname => 'webmail',
imap_server => 'ssl://imap.example.com',
imap_port => '993',
version => '0.91';
}
| rjpearce/puppet-roundcube | README.md | Markdown | mit | 557 |
## 0.0.2 30-08-2016
* Fixed pin to mimic the old logic PR#4
## 0.0.1 29-08-2016
* First version
| senecajs-labs/seneca-pin | CHANGES.md | Markdown | mit | 99 |
exports.__esModule = true;
exports.parseServerOptionsForRunCommand = parseServerOptionsForRunCommand;
exports.parseRunTargets = parseRunTargets;
var _cordova = require('../cordova');
var cordova = babelHelpers.interopRequireWildcard(_cordova);
var _cordovaProjectJs = require('../cordova/project.js');
var _cordovaRunnerJs = require('../cordova/runner.js');
var _cordovaRunTargetsJs = require('../cordova/run-targets.js');
// The architecture used by MDG's hosted servers; it's the architecture used by
// 'meteor deploy'.
var main = require('./main.js');
var _ = require('underscore');
var files = require('../fs/files.js');
var deploy = require('../meteor-services/deploy.js');
var buildmessage = require('../utils/buildmessage.js');
var auth = require('../meteor-services/auth.js');
var authClient = require('../meteor-services/auth-client.js');
var config = require('../meteor-services/config.js');
var Future = require('fibers/future');
var runLog = require('../runners/run-log.js');
var utils = require('../utils/utils.js');
var httpHelpers = require('../utils/http-helpers.js');
var archinfo = require('../utils/archinfo.js');
var catalog = require('../packaging/catalog/catalog.js');
var stats = require('../meteor-services/stats.js');
var Console = require('../console/console.js').Console;
var projectContextModule = require('../project-context.js');
var release = require('../packaging/release.js');
var DEPLOY_ARCH = 'os.linux.x86_64';
// The default port that the development server listens on.
var DEFAULT_PORT = '3000';
// Valid architectures that Meteor officially supports.
var VALID_ARCHITECTURES = {
"os.osx.x86_64": true,
"os.linux.x86_64": true,
"os.linux.x86_32": true,
"os.windows.x86_32": true
};
// __dirname - the location of the current executing file
var __dirnameConverted = files.convertToStandardPath(__dirname);
// Given a site name passed on the command line (eg, 'mysite'), return
// a fully-qualified hostname ('mysite.meteor.com').
//
// This is fairly simple for now. It appends 'meteor.com' if the name
// doesn't contain a dot, and it deletes any trailing dots (the
// technically legal hostname 'mysite.com.' is canonicalized to
// 'mysite.com').
//
// In the future, you should be able to make this default to some
// other domain you control, rather than 'meteor.com'.
var qualifySitename = function (site) {
if (site.indexOf(".") === -1) site = site + ".meteor.com";
while (site.length && site[site.length - 1] === ".") site = site.substring(0, site.length - 1);
return site;
};
// Display a message showing valid Meteor architectures.
var showInvalidArchMsg = function (arch) {
Console.info("Invalid architecture: " + arch);
Console.info("The following are valid Meteor architectures:");
_.each(_.keys(VALID_ARCHITECTURES), function (va) {
Console.info(Console.command(va), Console.options({ indent: 2 }));
});
};
// Utility functions to parse options in run/build/test-packages commands
function parseServerOptionsForRunCommand(options, runTargets) {
var parsedServerUrl = parsePortOption(options.port);
// XXX COMPAT WITH 0.9.2.2 -- the 'mobile-port' option is deprecated
var mobileServerOption = options['mobile-server'] || options['mobile-port'];
var parsedMobileServerUrl = undefined;
if (mobileServerOption) {
parsedMobileServerUrl = parseMobileServerOption(mobileServerOption);
} else {
var isRunOnDeviceRequested = _.any(runTargets, function (runTarget) {
return runTarget.isDevice;
});
parsedMobileServerUrl = detectMobileServerUrl(parsedServerUrl, isRunOnDeviceRequested);
}
return { parsedServerUrl: parsedServerUrl, parsedMobileServerUrl: parsedMobileServerUrl };
}
function parsePortOption(portOption) {
var parsedServerUrl = utils.parseUrl(portOption);
if (!parsedServerUrl.port) {
Console.error("--port must include a port.");
throw new main.ExitWithCode(1);
}
return parsedServerUrl;
}
function parseMobileServerOption(mobileServerOption) {
var optionName = arguments.length <= 1 || arguments[1] === undefined ? 'mobile-server' : arguments[1];
var parsedMobileServerUrl = utils.parseUrl(mobileServerOption, { protocol: 'http://' });
if (!parsedMobileServerUrl.host) {
Console.error('--' + optionName + ' must include a hostname.');
throw new main.ExitWithCode(1);
}
return parsedMobileServerUrl;
}
function detectMobileServerUrl(parsedServerUrl, isRunOnDeviceRequested) {
// If we are running on a device, use the auto-detected IP
if (isRunOnDeviceRequested) {
var myIp = undefined;
try {
myIp = utils.ipAddress();
} catch (error) {
Console.error('Error detecting IP address for mobile app to connect to:\n' + error.message + '\nPlease specify the address that the mobile app should connect\nto with --mobile-server.');
throw new main.ExitWithCode(1);
}
return {
protocol: 'http://',
host: myIp,
port: parsedServerUrl.port
};
} else {
// We are running a simulator, use localhost
return {
protocol: 'http://',
host: 'localhost',
port: parsedServerUrl.port
};
}
}
function parseRunTargets(targets) {
return targets.map(function (target) {
var targetParts = target.split('-');
var platform = targetParts[0];
var isDevice = targetParts[1] === 'device';
if (platform == 'ios') {
return new _cordovaRunTargetsJs.iOSRunTarget(isDevice);
} else if (platform == 'android') {
return new _cordovaRunTargetsJs.AndroidRunTarget(isDevice);
} else {
Console.error('Unknown run target: ' + target);
throw new main.ExitWithCode(1);
}
});
}
;
///////////////////////////////////////////////////////////////////////////////
// options that act like commands
///////////////////////////////////////////////////////////////////////////////
// Prints the Meteor architecture name of this host
main.registerCommand({
name: '--arch',
requiresRelease: false,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
Console.rawInfo(archinfo.host() + "\n");
});
//Prints the Meteor log about the versions
main.registerCommand({
name:'--about',
requiresRelease: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options){
if (release.current === null) {
if (!options.appDir) throw new Error("missing release, but not in an app?");
Console.error("This project was created with a checkout of Meteor, rather than an " + "official release, and doesn't have a release number associated with " + "it. You can set its release with " + Console.command("'meteor update'") + ".");
return 1;
}
if (release.current.isCheckout()) {
var gitLog = utils.runGitInCheckout('log', '--format=%h%d', '-n 1').trim();
Console.error("Unreleased, running from a checkout at " + gitLog);
return 1;
}
var dirname = files.convertToStandardPath(__dirname);
var about = files.readFile(files.pathJoin(dirname, 'about.txt'), 'utf8');
console.log(about);
});
// Prints the current release in use. Note that if there is not
// actually a specific release, we print to stderr and exit non-zero,
// while if there is a release we print to stdout and exit zero
// (making this useful to scripts).
// XXX: What does this mean in our new release-free world?
main.registerCommand({
name: '--version',
requiresRelease: false,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (release.current === null) {
if (!options.appDir) throw new Error("missing release, but not in an app?");
Console.error("This project was created with a checkout of Meteor, rather than an " + "official release, and doesn't have a release number associated with " + "it. You can set its release with " + Console.command("'meteor update'") + ".");
return 1;
}
if (release.current.isCheckout()) {
var gitLog = utils.runGitInCheckout('log', '--format=%h%d', '-n 1').trim();
Console.error("Unreleased, running from a checkout at " + gitLog);
return 1;
}
Console.info(release.current.getDisplayName());
});
// Internal use only. For automated testing.
main.registerCommand({
name: '--long-version',
requiresRelease: false,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (files.inCheckout()) {
Console.error("checkout");
return 1;
} else if (release.current === null) {
// .meteor/release says "none" but not in a checkout.
Console.error("none");
return 1;
} else {
Console.rawInfo(release.current.name + "\n");
Console.rawInfo(files.getToolsVersion() + "\n");
return 0;
}
});
// Internal use only. For automated testing.
main.registerCommand({
name: '--requires-release',
requiresRelease: true,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
return 0;
});
///////////////////////////////////////////////////////////////////////////////
// run
///////////////////////////////////////////////////////////////////////////////
var runCommandOptions = {
requiresApp: true,
maxArgs: Infinity,
options: {
port: { type: String, short: "p", 'default': DEFAULT_PORT },
'mobile-server': { type: String },
// XXX COMPAT WITH 0.9.2.2
'mobile-port': { type: String },
'app-port': { type: String },
'debug-port': { type: String },
production: { type: Boolean },
'raw-logs': { type: Boolean },
settings: { type: String },
test: { type: Boolean, 'default': false },
verbose: { type: Boolean, short: "v" },
// With --once, meteor does not re-run the project if it crashes
// and does not monitor for file changes. Intentionally
// undocumented: intended for automated testing (eg, cli-test.sh),
// not end-user use. #Once
once: { type: Boolean },
// Don't run linter on rebuilds
'no-lint': { type: Boolean },
// Allow the version solver to make breaking changes to the versions
// of top-level dependencies.
'allow-incompatible-update': { type: Boolean }
},
catalogRefresh: new catalog.Refresh.Never()
};
main.registerCommand(_.extend({ name: 'run' }, runCommandOptions), doRunCommand);
function doRunCommand(options) {
Console.setVerbose(!!options.verbose);
// Additional args are interpreted as run targets
var runTargets = parseRunTargets(options.args);
var _parseServerOptionsForRunCommand = parseServerOptionsForRunCommand(options, runTargets);
var parsedServerUrl = _parseServerOptionsForRunCommand.parsedServerUrl;
var parsedMobileServerUrl = _parseServerOptionsForRunCommand.parsedMobileServerUrl;
var projectContext = new projectContextModule.ProjectContext({
projectDir: options.appDir,
allowIncompatibleUpdate: options['allow-incompatible-update'],
lintAppAndLocalPackages: !options['no-lint']
});
main.captureAndExit("=> Errors while initializing project:", function () {
// We're just reading metadata here --- we'll wait to do the full build
// preparation until after we've started listening on the proxy, etc.
projectContext.readProjectMetadata();
});
if (release.explicit) {
if (release.current.name !== projectContext.releaseFile.fullReleaseName) {
console.log("=> Using %s as requested (overriding %s)", release.current.getDisplayName(), projectContext.releaseFile.displayReleaseName);
console.log();
}
}
var appHost = undefined,
appPort = undefined;
if (options['app-port']) {
var appPortMatch = options['app-port'].match(/^(?:(.+):)?([0-9]+)?$/);
if (!appPortMatch) {
Console.error("run: --app-port must be a number or be of the form 'host:port' ", "where port is a number. Try", Console.command("'meteor help run'") + " for help.");
return 1;
}
appHost = appPortMatch[1] || null;
// It's legit to specify `--app-port host:` and still let the port be
// randomized.
appPort = appPortMatch[2] ? parseInt(appPortMatch[2]) : null;
}
if (options['raw-logs']) runLog.setRawLogs(true);
// Velocity testing. Sets up a DDP connection to the app process and
// runs phantomjs.
//
// NOTE: this calls process.exit() when testing is done.
if (options['test']) {
options.once = true;
var serverUrlForVelocity = 'http://' + (parsedServerUrl.host || "localhost") + ':' + parsedServerUrl.port;
var velocity = require('../runners/run-velocity.js');
velocity.runVelocity(serverUrlForVelocity);
}
var cordovaRunner = undefined;
if (!_.isEmpty(runTargets)) {
main.captureAndExit('', 'preparing Cordova project', function () {
var cordovaProject = new _cordovaProjectJs.CordovaProject(projectContext, {
settingsFile: options.settings,
mobileServerUrl: utils.formatUrl(parsedMobileServerUrl) });
cordovaRunner = new _cordovaRunnerJs.CordovaRunner(cordovaProject, runTargets);
cordovaRunner.checkPlatformsForRunTargets();
});
}
var runAll = require('../runners/run-all.js');
return runAll.run({
projectContext: projectContext,
proxyPort: parsedServerUrl.port,
proxyHost: parsedServerUrl.host,
appPort: appPort,
appHost: appHost,
debugPort: options['debug-port'],
settingsFile: options.settings,
buildOptions: {
minifyMode: options.production ? 'production' : 'development',
buildMode: options.production ? 'production' : 'development'
},
rootUrl: process.env.ROOT_URL,
mongoUrl: process.env.MONGO_URL,
oplogUrl: process.env.MONGO_OPLOG_URL,
mobileServerUrl: utils.formatUrl(parsedMobileServerUrl),
once: options.once,
cordovaRunner: cordovaRunner
});
}
///////////////////////////////////////////////////////////////////////////////
// debug
///////////////////////////////////////////////////////////////////////////////
main.registerCommand(_.extend({ name: 'debug' }, runCommandOptions), function (options) {
options['debug-port'] = options['debug-port'] || '5858';
return doRunCommand(options);
});
///////////////////////////////////////////////////////////////////////////////
// shell
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'shell',
requiresRelease: false,
requiresApp: true,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (!options.appDir) {
Console.error("The " + Console.command("'meteor shell'") + " command must be run", "in a Meteor app directory.");
} else {
var projectContext = new projectContextModule.ProjectContext({
projectDir: options.appDir
});
// Convert to OS path here because shell/server.js doesn't know how to
// convert paths, since it exists in the app and in the tool.
require('../shell-client.js').connect(files.convertToOSPath(projectContext.getMeteorShellDirectory()));
throw new main.WaitForExit();
}
});
///////////////////////////////////////////////////////////////////////////////
// create
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'create',
maxArgs: 1,
options: {
list: { type: Boolean },
example: { type: String },
'package': { type: Boolean }
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
// Creating a package is much easier than creating an app, so if that's what
// we are doing, do that first. (For example, we don't springboard to the
// latest release to create a package if we are inside an app)
if (options['package']) {
var packageName = options.args[0];
// No package examples exist yet.
if (options.list && options.example) {
Console.error("No package examples exist at this time.");
Console.error();
throw new main.ShowUsage();
}
if (!packageName) {
Console.error("Please specify the name of the package.");
throw new main.ShowUsage();
}
utils.validatePackageNameOrExit(packageName, { detailedColonExplanation: true });
// When we create a package, avoid introducing a colon into the file system
// by naming the directory after the package name without the prefix.
var fsName = packageName;
if (packageName.indexOf(":") !== -1) {
var split = packageName.split(":");
if (split.length > 2) {
// It may seem like this check should be inside package version parser's
// validatePackageName, but we decided to name test packages like this:
// local-test:prefix:name, so we have to support building packages
// with at least two colons. Therefore we will at least try to
// discourage people from putting a ton of colons in their package names
// here.
Console.error(packageName + ": Package names may not have more than one colon.");
return 1;
}
fsName = split[1];
}
var packageDir;
if (options.appDir) {
packageDir = files.pathResolve(options.appDir, 'packages', fsName);
} else {
packageDir = files.pathResolve(fsName);
}
var inYourApp = options.appDir ? " in your app" : "";
if (files.exists(packageDir)) {
Console.error(packageName + ": Already exists" + inYourApp);
return 1;
}
var transform = function (x) {
var xn = x.replace(/~name~/g, packageName).replace(/~fs-name~/g, fsName);
// If we are running from checkout, comment out the line sourcing packages
// from a release, with the latest release filled in (in case they do want
// to publish later). If we are NOT running from checkout, fill it out
// with the current release.
var relString;
if (release.current.isCheckout()) {
xn = xn.replace(/~cc~/g, "//");
var rel = catalog.official.getDefaultReleaseVersion();
// the no-release case should never happen except in tests.
relString = rel ? rel.version : "no-release";
} else {
xn = xn.replace(/~cc~/g, "");
relString = release.current.getDisplayName({ noPrefix: true });
}
// If we are not in checkout, write the current release here.
return xn.replace(/~release~/g, relString);
};
try {
files.cp_r(files.pathJoin(__dirnameConverted, '..', 'static-assets', 'skel-pack'), packageDir, {
transformFilename: function (f) {
return transform(f);
},
transformContents: function (contents, f) {
if (/(\.html|\.js|\.css)/.test(f)) return new Buffer(transform(contents.toString()));else return contents;
},
ignore: [/^local$/]
});
} catch (err) {
Console.error("Could not create package: " + err.message);
return 1;
}
var displayPackageDir = files.convertToOSPath(files.pathRelative(files.cwd(), packageDir));
// Since the directory can't have colons, the directory name will often not
// match the name of the package exactly, therefore we should tell people
// where it was created.
Console.info(packageName + ": created in", Console.path(displayPackageDir));
return 0;
}
// Suppose you have an app A, and from some directory inside that
// app, you run 'meteor create /my/new/app'. The new app should use
// the latest available Meteor release, not the release that A
// uses. So if we were run from inside an app directory, and the
// user didn't force a release with --release, we need to
// springboard to the correct release and tools version.
//
// (In particular, it's not sufficient to create the new app with
// this version of the tools, and then stamp on the correct release
// at the end.)
if (!release.current.isCheckout() && !release.forced) {
if (release.current.name !== release.latestKnown()) {
throw new main.SpringboardToLatestRelease();
}
}
var exampleDir = files.pathJoin(__dirnameConverted, '..', '..', 'examples');
var examples = _.reject(files.readdir(exampleDir), function (e) {
return e === 'unfinished' || e === 'other' || e[0] === '.';
});
if (options.list) {
Console.info("Available examples:");
_.each(examples, function (e) {
Console.info(Console.command(e), Console.options({ indent: 2 }));
});
Console.info();
Console.info("Create a project from an example with " + Console.command("'meteor create --example <name>'") + ".");
return 0;
};
var appPathAsEntered;
if (options.args.length === 1) appPathAsEntered = options.args[0];else if (options.example) appPathAsEntered = options.example;else throw new main.ShowUsage();
var appPath = files.pathResolve(appPathAsEntered);
if (files.findAppDir(appPath)) {
Console.error("You can't create a Meteor project inside another Meteor project.");
return 1;
}
var appName;
if (appPathAsEntered === "." || appPathAsEntered === "./") {
// If trying to create in current directory
appName = files.pathBasename(files.cwd());
} else {
appName = files.pathBasename(appPath);
}
var transform = function (x) {
return x.replace(/~name~/g, appName);
};
// These file extensions are usually metadata, not app code
var nonCodeFileExts = ['.txt', '.md', '.json', '.sh'];
var destinationHasCodeFiles = false;
// If the directory doesn't exist, it clearly doesn't have any source code
// inside itself
if (files.exists(appPath)) {
destinationHasCodeFiles = _.any(files.readdir(appPath), function thisPathCountsAsAFile(filePath) {
// We don't mind if there are hidden files or directories (this includes
// .git) and we don't need to check for .meteor here because the command
// will fail earlier
var isHidden = /^\./.test(filePath);
if (isHidden) {
// Not code
return false;
}
// We do mind if there are non-hidden directories, because we don't want
// to recursively check everything to do some crazy heuristic to see if
// we should try to creat an app.
var stats = files.stat(filePath);
if (stats.isDirectory()) {
// Could contain code
return true;
}
// Check against our file extension white list
var ext = files.pathExtname(filePath);
if (ext == '' || _.contains(nonCodeFileExts, ext)) {
return false;
}
// Everything not matched above is considered to be possible source code
return true;
});
}
if (options.example) {
if (destinationHasCodeFiles) {
Console.error('When creating an example app, the destination directory can only contain dot-files or files with the following extensions: ' + nonCodeFileExts.join(', ') + '\n');
return 1;
}
if (examples.indexOf(options.example) === -1) {
Console.error(options.example + ": no such example.");
Console.error();
Console.error("List available applications with", Console.command("'meteor create --list'") + ".");
return 1;
} else {
files.cp_r(files.pathJoin(exampleDir, options.example), appPath, {
// We try not to check the project ID into git, but it might still
// accidentally exist and get added (if running from checkout, for
// example). To be on the safe side, explicitly remove the project ID
// from example apps.
ignore: [/^local$/, /^\.id$/]
});
}
} else {
var toIgnore = [/^local$/, /^\.id$/];
if (destinationHasCodeFiles) {
// If there is already source code in the directory, don't copy our
// skeleton app code over it. Just create the .meteor folder and metadata
toIgnore.push(/(\.html|\.js|\.css)/);
}
files.cp_r(files.pathJoin(__dirnameConverted, '..', 'static-assets', 'skel'), appPath, {
transformFilename: function (f) {
return transform(f);
},
transformContents: function (contents, f) {
if (/(\.html|\.js|\.css)/.test(f)) return new Buffer(transform(contents.toString()));else return contents;
},
ignore: toIgnore
});
}
// We are actually working with a new meteor project at this point, so
// set up its context.
var projectContext = new projectContextModule.ProjectContext({
projectDir: appPath,
// Write .meteor/versions even if --release is specified.
alwaysWritePackageMap: true,
// examples come with a .meteor/versions file, but we shouldn't take it
// too seriously
allowIncompatibleUpdate: true
});
main.captureAndExit("=> Errors while creating your project", function () {
projectContext.readProjectMetadata();
if (buildmessage.jobHasMessages()) return;
projectContext.releaseFile.write(release.current.isCheckout() ? "none" : release.current.name);
if (buildmessage.jobHasMessages()) return;
// Any upgrader that is in this version of Meteor doesn't need to be run on
// this project.
var upgraders = require('../upgraders.js');
projectContext.finishedUpgraders.appendUpgraders(upgraders.allUpgraders());
projectContext.prepareProjectForBuild();
});
// No need to display the PackageMapDelta here, since it would include all of
// the packages (or maybe an unpredictable subset based on what happens to be
// in the template's versions file).
var appNameToDisplay = appPathAsEntered === "." ? "current directory" : '\'' + appPathAsEntered + '\'';
var message = 'Created a new Meteor app in ' + appNameToDisplay;
if (options.example && options.example !== appPathAsEntered) {
message += ' (from \'' + options.example + '\' template)';
}
message += ".";
Console.info(message + "\n");
// Print a nice message telling people we created their new app, and what to
// do next.
Console.info("To run your new app:");
if (appPathAsEntered !== ".") {
// Wrap the app path in quotes if it contains spaces
var appPathWithQuotesIfSpaces = appPathAsEntered.indexOf(' ') === -1 ? appPathAsEntered : '\'' + appPathAsEntered + '\'';
// Don't tell people to 'cd .'
Console.info(Console.command("cd " + appPathWithQuotesIfSpaces), Console.options({ indent: 2 }));
}
Console.info(Console.command("meteor"), Console.options({ indent: 2 }));
Console.info("");
Console.info("If you are new to Meteor, try some of the learning resources here:");
Console.info(Console.url("https://www.meteor.com/learn"), Console.options({ indent: 2 }));
Console.info("");
});
///////////////////////////////////////////////////////////////////////////////
// build
///////////////////////////////////////////////////////////////////////////////
var buildCommands = {
minArgs: 1,
maxArgs: 1,
requiresApp: true,
options: {
debug: { type: Boolean },
directory: { type: Boolean },
architecture: { type: String },
'mobile-settings': { type: String },
server: { type: String },
// XXX COMPAT WITH 0.9.2.2
"mobile-port": { type: String },
verbose: { type: Boolean, short: "v" },
'allow-incompatible-update': { type: Boolean }
},
catalogRefresh: new catalog.Refresh.Never()
};
main.registerCommand(_.extend({ name: 'build' }, buildCommands), function (options) {
return buildCommand(options);
});
// Deprecated -- identical functionality to 'build' with one exception: it
// doesn't output a directory with all builds but rather only one tarball with
// server/client programs.
// XXX COMPAT WITH 0.9.1.1
main.registerCommand(_.extend({ name: 'bundle', hidden: true
}, buildCommands), function (options) {
Console.error("This command has been deprecated in favor of " + Console.command("'meteor build'") + ", which allows you to " + "build for multiple platforms and outputs a directory instead of " + "a single tarball. See " + Console.command("'meteor help build'") + " " + "for more information.");
Console.error();
return buildCommand(_.extend(options, { _serverOnly: true }));
});
var buildCommand = function (options) {
Console.setVerbose(!!options.verbose);
// XXX output, to stderr, the name of the file written to (for human
// comfort, especially since we might change the name)
// XXX name the root directory in the bundle based on the basename
// of the file, not a constant 'bundle' (a bit obnoxious for
// machines, but worth it for humans)
// Error handling for options.architecture. We must pass in only one of three
// architectures. See archinfo.js for more information on what the
// architectures are, what they mean, et cetera.
if (options.architecture && !_.has(VALID_ARCHITECTURES, options.architecture)) {
showInvalidArchMsg(options.architecture);
return 1;
}
var bundleArch = options.architecture || archinfo.host();
var projectContext = new projectContextModule.ProjectContext({
projectDir: options.appDir,
serverArchitectures: _.uniq([bundleArch, archinfo.host()]),
allowIncompatibleUpdate: options['allow-incompatible-update']
});
main.captureAndExit("=> Errors while initializing project:", function () {
projectContext.prepareProjectForBuild();
});
projectContext.packageMapDelta.displayOnConsole();
// options['mobile-settings'] is used to set the initial value of
// `Meteor.settings` on mobile apps. Pass it on to options.settings,
// which is used in this command.
if (options['mobile-settings']) {
options.settings = options['mobile-settings'];
}
var appName = files.pathBasename(options.appDir);
var cordovaPlatforms = undefined;
var parsedMobileServerUrl = undefined;
if (!options._serverOnly) {
cordovaPlatforms = projectContext.platformList.getCordovaPlatforms();
if (process.platform === 'win32' && !_.isEmpty(cordovaPlatforms)) {
Console.warn('Can\'t build for mobile on Windows. Skipping the following platforms: ' + cordovaPlatforms.join(", "));
cordovaPlatforms = [];
} else if (process.platform !== 'darwin' && _.contains(cordovaPlatforms, 'ios')) {
cordovaPlatforms = _.without(cordovaPlatforms, 'ios');
Console.warn("Currently, it is only possible to build iOS apps \
on an OS X system.");
}
if (!_.isEmpty(cordovaPlatforms)) {
// XXX COMPAT WITH 0.9.2.2 -- the --mobile-port option is deprecated
var mobileServerOption = options.server || options["mobile-port"];
if (!mobileServerOption) {
// For Cordova builds, require '--server'.
// XXX better error message?
Console.error("Supply the server hostname and port in the --server option " + "for mobile app builds.");
return 1;
}
parsedMobileServerUrl = parseMobileServerOption(mobileServerOption, 'server');
}
} else {
cordovaPlatforms = [];
}
var buildDir = projectContext.getProjectLocalDirectory('build_tar');
var outputPath = files.pathResolve(options.args[0]); // get absolute path
// Unless we're just making a tarball, warn if people try to build inside the
// app directory.
if (options.directory || !_.isEmpty(cordovaPlatforms)) {
var relative = files.pathRelative(options.appDir, outputPath);
// We would like the output path to be outside the app directory, which
// means the first step to getting there is going up a level.
if (relative.substr(0, 3) !== '..' + files.pathSep) {
Console.warn();
Console.labelWarn("The output directory is under your source tree.", "Your generated files may get interpreted as source code!", "Consider building into a different directory instead (" + Console.command("meteor build ../output") + ")", Console.options({ indent: 2 }));
Console.warn();
}
}
var bundlePath = options.directory ? options._serverOnly ? outputPath : files.pathJoin(outputPath, 'bundle') : files.pathJoin(buildDir, 'bundle');
stats.recordPackages({
what: "sdk.bundle",
projectContext: projectContext
});
var bundler = require('../isobuild/bundler.js');
var bundleResult = bundler.bundle({
projectContext: projectContext,
outputPath: bundlePath,
buildOptions: {
minifyMode: options.debug ? 'development' : 'production',
// XXX is this a good idea, or should linux be the default since
// that's where most people are deploying
// default? i guess the problem with using DEPLOY_ARCH as default
// is then 'meteor bundle' with no args fails if you have any local
// packages with binary npm dependencies
serverArch: bundleArch,
buildMode: options.debug ? 'development' : 'production'
},
providePackageJSONForUnavailableBinaryDeps: !!process.env.METEOR_BINARY_DEP_WORKAROUND
});
if (bundleResult.errors) {
Console.error("Errors prevented bundling:");
Console.error(bundleResult.errors.formatMessages());
return 1;
}
if (!options._serverOnly) files.mkdir_p(outputPath);
if (!options.directory) {
main.captureAndExit('', 'creating server tarball', function () {
try {
var outputTar = options._serverOnly ? outputPath : files.pathJoin(outputPath, appName + '.tar.gz');
files.createTarball(files.pathJoin(buildDir, 'bundle'), outputTar);
} catch (err) {
buildmessage.exception(err);
files.rm_recursive(buildDir);
}
});
}
if (!_.isEmpty(cordovaPlatforms)) {
(function () {
var cordovaProject = undefined;
main.captureAndExit('', function () {
buildmessage.enterJob({ title: "preparing Cordova project" }, function () {
cordovaProject = new _cordovaProjectJs.CordovaProject(projectContext, {
settingsFile: options.settings,
mobileServerUrl: utils.formatUrl(parsedMobileServerUrl) });
var plugins = cordova.pluginVersionsFromStarManifest(bundleResult.starManifest);
cordovaProject.prepareFromAppBundle(bundlePath, plugins);
});
for (var _iterator = cordovaPlatforms, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
if (_isArray) {
if (_i >= _iterator.length) break;
platform = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
platform = _i.value;
}
buildmessage.enterJob({ title: 'building Cordova app for ' + cordova.displayNameForPlatform(platform) }, function () {
var buildOptions = [];
if (!options.debug) buildOptions.push('--release');
cordovaProject.buildForPlatform(platform, buildOptions);
var buildPath = files.pathJoin(projectContext.getProjectLocalDirectory('cordova-build'), 'platforms', platform);
var platformOutputPath = files.pathJoin(outputPath, platform);
files.cp_r(buildPath, files.pathJoin(platformOutputPath, 'project'));
if (platform === 'ios') {
files.writeFile(files.pathJoin(platformOutputPath, 'README'), 'This is an auto-generated XCode project for your iOS application.\n\nInstructions for publishing your iOS app to App Store can be found at:\nhttps://github.com/meteor/meteor/wiki/How-to-submit-your-iOS-app-to-App-Store\n', "utf8");
} else if (platform === 'android') {
var apkPath = files.pathJoin(buildPath, 'build/outputs/apk', options.debug ? 'android-debug.apk' : 'android-release-unsigned.apk');
if (files.exists(apkPath)) {
files.copyFile(apkPath, files.pathJoin(platformOutputPath, options.debug ? 'debug.apk' : 'release-unsigned.apk'));
}
files.writeFile(files.pathJoin(platformOutputPath, 'README'), 'This is an auto-generated Gradle project for your Android application.\n\nInstructions for publishing your Android app to Play Store can be found at:\nhttps://github.com/meteor/meteor/wiki/How-to-submit-your-Android-app-to-Play-Store\n', "utf8");
}
});
}
});
})();
}
files.rm_recursive(buildDir);
};
///////////////////////////////////////////////////////////////////////////////
// lint
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'lint',
maxArgs: 0,
requiresAppOrPackage: true,
options: {
'allow-incompatible-updates': { type: Boolean }
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var packageDir = options.packageDir;
var appDir = options.appDir;
var projectContext = null;
// if the goal is to lint the package, don't include the whole app
if (packageDir) {
// similar to `meteor publish`, create a fake project
var tempProjectDir = files.mkdtemp('meteor-package-build');
projectContext = new projectContextModule.ProjectContext({
projectDir: tempProjectDir,
explicitlyAddedLocalPackageDirs: [packageDir],
packageMapFilename: files.pathJoin(packageDir, '.versions'),
alwaysWritePackageMap: true,
forceIncludeCordovaUnibuild: true,
allowIncompatibleUpdate: options['allow-incompatible-update'],
lintPackageWithSourceRoot: packageDir
});
main.captureAndExit("=> Errors while setting up package:", function () {
return(
// Read metadata and initialize catalog.
projectContext.initializeCatalog()
);
});
var versionRecord = projectContext.localCatalog.getVersionBySourceRoot(packageDir);
if (!versionRecord) {
throw Error("explicitly added local package dir missing?");
}
var packageName = versionRecord.packageName;
var constraint = utils.parsePackageConstraint(packageName);
projectContext.projectConstraintsFile.removeAllPackages();
projectContext.projectConstraintsFile.addConstraints([constraint]);
}
// linting the app
if (!projectContext && appDir) {
projectContext = new projectContextModule.ProjectContext({
projectDir: appDir,
serverArchitectures: [archinfo.host()],
allowIncompatibleUpdate: options['allow-incompatible-update'],
lintAppAndLocalPackages: true
});
}
main.captureAndExit("=> Errors prevented the build:", function () {
projectContext.prepareProjectForBuild();
});
var bundlePath = projectContext.getProjectLocalDirectory('build');
var bundler = require('../isobuild/bundler.js');
var bundle = bundler.bundle({
projectContext: projectContext,
outputPath: null,
buildOptions: {
minifyMode: 'development'
}
});
var displayName = options.packageDir ? 'package' : 'app';
if (bundle.errors) {
Console.error('=> Errors building your ' + displayName + ':\n\n' + bundle.errors.formatMessages());
throw new main.ExitWithCode(2);
}
if (bundle.warnings) {
Console.warn(bundle.warnings.formatMessages());
return 1;
}
return 0;
});
///////////////////////////////////////////////////////////////////////////////
// mongo
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'mongo',
maxArgs: 1,
options: {
url: { type: Boolean, short: 'U' }
},
requiresApp: function (options) {
return options.args.length === 0;
},
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var mongoUrl;
var usedMeteorAccount = false;
if (options.args.length === 0) {
// localhost mode
var findMongoPort = require('../runners/run-mongo.js').findMongoPort;
var mongoPort = findMongoPort(options.appDir);
// XXX detect the case where Meteor is running, but MONGO_URL was
// specified?
if (!mongoPort) {
Console.info("mongo: Meteor isn't running a local MongoDB server.");
Console.info();
Console.info('This command only works while Meteor is running your application locally. Start your application first with \'meteor\' and then run this command in a new terminal. This error will also occur if you asked Meteor to use a different MongoDB server with $MONGO_URL when you ran your application.');
Console.info();
Console.info('If you\'re trying to connect to the database of an app you deployed with ' + Console.command("'meteor deploy'") + ', specify your site\'s name as an argument to this command.');
return 1;
}
mongoUrl = "mongodb://127.0.0.1:" + mongoPort + "/meteor";
} else {
// remote mode
var site = qualifySitename(options.args[0]);
config.printUniverseBanner();
mongoUrl = deploy.temporaryMongoUrl(site);
usedMeteorAccount = true;
if (!mongoUrl)
// temporaryMongoUrl() will have printed an error message
return 1;
}
if (options.url) {
console.log(mongoUrl);
} else {
if (usedMeteorAccount) auth.maybePrintRegistrationLink();
process.stdin.pause();
var runMongo = require('../runners/run-mongo.js');
runMongo.runMongoShell(mongoUrl);
throw new main.WaitForExit();
}
});
///////////////////////////////////////////////////////////////////////////////
// reset
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'reset',
// Doesn't actually take an argument, but we want to print an custom
// error message if they try to pass one.
maxArgs: 1,
requiresApp: true,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (options.args.length !== 0) {
Console.error("meteor reset only affects the locally stored database.");
Console.error();
Console.error("To reset a deployed application use");
Console.error(Console.command("meteor deploy --delete appname"), Console.options({ indent: 2 }));
Console.error("followed by");
Console.error(Console.command("meteor deploy appname"), Console.options({ indent: 2 }));
return 1;
}
// XXX detect the case where Meteor is running the app, but
// MONGO_URL was set, so we don't see a Mongo process
var findMongoPort = require('../runners/run-mongo.js').findMongoPort;
var isRunning = !!findMongoPort(options.appDir);
if (isRunning) {
Console.error("reset: Meteor is running.");
Console.error();
Console.error("This command does not work while Meteor is running your application.", "Exit the running Meteor development server.");
return 1;
}
var localDir = files.pathJoin(options.appDir, '.meteor', 'local');
files.rm_recursive(localDir);
Console.info("Project reset.");
});
///////////////////////////////////////////////////////////////////////////////
// deploy
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'deploy',
minArgs: 1,
maxArgs: 1,
options: {
'delete': { type: Boolean, short: 'D' },
debug: { type: Boolean },
settings: { type: String },
// No longer supported, but we still parse it out so that we can
// print a custom error message.
password: { type: String },
// Override architecture to deploy whatever stuff we have locally, even if
// it contains binary packages that should be incompatible. A hack to allow
// people to deploy from checkout or do other weird shit. We are not
// responsible for the consequences.
'override-architecture-with-local': { type: Boolean },
'allow-incompatible-update': { type: Boolean }
},
requiresApp: function (options) {
return !options['delete'];
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var site = qualifySitename(options.args[0]);
config.printUniverseBanner();
if (options['delete']) {
return deploy.deleteApp(site);
}
if (options.password) {
Console.error("Setting passwords on apps is no longer supported. Now there are " + "user accounts and your apps are associated with your account so " + "that only you (and people you designate) can access them. See the " + Console.command("'meteor claim'") + " and " + Console.command("'meteor authorized'") + " commands.");
return 1;
}
var loggedIn = auth.isLoggedIn();
if (!loggedIn) {
Console.error("To instantly deploy your app on a free testing server,", "just enter your email address!");
Console.error();
if (!auth.registerOrLogIn()) return 1;
}
// Override architecture iff applicable.
var buildArch = DEPLOY_ARCH;
if (options['override-architecture-with-local']) {
Console.warn();
Console.labelWarn("OVERRIDING DEPLOY ARCHITECTURE WITH LOCAL ARCHITECTURE.", "If your app contains binary code, it may break in unexpected " + "and terrible ways.");
buildArch = archinfo.host();
}
var projectContext = new projectContextModule.ProjectContext({
projectDir: options.appDir,
serverArchitectures: _.uniq([buildArch, archinfo.host()]),
allowIncompatibleUpdate: options['allow-incompatible-update']
});
main.captureAndExit("=> Errors while initializing project:", function () {
projectContext.prepareProjectForBuild();
});
projectContext.packageMapDelta.displayOnConsole();
var buildOptions = {
minifyMode: options.debug ? 'development' : 'production',
buildMode: options.debug ? 'development' : 'production',
serverArch: buildArch
};
var deployResult = deploy.bundleAndDeploy({
projectContext: projectContext,
site: site,
settingsFile: options.settings,
buildOptions: buildOptions
});
if (deployResult === 0) {
auth.maybePrintRegistrationLink({
leadingNewline: true,
// If the user was already logged in at the beginning of the
// deploy, then they've already been prompted to set a password
// at least once before, so we use a slightly different message.
firstTime: !loggedIn
});
}
return deployResult;
});
///////////////////////////////////////////////////////////////////////////////
// logs
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'logs',
minArgs: 1,
maxArgs: 1,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var site = qualifySitename(options.args[0]);
return deploy.logs(site);
});
///////////////////////////////////////////////////////////////////////////////
// authorized
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'authorized',
minArgs: 1,
maxArgs: 1,
options: {
add: { type: String, short: "a" },
remove: { type: String, short: "r" },
list: { type: Boolean }
},
pretty: function (options) {
// pretty if we're mutating; plain if we're listing (which is more likely to
// be used by scripts)
return options.add || options.remove;
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (options.add && options.remove) {
Console.error("Sorry, you can only add or remove one user at a time.");
return 1;
}
if ((options.add || options.remove) && options.list) {
Console.error("Sorry, you can't change the users at the same time as", "you're listing them.");
return 1;
}
config.printUniverseBanner();
auth.pollForRegistrationCompletion();
var site = qualifySitename(options.args[0]);
if (!auth.isLoggedIn()) {
Console.error("You must be logged in for that. Try " + Console.command("'meteor login'"));
return 1;
}
if (options.add) return deploy.changeAuthorized(site, "add", options.add);else if (options.remove) return deploy.changeAuthorized(site, "remove", options.remove);else return deploy.listAuthorized(site);
});
///////////////////////////////////////////////////////////////////////////////
// claim
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'claim',
minArgs: 1,
maxArgs: 1,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
config.printUniverseBanner();
auth.pollForRegistrationCompletion();
var site = qualifySitename(options.args[0]);
if (!auth.isLoggedIn()) {
Console.error("You must be logged in to claim sites. Use " + Console.command("'meteor login'") + " to log in. If you don't have a " + "Meteor developer account yet, create one by clicking " + Console.command("'Sign in'") + " and then " + Console.command("'Create account'") + " at www.meteor.com.");
Console.error();
return 1;
}
return deploy.claim(site);
});
///////////////////////////////////////////////////////////////////////////////
// test-packages
///////////////////////////////////////////////////////////////////////////////
//
// Test your local packages.
//
main.registerCommand({
name: 'test-packages',
maxArgs: Infinity,
options: {
port: { type: String, short: "p", 'default': DEFAULT_PORT },
'mobile-server': { type: String },
// XXX COMPAT WITH 0.9.2.2
'mobile-port': { type: String },
'debug-port': { type: String },
deploy: { type: String },
production: { type: Boolean },
settings: { type: String },
velocity: { type: Boolean },
verbose: { type: Boolean, short: "v" },
// Undocumented. See #Once
once: { type: Boolean },
// Undocumented. To ensure that QA covers both
// PollingObserveDriver and OplogObserveDriver, this option
// disables oplog for tests. (It still creates a replset, it just
// doesn't do oplog tailing.)
'disable-oplog': { type: Boolean },
// Undocumented flag to use a different test driver.
'driver-package': { type: String, 'default': 'test-in-browser' },
// Sets the path of where the temp app should be created
'test-app-path': { type: String },
// Undocumented, runs tests under selenium
'selenium': { type: Boolean },
'selenium-browser': { type: String },
// Undocumented. Usually we just show a banner saying 'Tests' instead of
// the ugly path to the temporary test directory, but if you actually want
// to see it you can ask for it.
'show-test-app-path': { type: Boolean },
// hard-coded options with all known Cordova platforms
ios: { type: Boolean },
'ios-device': { type: Boolean },
android: { type: Boolean },
'android-device': { type: Boolean },
// This could theoretically be useful/necessary in conjunction with
// --test-app-path.
'allow-incompatible-update': { type: Boolean },
// Don't print linting messages for tested packages
'no-lint': { type: Boolean },
// allow excluding packages when testing all packages.
// should be a comma-separated list of package names.
'exclude': { type: String }
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
Console.setVerbose(!!options.verbose);
var runTargets = parseRunTargets(_.intersection(Object.keys(options), ['ios', 'ios-device', 'android', 'android-device']));
var _parseServerOptionsForRunCommand2 = parseServerOptionsForRunCommand(options, runTargets);
var parsedServerUrl = _parseServerOptionsForRunCommand2.parsedServerUrl;
var parsedMobileServerUrl = _parseServerOptionsForRunCommand2.parsedMobileServerUrl;
// Find any packages mentioned by a path instead of a package name. We will
// load them explicitly into the catalog.
var packagesByPath = _.filter(options.args, function (p) {
return p.indexOf('/') !== -1;
});
// Make a temporary app dir (based on the test runner app). This will be
// cleaned up on process exit. Using a temporary app dir means that we can
// run multiple "test-packages" commands in parallel without them stomping
// on each other.
var testRunnerAppDir = options['test-app-path'] || files.mkdtemp('meteor-test-run');
// Download packages for our architecture, and for the deploy server's
// architecture if we're deploying.
var serverArchitectures = [archinfo.host()];
if (options.deploy && DEPLOY_ARCH !== archinfo.host()) serverArchitectures.push(DEPLOY_ARCH);
// XXX Because every run uses a new app with its own IsopackCache directory,
// this always does a clean build of all packages. Maybe we can speed up
// repeated test-packages calls with some sort of shared or semi-shared
// isopack cache that's specific to test-packages? See #3012.
var projectContext = new projectContextModule.ProjectContext({
projectDir: testRunnerAppDir,
// If we're currently in an app, we still want to use the real app's
// packages subdirectory, not the test runner app's empty one.
projectDirForLocalPackages: options.appDir,
explicitlyAddedLocalPackageDirs: packagesByPath,
serverArchitectures: serverArchitectures,
allowIncompatibleUpdate: options['allow-incompatible-update'],
lintAppAndLocalPackages: !options['no-lint']
});
main.captureAndExit("=> Errors while setting up tests:", function () {
// Read metadata and initialize catalog.
projectContext.initializeCatalog();
});
// Overwrite .meteor/release.
projectContext.releaseFile.write(release.current.isCheckout() ? "none" : release.current.name);
var packagesToAdd = getTestPackageNames(projectContext, options.args);
// filter out excluded packages
var excludedPackages = options.exclude && options.exclude.split(',');
if (excludedPackages) {
packagesToAdd = _.filter(packagesToAdd, function (p) {
return !_.some(excludedPackages, function (excluded) {
return p.replace(/^local-test:/, '') === excluded;
});
});
}
// Use the driver package
// Also, add `autoupdate` so that you don't have to manually refresh the tests
packagesToAdd.unshift("autoupdate", options['driver-package']);
var constraintsToAdd = _.map(packagesToAdd, function (p) {
return utils.parsePackageConstraint(p);
});
// Add the packages to our in-memory representation of .meteor/packages. (We
// haven't yet resolved constraints, so this will affect constraint
// resolution.) This will get written to disk once we prepareProjectForBuild,
// either in the Cordova code below, right before deploying below, or in the
// app runner. (Note that removeAllPackages removes any comments from
// .meteor/packages, but that's OK since this isn't a real user project.)
projectContext.projectConstraintsFile.removeAllPackages();
projectContext.projectConstraintsFile.addConstraints(constraintsToAdd);
// Write these changes to disk now, so that if the first attempt to prepare
// the project for build hits errors, we don't lose them on
// projectContext.reset.
projectContext.projectConstraintsFile.writeIfModified();
// The rest of the projectContext preparation process will happen inside the
// runner, once the proxy is listening. The changes we made were persisted to
// disk, so projectContext.reset won't make us forget anything.
var cordovaRunner = undefined;
if (!_.isEmpty(runTargets)) {
main.captureAndExit('', 'preparing Cordova project', function () {
var cordovaProject = new _cordovaProjectJs.CordovaProject(projectContext, {
settingsFile: options.settings,
mobileServerUrl: utils.formatUrl(parsedMobileServerUrl) });
cordovaRunner = new _cordovaRunnerJs.CordovaRunner(cordovaProject, runTargets);
projectContext.platformList.write(cordovaRunner.platformsForRunTargets);
cordovaRunner.checkPlatformsForRunTargets();
});
}
options.cordovaRunner = cordovaRunner;
if (options.velocity) {
var serverUrlForVelocity = 'http://' + (parsedServerUrl.host || "localhost") + ':' + parsedServerUrl.port;
var velocity = require('../runners/run-velocity.js');
velocity.runVelocity(serverUrlForVelocity);
}
return runTestAppForPackages(projectContext, _.extend(options, { mobileServerUrl: utils.formatUrl(parsedMobileServerUrl) }));
});
// Returns the "local-test:*" package names for the given package names (or for
// all local packages if packageNames is empty/unspecified).
var getTestPackageNames = function (projectContext, packageNames) {
var packageNamesSpecifiedExplicitly = !_.isEmpty(packageNames);
if (_.isEmpty(packageNames)) {
// If none specified, test all local packages. (We don't have tests for
// non-local packages.)
packageNames = projectContext.localCatalog.getAllPackageNames();
}
var testPackages = [];
main.captureAndExit("=> Errors while collecting tests:", function () {
_.each(packageNames, function (p) {
buildmessage.enterJob("trying to test package `" + p + "`", function () {
// If it's a package name, look it up the normal way.
if (p.indexOf('/') === -1) {
if (p.indexOf('@') !== -1) {
buildmessage.error("You may not specify versions for local packages: " + p);
return; // recover by ignoring
}
// Check to see if this is a real local package, and if it is a real
// local package, if it has tests.
var version = projectContext.localCatalog.getLatestVersion(p);
if (!version) {
buildmessage.error("Not a known local package, cannot test");
} else if (version.testName) {
testPackages.push(version.testName);
} else if (packageNamesSpecifiedExplicitly) {
// It's only an error to *ask* to test a package with no tests, not
// to come across a package with no tests when you say "test all
// packages".
buildmessage.error("Package has no tests");
}
} else {
// Otherwise, it's a directory; find it by source root.
version = projectContext.localCatalog.getVersionBySourceRoot(files.pathResolve(p));
if (!version) {
throw Error("should have been caught when initializing catalog?");
}
if (version.testName) {
testPackages.push(version.testName);
}
// It is not an error to mention a package by directory that is a
// package but has no tests; this means you can run `meteor
// test-packages $APP/packages/*` without having to worry about the
// packages that don't have tests.
}
});
});
});
return testPackages;
};
var runTestAppForPackages = function (projectContext, options) {
var buildOptions = {
minifyMode: options.production ? 'production' : 'development',
buildMode: options.production ? 'production' : 'development'
};
if (options.deploy) {
// Run the constraint solver and build local packages.
main.captureAndExit("=> Errors while initializing project:", function () {
projectContext.prepareProjectForBuild();
});
// No need to display the PackageMapDelta here, since it would include all
// of the packages!
buildOptions.serverArch = DEPLOY_ARCH;
return deploy.bundleAndDeploy({
projectContext: projectContext,
site: options.deploy,
settingsFile: options.settings,
buildOptions: buildOptions,
recordPackageUsage: false
});
} else {
var runAll = require('../runners/run-all.js');
return runAll.run({
projectContext: projectContext,
proxyPort: options.port,
debugPort: options['debug-port'],
disableOplog: options['disable-oplog'],
settingsFile: options.settings,
banner: options['show-test-app-path'] ? null : "Tests",
buildOptions: buildOptions,
rootUrl: process.env.ROOT_URL,
mongoUrl: process.env.MONGO_URL,
oplogUrl: process.env.MONGO_OPLOG_URL,
mobileServerUrl: options.mobileServerUrl,
once: options.once,
recordPackageUsage: false,
selenium: options.selenium,
seleniumBrowser: options['selenium-browser'],
cordovaRunner: options.cordovaRunner,
// On the first run, we shouldn't display the delta between "no packages
// in the temp app" and "all the packages we're testing". If we make
// changes and reload, though, it's fine to display them.
omitPackageMapDeltaDisplayOnFirstRun: true
});
}
};
///////////////////////////////////////////////////////////////////////////////
// rebuild
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'rebuild',
maxArgs: Infinity,
hidden: true,
requiresApp: true,
catalogRefresh: new catalog.Refresh.Never(),
'allow-incompatible-update': { type: Boolean }
}, function (options) {
var projectContextModule = require('../project-context.js');
var projectContext = new projectContextModule.ProjectContext({
projectDir: options.appDir,
forceRebuildPackages: options.args.length ? options.args : true,
allowIncompatibleUpdate: options['allow-incompatible-update']
});
main.captureAndExit("=> Errors while rebuilding packages:", function () {
projectContext.prepareProjectForBuild();
});
projectContext.packageMapDelta.displayOnConsole();
Console.info("Packages rebuilt.");
});
///////////////////////////////////////////////////////////////////////////////
// login
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'login',
options: {
email: { type: Boolean }
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
return auth.loginCommand(_.extend({
overwriteExistingToken: true
}, options));
});
///////////////////////////////////////////////////////////////////////////////
// logout
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'logout',
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
return auth.logoutCommand(options);
});
///////////////////////////////////////////////////////////////////////////////
// whoami
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'whoami',
catalogRefresh: new catalog.Refresh.Never(),
pretty: false
}, function (options) {
return auth.whoAmICommand(options);
});
///////////////////////////////////////////////////////////////////////////////
// organizations
///////////////////////////////////////////////////////////////////////////////
var loggedInAccountsConnectionOrPrompt = function (action) {
var token = auth.getSessionToken(config.getAccountsDomain());
if (!token) {
Console.error("You must be logged in to " + action + ".");
auth.doUsernamePasswordLogin({ retry: true });
Console.info();
}
token = auth.getSessionToken(config.getAccountsDomain());
var conn = auth.loggedInAccountsConnection(token);
if (conn === null) {
// Server rejected our token.
Console.error("You must be logged in to " + action + ".");
auth.doUsernamePasswordLogin({ retry: true });
Console.info();
token = auth.getSessionToken(config.getAccountsDomain());
conn = auth.loggedInAccountsConnection(token);
}
return conn;
};
// List the organizations of which the current user is a member.
main.registerCommand({
name: 'admin list-organizations',
minArgs: 0,
maxArgs: 0,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var token = auth.getSessionToken(config.getAccountsDomain());
if (!token) {
Console.error("You must be logged in to list your organizations.");
auth.doUsernamePasswordLogin({ retry: true });
Console.info();
}
var url = config.getAccountsApiUrl() + "/organizations";
try {
var result = httpHelpers.request({
url: url,
method: "GET",
useSessionHeader: true,
useAuthHeader: true
});
var body = JSON.parse(result.body);
} catch (err) {
Console.error("Error listing organizations.");
return 1;
}
if (result.response.statusCode === 401 && body && body.error === "invalid_credential") {
Console.error("You must be logged in to list your organizations.");
// XXX It would be nice to do a username/password prompt here like
// we do for the other orgs commands.
return 1;
}
if (result.response.statusCode !== 200 || !body || !body.organizations) {
Console.error("Error listing organizations.");
return 1;
}
if (body.organizations.length === 0) {
Console.info("You are not a member of any organizations.");
} else {
Console.rawInfo(_.pluck(body.organizations, "name").join("\n") + "\n");
}
return 0;
});
main.registerCommand({
name: 'admin members',
minArgs: 1,
maxArgs: 1,
options: {
add: { type: String },
remove: { type: String },
list: { type: Boolean }
},
pretty: function (options) {
// pretty if we're mutating; plain if we're listing (which is more likely to
// be used by scripts)
return options.add || options.remove;
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (options.add && options.remove) {
Console.error("Sorry, you can only add or remove one member at a time.");
throw new main.ShowUsage();
}
config.printUniverseBanner();
var username = options.add || options.remove;
var conn = loggedInAccountsConnectionOrPrompt(username ? "edit organizations" : "show an organization's members");
if (username) {
// Adding or removing members
try {
conn.call(options.add ? "addOrganizationMember" : "removeOrganizationMember", options.args[0], username);
} catch (err) {
Console.error("Error " + (options.add ? "adding" : "removing") + " member: " + err.reason);
return 1;
}
Console.info(username + " " + (options.add ? "added to" : "removed from") + " organization " + options.args[0] + ".");
} else {
// Showing the members of an org
try {
var result = conn.call("showOrganization", options.args[0]);
} catch (err) {
Console.error("Error showing organization: " + err.reason);
return 1;
}
var members = _.pluck(result, "username");
Console.rawInfo(members.join("\n") + "\n");
}
return 0;
});
///////////////////////////////////////////////////////////////////////////////
// self-test
///////////////////////////////////////////////////////////////////////////////
// XXX we should find a way to make self-test fully self-contained, so that it
// ignores "packageDirs" (ie, it shouldn't fail just because you happen to be
// sitting in an app with packages that don't build)
main.registerCommand({
name: 'self-test',
minArgs: 0,
maxArgs: 1,
options: {
changed: { type: Boolean },
'force-online': { type: Boolean },
slow: { type: Boolean },
galaxy: { type: Boolean },
browserstack: { type: Boolean },
history: { type: Number },
list: { type: Boolean },
file: { type: String },
exclude: { type: String }
},
hidden: true,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (!files.inCheckout()) {
Console.error("self-test is only supported running from a checkout");
return 1;
}
var selftest = require('../tool-testing/selftest.js');
// Auto-detect whether to skip 'net' tests, unless --force-online is passed.
var offline = false;
if (!options['force-online']) {
try {
require('../utils/http-helpers.js').getUrl("http://www.google.com/");
} catch (e) {
if (e instanceof files.OfflineError) offline = true;
}
}
var compileRegexp = function (str) {
try {
return new RegExp(str);
} catch (e) {
if (!(e instanceof SyntaxError)) throw e;
Console.error("Bad regular expression: " + str);
return null;
}
};
var testRegexp = undefined;
if (options.args.length) {
testRegexp = compileRegexp(options.args[0]);
if (!testRegexp) {
return 1;
}
}
var fileRegexp = undefined;
if (options.file) {
fileRegexp = compileRegexp(options.file);
if (!fileRegexp) {
return 1;
}
}
var excludeRegexp = undefined;
if (options.exclude) {
excludeRegexp = compileRegexp(options.exclude);
if (!excludeRegexp) {
return 1;
}
}
if (options.list) {
selftest.listTests({
onlyChanged: options.changed,
offline: offline,
includeSlowTests: options.slow,
galaxyOnly: options.galaxy,
testRegexp: testRegexp,
fileRegexp: fileRegexp
});
return 0;
}
var clients = {
browserstack: options.browserstack
};
return selftest.runTests({
// filtering options
onlyChanged: options.changed,
offline: offline,
includeSlowTests: options.slow,
galaxyOnly: options.galaxy,
testRegexp: testRegexp,
fileRegexp: fileRegexp,
excludeRegexp: excludeRegexp,
// other options
historyLines: options.history,
clients: clients
});
});
///////////////////////////////////////////////////////////////////////////////
// list-sites
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'list-sites',
minArgs: 0,
maxArgs: 0,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
auth.pollForRegistrationCompletion();
if (!auth.isLoggedIn()) {
Console.error("You must be logged in for that. Try " + Console.command("'meteor login'") + ".");
return 1;
}
return deploy.listSites();
});
///////////////////////////////////////////////////////////////////////////////
// admin get-machine
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'admin get-machine',
minArgs: 1,
maxArgs: 1,
options: {
json: { type: Boolean },
verbose: { type: Boolean, short: "v" },
// By default, we give you a machine for 5 minutes. You can request up to
// 15. (MDG can reserve machines for longer than that.)
minutes: { type: Number }
},
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
// Check that we are asking for a valid architecture.
var arch = options.args[0];
if (!_.has(VALID_ARCHITECTURES, arch)) {
showInvalidArchMsg(arch);
return 1;
}
// Set the minutes. We will check validity on the server.
var minutes = options.minutes || 5;
// In verbose mode, we let you know what is going on.
var maybeLog = function (string) {
if (options.verbose) {
Console.info(string);
}
};
try {
maybeLog("Logging into the get-machines server ...");
var conn = authClient.loggedInConnection(config.getBuildFarmUrl(), config.getBuildFarmDomain(), "build-farm");
} catch (err) {
authClient.handleConnectionError(err, "get-machines server");
return 1;
}
try {
maybeLog("Reserving machine ...");
// The server returns to us an object with the following keys:
// username & sshKey : use this to log in.
// host: what you login into
// port: port you should use
// hostKey: RSA key to compare for safety.
var ret = conn.call('createBuildServer', arch, minutes);
} catch (err) {
authClient.handleConnectionError(err, "build farm");
return 1;
}
conn.close();
// Possibly, the user asked us to return a JSON of the data and is going to process it
// themselves. In that case, let's do that and exit.
if (options.json) {
var retJson = {
'username': ret.username,
'host': ret.host,
'port': ret.port,
'key': ret.sshKey,
'hostKey': ret.hostKey
};
Console.rawInfo(JSON.stringify(retJson, null, 2) + "\n");
return 0;
}
// Record the SSH Key in a temporary file on disk and give it the permissions
// that ssh-agent requires it to have.
var tmpDir = files.mkdtemp('meteor-ssh-');
var idpath = tmpDir + '/id';
maybeLog("Writing ssh key to " + idpath);
files.writeFile(idpath, ret.sshKey, { encoding: 'utf8', mode: 256 });
// Add the known host key to a custom known hosts file.
var hostpath = tmpDir + '/host';
var addendum = ret.host + " " + ret.hostKey + "\n";
maybeLog("Writing host key to " + hostpath);
files.writeFile(hostpath, addendum, 'utf8');
// Finally, connect to the machine.
var login = ret.username + "@" + ret.host;
var maybeVerbose = options.verbose ? "-v" : "-q";
var connOptions = [login, "-i" + idpath, "-p" + ret.port, "-oUserKnownHostsFile=" + hostpath, maybeVerbose];
var printOptions = connOptions.join(' ');
maybeLog("Connecting: " + Console.command("ssh " + printOptions));
var child_process = require('child_process');
var future = new Future();
if (arch.match(/win/)) {
// The ssh output from Windows machines is buggy, it can overlay your
// existing output on the top of the screen which is very ugly. Force the
// screen cleaning to assist.
Console.clear();
}
var sshCommand = child_process.spawn("ssh", connOptions, { stdio: 'inherit' }); // Redirect spawn stdio to process
sshCommand.on('error', function (err) {
if (err.code === "ENOENT") {
if (process.platform === "win32") {
Console.error("Could not find the `ssh` command in your PATH.", "Please read this page about using the get-machine command on Windows:", Console.url("https://github.com/meteor/meteor/wiki/Accessing-Meteor-provided-build-machines-from-Windows"));
} else {
Console.error("Could not find the `ssh` command in your PATH.");
}
future['return'](1);
}
});
sshCommand.on('exit', function (code, signal) {
if (signal) {
// XXX: We should process the signal in some way, but I am not sure we
// care right now.
future['return'](1);
} else {
future['return'](code);
}
});
var sshEnd = future.wait();
return sshEnd;
});
///////////////////////////////////////////////////////////////////////////////
// admin progressbar-test
///////////////////////////////////////////////////////////////////////////////
// A test command to print a progressbar. Useful for manual testing.
main.registerCommand({
name: 'admin progressbar-test',
options: {
secs: { type: Number, 'default': 20 },
spinner: { type: Boolean, 'default': false }
},
hidden: true,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
buildmessage.enterJob({ title: "A test progressbar" }, function () {
var doneFuture = new Future();
var progress = buildmessage.getCurrentProgressTracker();
var totalProgress = { current: 0, end: options.secs, done: false };
var i = 0;
var n = options.secs;
if (options.spinner) {
totalProgress.end = undefined;
}
var updateProgress = function () {
i++;
if (!options.spinner) {
totalProgress.current = i;
}
if (i === n) {
totalProgress.done = true;
progress.reportProgress(totalProgress);
doneFuture['return']();
} else {
progress.reportProgress(totalProgress);
setTimeout(updateProgress, 1000);
}
};
setTimeout(updateProgress);
doneFuture.wait();
});
});
///////////////////////////////////////////////////////////////////////////////
// dummy
///////////////////////////////////////////////////////////////////////////////
// Dummy test command. Used for automated testing of the command line
// option parser.
main.registerCommand({
name: 'dummy',
options: {
ething: { type: String, short: "e", required: true },
port: { type: Number, short: "p", 'default': DEFAULT_PORT },
url: { type: Boolean, short: "U" },
'delete': { type: Boolean, short: "D" },
changed: { type: Boolean }
},
maxArgs: 2,
hidden: true,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var p = function (key) {
if (_.has(options, key)) return JSON.stringify(options[key]);
return 'none';
};
Console.info(p('ething') + " " + p('port') + " " + p('changed') + " " + p('args'));
if (options.url) Console.info('url');
if (options['delete']) Console.info('delete');
});
///////////////////////////////////////////////////////////////////////////////
// throw-error
///////////////////////////////////////////////////////////////////////////////
// Dummy test command. Used to test that stack traces work from an installed
// Meteor tool.
main.registerCommand({
name: 'throw-error',
hidden: true,
catalogRefresh: new catalog.Refresh.Never()
}, function () {
throw new Error("testing stack traces!"); // #StackTraceTest this line is found in tests/source-maps.js
});
//# sourceMappingURL=commands.js.map | lpinto93/meteor | tools/cli/commands.js | JavaScript | mit | 76,122 |
# MilkshakeAndMouse
An online store for organic/cruelty free merchandise.
| Wimsy113/MilkshakeAndMouse | README.md | Markdown | mit | 75 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0037)http://notefeeder.heroku.com/500.html -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="/stylesheets/front_page.css" media="screen" rel="stylesheet" type="text/css">
<title>notefeeder: whoops!</title>
</head>
<body>
<h1> <a href="http://notefeeder.heroku.com/">note feeder</a> <div id="underline"></div> </h1>
<div class="content_area">
<h2>Whoops!</h2>
<p>
The change you tried to make was rejected<br/>
Either your messing around with things or we have a problem.
</p>
If you think this is a real error and you've got a minute I'd really appresheate an email with the url you were trying to reach and maybe a short description of whatever you were trying to doing.
<p> email: davidhampgonsavles(at)gmail.com </p>
<div id="error_code">error 404</div>
</div>
</body></html>
| davidhampgonsalves/notefeeder | public/422.html | HTML | mit | 1,097 |
from attributes import *
from constants import *
# ------------------------------------------------------------------------------
#
class UnitManager (Attributes) :
"""
UnitManager class -- manages a pool
"""
# --------------------------------------------------------------------------
#
def __init__ (self, url=None, scheduler='default', session=None) :
Attributes.__init__ (self)
# --------------------------------------------------------------------------
#
def add_pilot (self, pid) :
"""
add (Compute or Data)-Pilot(s) to the pool
"""
raise Exception ("%s.add_pilot() is not implemented" % self.__class__.__name__)
# --------------------------------------------------------------------------
#
def list_pilots (self, ptype=ANY) :
"""
List IDs of data and/or compute pilots
"""
raise Exception ("%s.list_pilots() is not implemented" % self.__class__.__name__)
# --------------------------------------------------------------------------
#
def remove_pilot (self, pid, drain=False) :
"""
Remove pilot(s) (does not cancel the pilot(s), but removes all units
from the pilot(s).
`drain` determines what happens to the units which are managed by the
removed pilot(s). If `True`, the pilot removal is delayed until all
units reach a final state. If `False` (the default), then `RUNNING`
units will be canceled, and `PENDING` units will be re-assinged to the
unit managers for re-scheduling to other pilots.
"""
raise Exception ("%s.remove_pilot() is not implemented" % self.__class__.__name__)
# --------------------------------------------------------------------------
#
def submit_unit (self, description) :
"""
Instantiate and return (Compute or Data)-Unit object(s)
"""
raise Exception ("%s.submit_unit() is not implemented" % self.__class__.__name__)
# --------------------------------------------------------------------------
#
def list_units (self, utype=ANY) :
"""
List IDs of data and/or compute units
"""
raise Exception ("%s.list_units() is not implemented" % self.__class__.__name__)
# --------------------------------------------------------------------------
#
def get_unit (self, uids) :
"""
Reconnect to and return (Compute or Data)-Unit object(s)
"""
raise Exception ("%s.get_unit() is not implemented" % self.__class__.__name__)
# --------------------------------------------------------------------------
#
def wait_unit (self, uids, state=[DONE, FAILED, CANCELED], timeout=-1.0) :
"""
Wait for given unit(s) to enter given state
"""
raise Exception ("%s.wait_unit() is not implemented" % self.__class__.__name__)
# --------------------------------------------------------------------------
#
def cancel_units (self, uids) :
"""
Cancel given unit(s)
"""
raise Exception ("%s.cancel_unit() is not implemented" % self.__class__.__name__)
# ------------------------------------------------------------------------------
#
| JensTimmerman/radical.pilot | docs/architecture/api_draft/unit_manager.py | Python | mit | 3,311 |
'use strict';
angular.module('terminaaliApp')
.factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) {
var currentUser = {};
if($cookieStore.get('token')) {
currentUser = User.get();
}
return {
/**
* Authenticate user and save token
*
* @param {Object} user - login info
* @param {Function} callback - optional
* @return {Promise}
*/
login: function(user, callback) {
var cb = callback || angular.noop;
var deferred = $q.defer();
$http.post('/auth/local', {
email: user.email,
password: user.password
}).
success(function(data) {
$cookieStore.put('token', data.token);
currentUser = User.get();
deferred.resolve(data);
return cb();
}).
error(function(err) {
this.logout();
deferred.reject(err);
return cb(err);
}.bind(this));
return deferred.promise;
},
/**
* Delete access token and user info
*
* @param {Function}
*/
logout: function() {
$cookieStore.remove('token');
currentUser = {};
},
/**
* Create a new user
*
* @param {Object} user - user info
* @param {Function} callback - optional
* @return {Promise}
*/
createUser: function(user, callback) {
var cb = callback || angular.noop;
return User.save(user,
function(data) {
$cookieStore.put('token', data.token);
currentUser = User.get();
return cb(user);
},
function(err) {
this.logout();
return cb(err);
}.bind(this)).$promise;
},
/**
* Change password
*
* @param {String} oldPassword
* @param {String} newPassword
* @param {Function} callback - optional
* @return {Promise}
*/
changePassword: function(oldPassword, newPassword, callback) {
var cb = callback || angular.noop;
return User.changePassword({ id: currentUser._id }, {
oldPassword: oldPassword,
newPassword: newPassword
}, function(user) {
return cb(user);
}, function(err) {
return cb(err);
}).$promise;
},
/**
* Gets all available info on authenticated user
*
* @return {Object} user
*/
getCurrentUser: function() {
return currentUser;
},
/**
* Check if a user is logged in
*
* @return {Boolean}
*/
isLoggedIn: function() {
return currentUser.hasOwnProperty('role');
},
/**
* Waits for currentUser to resolve before checking if user is logged in
*/
isLoggedInAsync: function(cb) {
if(currentUser.hasOwnProperty('$promise')) {
currentUser.$promise.then(function() {
cb(true);
}).catch(function() {
cb(false);
});
} else if(currentUser.hasOwnProperty('role')) {
cb(true);
} else {
cb(false);
}
},
/**
* Check if a user is an admin
*
* @return {Boolean}
*/
isAdmin: function() {
return currentUser.role === 'admin';
},
/**
* Get auth token
*/
getToken: function() {
return $cookieStore.get('token');
}
};
});
| henrikre/terminaali | client/components/auth/auth.service.js | JavaScript | mit | 3,575 |
$(document).ready(function(){
var toggleMuffEditor = function(stat=false){
$("#muff-opt").remove();
// bind event
if(stat){
$(".muff").mouseover(function() {
$("#muff-opt").remove();
muffShowOptions($(this));
$(window).scroll(function(){
$("#muff-opt").remove();
})
});
}else{// unbind event
$(".muff").unbind("mouseover");
}
};
function muffShowOptions( e ){
var t = "";
var id = e.attr("data-muff-id");
var title = e.attr("data-muff-title");
var p = e.offset();
var opttop = p.top + 15;
var optleft = p.left + 5;
if(e.hasClass("muff-div")){ t="div";
}else if(e.hasClass("muff-text")){ t="text";
}else if(e.hasClass("muff-a")){ t="link";
}else if(e.hasClass("muff-img")){ t="image";
}
if(!title){ title = t;}
// check position is beyond document
if((p.left + 25 + 75) > $(window).width()){
optleft -= 75;
}
var opt = "<div id='muff-opt' style='position:absolute;top:"+opttop+"px;left:"+optleft+"px;z-index:99998;display:none;'>";
opt += "<a href='admin/"+t+"/"+id+"/edit' class='mbtn edit'></a>";
opt += "<a href='admin/"+t+"/delete/' class='mbtn delete' data-mod='"+t+"' data-id='"+id+"'></a>";
opt += "<span>"+title+"</span>";
opt += "</div>";
$("body").prepend(opt);
$("#muff-opt").slideDown(300);
$("body").find("#muff-opt > a.delete").click(function(e){
var path = $(this).attr('href');
var mod = $(this).attr('data-mod');
// e.preventDefault();
swal({
title: "Are you sure?",
text: "You are about to delete this "+mod,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "Cancel",
closeOnConfirm: true,
closeOnCancel: true
},
function(isConfirm){
if (isConfirm) {
// window.location.href = path;
proceedDelete(path, id);
}
});
return false;
});
}
toggleMuffEditor(false);
// set checkbox editor event
$("input[name=cb-muff-editor]").click(function(){
if($(this).is(':checked')){ toggleMuffEditor(true); }
else{ toggleMuffEditor(false) }
});
function proceedDelete(path, id){
var newForm = jQuery('<form>', {
'action': path,
'method': 'POST',
'target': '_top'
}).append(jQuery('<input>', {
'name': '_token',
'value': $("meta[name=csrf-token]").attr("content"),
'type': 'hidden'
})).append(jQuery('<input>', {
'name': 'id',
'value': id,
'type': 'hidden'
}));
newForm.hide().appendTo("body").submit();
}
// $(".opt-div a.delete, .w-conf a.delete, .w-conf-hvr a.delete").click(function(e){
// var path = $(this).attr('href');
// var mod = $(this).attr('data-mod');
// // e.preventDefault();
// swal({
// title: "Are you sure?",
// text: "You are about to delete this "+mod,
// type: "warning",
// showCancelButton: true,
// confirmButtonColor: "#DD6B55",
// confirmButtonText: "Yes, delete it!",
// cancelButtonText: "Cancel",
// closeOnConfirm: true,
// closeOnCancel: true
// },
// function(isConfirm){
// if (isConfirm) {
// window.location.href = path;
// }
// });
// return false;
// });
// top nav click
$(".top-nav>li").click(function(){
var i = $(this).find('.dropdown-menu');
toggleClassExcept('.top-nav .dropdown-menu', 'rmv', 'active', i);
i.toggleClass("active");
});
/** toggle a certain class except the given object
* works with li and lists
* @param id identifier
* @param a action
* @param c class
* @param ex object
*/
function toggleClassExcept(id, a, c, ex){
$(id).each(function(){
switch(a){
case 'remove':
case 'rmv':
if(!$(this).is(ex)) $(this).removeClass(c);
break;
case 'add':
if(!$(this).is(ex)) $(this).addClass(c);
break;
default:
break;
}
});
}
$(".w-add .muff-add").click(function(event){
event.preventDefault();
var b = $(this);
var newForm = jQuery('<form>', {
'action': b.data('href'),
'method': 'GET',
'target': '_top'
}).append(jQuery('<input>', {
'name': '_token',
'value': $("meta[name=csrf-token]").attr("content"),
'type': 'hidden'
})).append(jQuery('<input>', {
'name': 'url',
'value': $("meta[name=muffin-url]").attr("content"),
'type': 'hidden'
})).append(jQuery('<input>', {
'name': 'location',
'value': b.data("loc"),
'type': 'hidden'
}));
// console.log(newForm);
newForm.hide().appendTo("body").submit();
})
// TAGs
//var tagArea = '.tag-area';
if($('.tagarea')[0]){
var backSpace;
var close = '<a class="close"></a>';
var PreTags = $('.tagarea').val().trim().split(" ");
$('.tagarea').after('<ul class="tag-box"></ul>');
for (i=0 ; i < PreTags.length; i++ ){
var pretag = PreTags[i].split("_").join(" ");
if($('.tagarea').val().trim() != "" )
$('.tag-box').append('<li class="tags"><input type="hidden" name="tags[]" value="'+pretag+'">'+pretag+close+'</li>');
}
$('.tag-box').append('<li class="new-tag"><input class="input-tag" type="text"></li>');
// unbind submit form when pressing enter
$('.input-tag').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
});
// Taging
$('.input-tag').bind("keydown", function (kp) {
var tag = $('.input-tag').val().trim();
if(tag.length > 0){
$(".tags").removeClass("danger");
if(kp.keyCode == 13 || kp.keyCode == 9){
$(".new-tag").before('<li class="tags"><input type="hidden" name="tags[]" value="'+tag+'">'+tag+close+'</li>');
$(this).val('');
}}
else {if(kp.keyCode == 8 ){
if($(".new-tag").prev().hasClass("danger")){
$(".new-tag").prev().remove();
}else{
$(".new-tag").prev().addClass("danger");
}
}
}
});
//Delete tag
$(".tag-box").on("click", ".close", function() {
$(this).parent().remove();
});
$(".tag-box").click(function(){
$('.input-tag').focus();
});
// Edit
$('.tag-box').on("dblclick" , ".tags", function(cl){
var tags = $(this);
var tag = tags.text().trim();
$('.tags').removeClass('edit');
tags.addClass('edit');
tags.html('<input class="input-tag" value="'+tag+'" type="text">')
$(".new-tag").hide();
tags.find('.input-tag').focus();
tag = $(this).find('.input-tag').val() ;
$('.tags').dblclick(function(){
tags.html(tag + close);
$('.tags').removeClass('edit');
$(".new-tag").show();
});
tags.find('.input-tag').bind("keydown", function (edit) {
tag = $(this).val() ;
if(edit.keyCode == 13){
$(".new-tag").show();
$('.input-tag').focus();
$('.tags').removeClass('edit');
if(tag.length > 0){
tags.html('<input type="hidden" name="tags[]" value="'+tag+'">'+tag + close);
}
else{
tags.remove();
}
}
});
});
}
// sorting
// $(function() {
// $( ".tag-box" ).sortable({
// items: "li:not(.new-tag)",
// containment: "parent",
// scrollSpeed: 100
// });
// $( ".tag-box" ).disableSelection();
// });
});
| johnguild/muffincms | src/Public/main/js/muffincms.js | JavaScript | mit | 7,581 |
---
layout: page
title: Version history
permalink: "setup/en/releasenotes/"
language: en
---
#### vNext
* __New__ FileCopy Add-In: parameter sourceTimeFilter also for FILE and SFTP protocol.
#### 1.4.5
* __New__ New Add-In List2Csv to export SharePoint Online lists to CSV files.
* __New__ New add-in SharepointToDB to export items from SharePoint Online document libraries or lists to a database.
* __New__ FileCopy Add-In: Files can be downloaded from SharePoint Online document libraries.
* __New__ SharepointEraser Add-In: New parameters "subFolder" and "recursive".
* __New__ display of the alarm history (list of the most recently sent alarms).
* __BREAKING CHANGE__ FileCopy FileCopy Add-In: If "destinationProtocol" = SHAREPOINT, the URL to the document library must be specified again in the "destinationSystem" parameter.
#### 1.4.3
* __New__ Ldap2CSV Add-In: New data type "bitmask"
* __New__ Csv2Database Add-In: New parameter "fileNameColumn"
* __New__ display of utilization
* __Error__ Csv2Database Add-In: Overly long texts are shortened to the length of the database field
* __Error__ WebConnect: : JSON return value formatting corrected, logging improved
* __Error__ OneMessageAddIn: OneMessageAddIn: Error corrected if no trace was used
#### 1.4.1
* __Error__ instances of OneOffixxDocumentCreator not running in parallel
* __Error__ Csv2Database Add-In: Support of tabs as separators, support of column names with special characters
* __New__ FileCopy Add-In: New parameter "skipExistingFiles"
#### 1.4.0
* __New__ FileCopy Add-In: Support for a "Filter" event with which another Add-In can manipulate the file to be copied
* __New__ TextReplace add-in
* __New__ MailSender Add-In: Support of TLS and authentication
* __New__ configurator role can be defined for each instance
* __New__ display of version number and modification date of an add-in
* __New__ Improved display of alerts for many email addresses
* __New__ Improved display of rule execution time in the overview
* __New__ statistics can be updated manually
* __New__ statistics can also be displayed as tables
* __New__ context menu in log analysis for filtering log entries for an instance
* __Error__ Users who are not in the configurator role can no longer copy or delete instances via the context menu
* __Error__ Parameter values containing XML tags could not be saved correctly
* __Error__ Multi-line parameters were not handled correctly (DatabaseToCsv, DatabaseMaintenance, Dispatcher, Csv2Database)
* __Error__ No more session timeout in web administration
#### 1.3.0
* __New__ DatabaseMaintenance Add-In: Possibility to execute any SQL command
* __New__ The order of the statistics can be changed using drag and drop
* __New__ New parameter type for multi-line texts (see DatabaseToCsv, DatabaseMaintenance, Dispatcher, Csv2Database)
* __New__ display of the OneConnexx version in the web administration, reference to incompatible versions
#### 1.2.1
* __New__ list of installations is sorted alphabetically by name
* __New__ FileEraser Add-In supports multiple search patterns
* __New__ page "Alerting" is now a subpage of "Monitoring"
* __New__ New page "Statistics"
* __New__ Improved display for small screen widths (e.g. mobile devices)
* __New__ possibility to check rules only on certain days of the week or days of the month
* __New__ Standard texts can be defined in Web.config for new alarms
* __New__ option in log analysis to display the latest entries at the top
* __New__ rules and alarms can be exported as an Excel file
* __New__ rules and alerts can be filtered according to active / inactive
* __New__ option to issue alerts only in the event of rule violations and not for every faulty transaction
* __New__ FileCopy Add-In: Possibility to upload files> 2MB to SharePoint Online
* __New__ Xls2Csv add-in
* __New__ Csv2Database add-in
* __Error__ If the list of installations contained old entries with the same port number, the wrong connection string may have been used
* __Error__ FileCopy Add-In: deleting and archiving on SFTP Server did not work
* __Error__ FileCopy Add-In: If parameters were set by a Dispatcher Add-In and the configuration changed at the same time, the parameters were reset again
* __Error__ FileCopy Add-In: file name is written to transaction
* __Error__ FileCopy Add-In: Absolute paths now also work with the SFTP protocol
* __Error__ FileCopy Add-In: FTPS supports newer protocols
* __Error__ Ldap2CSV: Date format now also works for date fields
* __Error__ Immediately after renaming an instance, parameter changes were not saved
* __Error__ Improved bug behavior when moving instances to interfaces
* __Error__ In the HTML view, changes to the email text of alerts were not saved
* __Error__ Encoding Error loading transactions on the "monitoring"
* __Error__ log analysis did not work if there are other files in the "Logs" directory
* __Error__ Real-time log is reset each time the page is reloaded, otherwise the browser freezes with large amounts of data
* __Error__ Ldap2CSV, Xml2Csv: Ldap2CSV, Xml2Csv: double quotation marks if necessary
#### 1.1.4
* __Error__ corrected bizagi / OneMessage transformation
#### 1.1.3
* __New__ status of the checkbox and interfaces on the Monitoring / Overview page is saved in a cookie
* __Error__ corrected wrong English date format to the Monitoring page / Overview
* __Error__ corrected wrong English date format to the Monitoring page / Overview
#### 1.1.2
* __New__ tandard add-in "OneMessageAdapter"
* __New__ context menu in the tree for instances, add-ins and groups
* __Error__ error message in web administration if 'installation' directory is missing
* __Error__ grouping by add-in or group is saved permanently
* __Error__ order of the instances within a group was not always saved correctly
* __Error__ 'Last 5 min' button on the log analysis page did not update the start time
* __Error__ log files are now written in UTF-8 by default
#### 1.1.0
* __New__ OneConnexx installations are saved under %ProgramData%\Sevitec\OneConnexx\Installations and can no longer be added manually in the web administration
| Sevitec/oneconnexx-docs | _pages/setup/en/releasenotes.md | Markdown | mit | 6,144 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = undefined;
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _objectAssign = require('object-assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _rcTable = require('rc-table');
var _rcTable2 = _interopRequireDefault(_rcTable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var __assign = undefined && undefined.__assign || Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
}
return t;
};
var Table = function (_React$Component) {
(0, _inherits3["default"])(Table, _React$Component);
function Table() {
(0, _classCallCheck3["default"])(this, Table);
return (0, _possibleConstructorReturn3["default"])(this, _React$Component.apply(this, arguments));
}
Table.prototype.render = function render() {
var _props = this.props,
columns = _props.columns,
dataSource = _props.dataSource,
direction = _props.direction,
scrollX = _props.scrollX,
titleFixed = _props.titleFixed;
var _props2 = this.props,
style = _props2.style,
className = _props2.className;
var restProps = (0, _objectAssign2["default"])({}, this.props);
['style', 'className'].forEach(function (prop) {
if (restProps.hasOwnProperty(prop)) {
delete restProps[prop];
}
});
var table = void 0;
// 默认纵向
if (!direction || direction === 'vertical') {
if (titleFixed) {
table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", scroll: { x: true }, showHeader: false }));
} else {
table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", scroll: { x: scrollX } }));
}
} else if (direction === 'horizon') {
columns[0].className = 'am-table-horizonTitle';
table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", showHeader: false, scroll: { x: scrollX } }));
} else if (direction === 'mix') {
columns[0].className = 'am-table-horizonTitle';
table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", scroll: { x: scrollX } }));
}
return _react2["default"].createElement("div", { className: className, style: style }, table);
};
return Table;
}(_react2["default"].Component);
exports["default"] = Table;
Table.defaultProps = {
dataSource: [],
prefixCls: 'am-table'
};
module.exports = exports['default']; | forwk1990/wechart-checkin | antd-mobile-custom/antd-mobile/lib/table/index.web.js | JavaScript | mit | 3,649 |
package jp.opap.material.model
import java.util.UUID
import jp.opap.data.yaml.Node
import jp.opap.material.data.Collections.{EitherSeq, Seqs}
import jp.opap.material.facade.GitLabRepositoryLoaderFactory.GitlabRepositoryInfo
import jp.opap.material.model.RepositoryConfig.RepositoryInfo
import jp.opap.material.model.Warning.GlobalWarning
import scala.util.matching.Regex
case class RepositoryConfig(repositories: List[RepositoryInfo])
object RepositoryConfig {
val PATTERN_ID: Regex = "^[a-z0-9_-]+$".r
val WARNING_INVALID_ID: String = "%1$s - このIDは不正です。IDは、 /^[a-z0-9_-]+$/ でなければなりません。"
val WARNING_NO_SUCH_PROTOCOL: String = "%1$s - そのような取得方式はありません。"
val WARNING_DUPLICATED_ID: String = "%1$s - このIDは重複しています。"
/**
* 取得するリポジトリの情報を表現するクラスです。
*/
trait RepositoryInfo {
/**
* システム内での、このリポジトリの識別子です。
* システム内で一意かつ、ファイル名として正しい文字列でなければなりません。
*/
val id: String
/**
* このリポジトリの名称です。ウェブページ上で表示されます。
*/
val title: String
}
def fromYaml(document: Node): (List[Warning], RepositoryConfig) = {
def extractItem(node: Node): Either[Warning, RepositoryInfo] = {
withWarning(GlobalContext) {
val id = node("id").string.get.toLowerCase
if (PATTERN_ID.findFirstIn(id).isEmpty)
throw DeserializationException(WARNING_INVALID_ID.format(id), Option(node))
node("protocol").string.get match {
case "gitlab" =>
GitlabRepositoryInfo(id, node("title").string.get, node("host").string.get, node("namespace").string.get, node("name").string.get)
case protocol => throw DeserializationException(WARNING_NO_SUCH_PROTOCOL.format(protocol), Option(node))
}
}
}
def validate(warnings: List[Warning], config: RepositoryConfig): (List[Warning], RepositoryConfig) = {
val duplications = config.repositories.groupByOrdered(info => info.id)
.filter(entry => entry._2.size > 1)
val duplicationSet = duplications.map(_._1).toSet
val c = config.copy(repositories = config.repositories.filter(r => !duplicationSet.contains(r.id)))
val w = duplications.map(entry => new GlobalWarning(UUID.randomUUID(), WARNING_DUPLICATED_ID.format(entry._1)))
(warnings ++ w, c)
}
val repositories = withWarnings(GlobalContext) {
val items = document("repositories").list.map(extractItem).toList
items.left -> RepositoryConfig(items.right.toList)
}
validate(repositories._1.toList, repositories._2.getOrElse(RepositoryConfig(List())))
}
}
| opap-jp/material-explorer | rest/src/main/scala/jp/opap/material/model/RepositoryConfig.scala | Scala | mit | 2,845 |
const _cache = Dict{AbstractString,Array}()
function fetch_word_list(filename::AbstractString)
haskey(_cache, filename) && return _cache[filename]
try
io = open(filename, "r")
words = map(x -> chomp(x), readlines(io))
close(io)
ret = convert(Array{UTF8String,1}, words)
_cache[filename] = ret
return ret
catch
error("Failed to fetch word list from $(filename)")
end
end
| slundberg/Languages.jl | src/utils.jl | Julia | mit | 408 |
<!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_11) on Sun Aug 31 14:44:00 IST 2014 -->
<title>Uses of Class org.symboltable.Edge</title>
<meta name="date" content="2014-08-31">
<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="Uses of Class org.symboltable.Edge";
}
}
catch(err) {
}
//-->
</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="../../../org/symboltable/package-summary.html">Package</a></li>
<li><a href="../../../org/symboltable/Edge.html" title="class in org.symboltable">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/symboltable/class-use/Edge.html" target="_top">Frames</a></li>
<li><a href="Edge.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>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.symboltable.Edge" class="title">Uses of Class<br>org.symboltable.Edge</h2>
</div>
<div class="classUseContainer">No usage of org.symboltable.Edge</div>
<!-- ======= 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="../../../org/symboltable/package-summary.html">Package</a></li>
<li><a href="../../../org/symboltable/Edge.html" title="class in org.symboltable">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/symboltable/class-use/Edge.html" target="_top">Frames</a></li>
<li><a href="Edge.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>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| shivam091/Symbol-Table | Symbol Table/doc/org/symboltable/class-use/Edge.html | HTML | mit | 4,022 |
# Parser.Many<T> method
Always succeeds. The value is a collection of as many items as can be successfully parsed.
```csharp
public static IParser<IReadOnlyList<T>> Many<T>(this IParser<T> parser)
```
## See Also
* interface [IParser<T>](../IParser-1.md)
* class [Parser](../Parser.md)
* namespace [Faithlife.Parsing](../../Faithlife.Parsing.md)
<!-- DO NOT EDIT: generated by xmldocmd for Faithlife.Parsing.dll -->
| Faithlife/Parsing | docs/Faithlife.Parsing/Parser/Many.md | Markdown | mit | 436 |
using System.ComponentModel;
namespace NSysmon.Collector.HAProxy
{
/// <summary>
/// Current server statuses
/// </summary>
public enum ProxyServerStatus
{
[Description("Status Unknown!")]
None = 0, //Won't be populated for backends
[Description("Server is up, status normal.")]
ActiveUp = 2,
[Description("Server has not responded to checks in a timely manner, going down.")]
ActiveUpGoingDown = 8,
[Description("Server is responsive and recovering.")]
ActiveDownGoingUp = 6,
[Description("Backup server is up, status normal.")]
BackupUp = 3,
[Description("Backup server has not responded to checks in a timely manner, going down.")]
BackupUpGoingDown = 9,
[Description("Backup server is responsive and recovering.")]
BackupDownGoingUp = 7,
[Description("Server is not checked.")]
NotChecked = 4,
[Description("Server is down and receiving no requests.")]
Down = 10,
[Description("Server is in maintenance and receiving no requests.")]
Maintenance = 5,
[Description("Front end is open to receiving requests.")]
Open = 1
}
public static class ProxyServerStatusExtensions
{
public static string ShortDescription(this ProxyServerStatus status)
{
switch (status)
{
case ProxyServerStatus.ActiveUp:
return "Active";
case ProxyServerStatus.ActiveUpGoingDown:
return "Active (Up -> Down)";
case ProxyServerStatus.ActiveDownGoingUp:
return "Active (Down -> Up)";
case ProxyServerStatus.BackupUp:
return "Backup";
case ProxyServerStatus.BackupUpGoingDown:
return "Backup (Up -> Down)";
case ProxyServerStatus.BackupDownGoingUp:
return "Backup (Down -> Up)";
case ProxyServerStatus.NotChecked:
return "Not Checked";
case ProxyServerStatus.Down:
return "Down";
case ProxyServerStatus.Maintenance:
return "Maintenance";
case ProxyServerStatus.Open:
return "Open";
//case ProxyServerStatus.None:
default:
return "Unknown";
}
}
public static bool IsBad(this ProxyServerStatus status)
{
switch (status)
{
case ProxyServerStatus.ActiveUpGoingDown:
case ProxyServerStatus.BackupUpGoingDown:
case ProxyServerStatus.Down:
return true;
default:
return false;
}
}
}
} | clearwavebuild/nsysmon | NSysmon.Collector/HAProxy/ProxyServerStatus.cs | C# | mit | 2,906 |
import datetime
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from .models import Action
def create_action(user, verb, target=None):
now = timezone.now()
last_minute = now - datetime.timedelta(seconds=60)
similar_actions = Action.objects.filter(user_id=user.id, verb=verb, created__gte=last_minute)
if target:
target_ct = ContentType.objects.get_for_model(target)
similar_actions = Action.objects.filter(target_ct=target_ct, target_id=target.id)
if not similar_actions:
action = Action(user=user, verb=verb, target=target)
action.save()
return True
return False
| EssaAlshammri/django-by-example | bookmarks/bookmarks/actions/utils.py | Python | mit | 679 |
package engine;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
public class CircleShape extends Shape {
double radius; //radius of shape
public CircleShape(double rad, Vector2D v, double r, double d, Color c) {
super(v, r, d, c);
radius = rad;
}
@Override
public void calculateInertia() {
mass = radius * radius * Math.PI * density;
inertia = radius * radius * mass;
}
@Override
public void paint(Graphics2D g) {
super.paint(g);
vector.readyPoint();
g.fillOval((int) (x - radius), (int) (y - radius), (int) radius * 2, (int) radius * 2);
g.drawOval((int) (x - radius), (int) (y - radius), (int) radius * 2, (int) radius * 2);
g.setColor(Color.BLACK);
g.drawLine((int) (x), (int) (y), (int) (x + Math.cos(rotation) * radius), (int) (y + Math.sin(rotation) * radius));
}
@Override
public boolean contains(Point.Double p) {
return p.distanceSq(x, y) < radius * radius;
}
}
| bjornenalfa/GA | src/engine/CircleShape.java | Java | mit | 1,041 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M19.99 9.79c.51-.4.51-1.18 0-1.58l-6.76-5.26c-.72-.56-1.73-.56-2.46 0L9.41 4.02l7.88 7.88 2.7-2.11zm0 3.49l-.01-.01a.991.991 0 00-1.22 0l-.05.04 1.4 1.4c.37-.41.34-1.07-.12-1.43zm1.45 5.6L4.12 1.56a.9959.9959 0 00-1.41 0c-.39.39-.39 1.02 0 1.41l3.52 3.52-2.22 1.72c-.51.4-.51 1.18 0 1.58l6.76 5.26c.72.56 1.73.56 2.46 0l.87-.68 1.42 1.42-2.92 2.27c-.36.28-.87.28-1.23 0l-6.15-4.78a.991.991 0 00-1.22 0c-.51.4-.51 1.17 0 1.57l6.76 5.26c.72.56 1.73.56 2.46 0l3.72-2.89 3.07 3.07c.39.39 1.02.39 1.41 0 .41-.39.41-1.02.02-1.41z" />
, 'LayersClearRounded');
| kybarg/material-ui | packages/material-ui-icons/src/LayersClearRounded.js | JavaScript | mit | 673 |
Deprecated.
See:
- [TRex Collection](https://github.com/Raphhh/trex-collection): PHP helpers for collections.
- [TRex Reflection](https://github.com/Raphhh/trex-reflection): PHP tool to reflect callables an types.
- [TRex parser](https://github.com/Raphhh/trex-parser): PHP tool to parse code and extract statements.
- [TRex Cli](https://github.com/Raphhh/trex-cli): Command process helper.
| Raphhh/trex | README.md | Markdown | mit | 396 |
sandbox.lua
===========
A pure-lua solution for running untrusted Lua code.
The default behavior is restricting access to "dangerous" functions in Lua, such as `os.execute`.
It's possible to provide extra functions via the `options.env` parameter.
Infinite loops are prevented via the `debug` library.
For now, sandbox.lua only works with Lua 5.1.x.
Usage
=====
Require the module like this:
``` lua
local sandbox = require 'sandbox'
```
### sandbox.protect
`sandbox.protect(f)` (or `sandbox(f)`) produces a sandboxed version of `f`. `f` can be a Lua function or a string with Lua code.
A sandboxed function works as regular functions as long as they don't access any insecure features:
```lua
local sandboxed_f = sandbox(function() return 'hey' end)
local msg = sandboxed_f() -- msg is now 'hey'
```
Sandboxed options can not access unsafe Lua modules. (See the [source code](https://github.com/kikito/sandbox.lua/blob/master/sandbox.lua#L35) for a list)
When a sandboxed function tries to access an unsafe module, an error is produced.
```lua
local sf = sandbox.protect(function()
os.execute('rm -rf /') -- this will throw an error, no damage done
end)
sf() -- error: os.execute not found
```
Sandboxed functions will eventually throw an error if they contain infinite loops:
```lua
local sf = sandbox.protect(function()
while true do end
end)
sf() -- error: quota exceeded
```
### options.quota
`sandbox.lua` prevents infinite loops from halting the program by hooking the `debug` library to the sandboxed function, and "counting instructions". When
the instructions reach a certain limit, an error is produced.
This limit can be tweaked via the `quota` option. But default, it is 500000.
It is not possible to exhaust the machine with infinite loops; the following will throw an error after invoking 500000 instructions:
``` lua
sandbox.run('while true do end') -- raise errors after 500000 instructions
sandbox.run('while true do end', {quota=10000}) -- raise error after 10000 instructions
```
Note that if the quota is low enough, sandboxed functions that do lots of calculations might fail:
``` lua
local f = function()
local count = 1
for i=1, 400 do count = count + 1 end
return count
end
sandbox.run(f, {quota=100}) -- raises error before the function ends
```
### options.env
Use the `env` option to inject additional variables to the environment in which the sandboxed function is executed.
local msg = sandbox.run('return foo', {env = {foo = 'This is a global var on the the environment'}})
Note that the `env` variable will be modified by the sandbox (adding base modules like `string`). The sandboxed code can also modify it. It is
recommended to discard it after use.
local env = {amount = 1}
sandbox.run('amount = amount + 1', {env = env})
assert(env.amount == 2)
### sandbox.run
`sandbox.run(f)` sanboxes and executes `f` in a single line. `f` can be either a string or a function
You can pass `options` param, and it will work like in `sandbox.protect`.
Any extra parameters will just be passed to the sandboxed function when executed.
In other words, `sandbox.run(f, o, ...)` is equivalent to `sandbox.protect(f,o)(...)`.
Notice that if `f` throws an error, it is *NOT* captured by `sandbox.run`. Use `pcall` if you want your app to be immune to errors, like this:
``` lua
local ok, result = pcall(sandbox.run, 'error("this just throws an error")')
```
Installation
============
Just copy sandbox.lua wherever you need it.
License
=======
This library is released under the MIT license. See MIT-LICENSE.txt for details
Specs
=====
This project uses [telescope](https://github.com/norman/telescope) for its specs. In order to run them, install it and then:
```
cd /path/to/where/the/spec/folder/is
tsc spec/*
```
I would love to use [busted](http://olivinelabs.com/busted/), but it has some incompatibility with `debug.sethook(f, "", quota)` and the tests just hanged up.
| APItools/sandbox.lua | README.md | Markdown | mit | 3,966 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ms_MY" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About DarkSwift</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>DarkSwift</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The DarkSwift developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Klik dua kali untuk mengubah alamat atau label</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Cipta alamat baru</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Salin alamat terpilih ke dalam sistem papan klip</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your DarkSwift addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a DarkSwift address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified DarkSwift address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Padam</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Fail yang dipisahkan dengan koma</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-58"/>
<source>DarkSwift will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show information about DarkSwift</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>Pilihan</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Send coins to a DarkSwift address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for DarkSwift</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-202"/>
<source>DarkSwift</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+180"/>
<source>&About DarkSwift</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>DarkSwift client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to DarkSwift network</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About DarkSwift card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about DarkSwift card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid DarkSwift address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. DarkSwift can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid DarkSwift address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>DarkSwift-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start DarkSwift after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start DarkSwift on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the DarkSwift client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the DarkSwift network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting DarkSwift.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show DarkSwift addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting DarkSwift.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the DarkSwift network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the DarkSwift-Qt help message to get a list with possible DarkSwift command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>DarkSwift - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>DarkSwift Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the DarkSwift debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the DarkSwift RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 BOST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Baki</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 BOST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a DarkSwift address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid DarkSwift address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a DarkSwift address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this DarkSwift address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified DarkSwift address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a DarkSwift address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter DarkSwift signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Fail yang dipisahkan dengan koma</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>DarkSwift version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or DarkSwiftd</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: DarkSwift.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: DarkSwiftd.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong DarkSwift will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=DarkSwiftrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "DarkSwift Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. DarkSwift is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>DarkSwift</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of DarkSwift</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart DarkSwift to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. DarkSwift is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | DarkSwift/DarkSwift | src/qt/locale/bitcoin_ms_MY.ts | TypeScript | mit | 107,393 |
# Worker Glass [Unmaintained]
**Note**: This library is no longer in use in the Karafka ecosystem. It was developed for Karafka versions prior to `1.0`. If you're using this library and want to take it over, please ping us.
[](https://github.com/karafka/worker-glass/actions?query=workflow%3Aci)
[](http://badge.fury.io/rb/worker-glass)
[](https://gitter.im/karafka/karafka)
WorkerGlass provides optional timeout and after failure (reentrancy) for background processing worker engines (like Sidekiq, Resque, etc).
## Reentrancy
If you don't know what is reentrancy, you can read about it [here](http://dev.mensfeld.pl/2014/05/ruby-rails-sinatra-background-processing-reentrancy-for-your-workers-is-a-must-be/).
## Setup
If you want to use timeout and/or reentrancy, please add appropriate modules into your worker.
WorkerGlass allows to configure following options:
| Method | Arguments | Description |
|------------------|-----------|------------------------------------------------------------------------------------------|
| self.logger= | Logger | Set logger which will be used by Worker Glass (if not defined, null logger will be used) |
## Usage
WorkerGlass has few submodules that you can prepend to your workers to obtain given functionalities:
| Module | Description |
|-------------------------|-------------------------------------------------------------------|
| WorkerGlass::Reentrancy | Provides additional reentrancy layer if anything goes wrong |
| WorkerGlass::Timeout | Allows to set a timeout after which a given worker task will fail |
### WorkerGlass::Timeout
If you want to provide timeouts for your workers, just prepend WorkerGlass::Timeout to your worker and set the timeout value:
```ruby
class Worker2
prepend WorkerGlass::Timeout
self.timeout = 60 # 1 minute timeout
def perform(first_param, second_param, third_param)
SomeService.new.process(first_param, second_param, third_param)
end
end
Worker2.perform_async(example1, example2, example3)
```
### WorkerGlass::Reentrancy
If you want to provide reentrancy for your workers, just prepend WorkerGlass::Reentrancy to your worker and define **after_failure** method that will be executed upon failure:
```ruby
class Worker3
prepend WorkerGlass::Reentrancy
def perform(first_param, second_param, third_param)
SomeService.new.process(first_param, second_param, third_param)
end
def after_failure(first_param, second_param, third_param)
SomeService.new.reset_state(first_param, second_param, third_param)
end
end
Worker3.perform_async(example1, example2, example3)
```
## References
* [Karafka framework](https://github.com/karafka/karafka)
* [Worker Glass Actions CI](https://github.com/karafka/worker-glass/actions?query=workflow%3Aci)
* [Worker Glass Coditsu](https://app.coditsu.io/karafka/repositories/worker-glass)
## Note on contributions
First, thank you for considering contributing to Worker Glass! It's people like you that make the open source community such a great community!
Each pull request must pass all the RSpec specs and meet our quality requirements.
To check if everything is as it should be, we use [Coditsu](https://coditsu.io) that combines multiple linters and code analyzers for both code and documentation. Once you're done with your changes, submit a pull request.
Coditsu will automatically check your work against our quality standards. You can find your commit check results on the [builds page](https://app.coditsu.io/karafka/repositories/worker-glass/builds/commit_builds) of Worker Glass repository.
| karafka/sidekiq-glass | README.md | Markdown | mit | 3,985 |
# -*- coding: utf-8 -*-
#
# RedPipe documentation build configuration file, created by
# sphinx-quickstart on Wed Apr 19 13:22:45 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
import os
import sys
from os import path
ROOTDIR = path.abspath(os.path.dirname(os.path.dirname(__file__)))
sys.path.insert(0, ROOTDIR)
import redpipe # noqa
extensions = [
'alabaster',
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'RedPipe'
copyright = u'2017, John Loehrer'
author = u'John Loehrer'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = redpipe.__version__
# The full version, including alpha/beta/rc tags.
release = redpipe.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
'logo': 'redpipe-logo.gif',
'github_banner': True,
'github_user': '72squared',
'github_repo': 'redpipe',
'travis_button': True,
'analytics_id': 'UA-98626018-1',
}
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'relations.html',
'searchbox.html',
]
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'RedPipedoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'RedPipe.tex', u'%s Documentation' % project,
u'John Loehrer', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, project, u'%s Documentation' % project,
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, project, u'%s Documentation' % project,
author, project, 'making redis pipelines easy in python',
'Miscellaneous'),
]
suppress_warnings = ['image.nonlocal_uri']
| 72squared/redpipe | docs/conf.py | Python | mit | 5,400 |
import {
assign,
forEach,
isArray
} from 'min-dash';
var abs= Math.abs,
round = Math.round;
var TOLERANCE = 10;
export default function BendpointSnapping(eventBus) {
function snapTo(values, value) {
if (isArray(values)) {
var i = values.length;
while (i--) if (abs(values[i] - value) <= TOLERANCE) {
return values[i];
}
} else {
values = +values;
var rem = value % values;
if (rem < TOLERANCE) {
return value - rem;
}
if (rem > values - TOLERANCE) {
return value - rem + values;
}
}
return value;
}
function mid(element) {
if (element.width) {
return {
x: round(element.width / 2 + element.x),
y: round(element.height / 2 + element.y)
};
}
}
// connection segment snapping //////////////////////
function getConnectionSegmentSnaps(context) {
var snapPoints = context.snapPoints,
connection = context.connection,
waypoints = connection.waypoints,
segmentStart = context.segmentStart,
segmentStartIndex = context.segmentStartIndex,
segmentEnd = context.segmentEnd,
segmentEndIndex = context.segmentEndIndex,
axis = context.axis;
if (snapPoints) {
return snapPoints;
}
var referenceWaypoints = [
waypoints[segmentStartIndex - 1],
segmentStart,
segmentEnd,
waypoints[segmentEndIndex + 1]
];
if (segmentStartIndex < 2) {
referenceWaypoints.unshift(mid(connection.source));
}
if (segmentEndIndex > waypoints.length - 3) {
referenceWaypoints.unshift(mid(connection.target));
}
context.snapPoints = snapPoints = { horizontal: [] , vertical: [] };
forEach(referenceWaypoints, function(p) {
// we snap on existing bendpoints only,
// not placeholders that are inserted during add
if (p) {
p = p.original || p;
if (axis === 'y') {
snapPoints.horizontal.push(p.y);
}
if (axis === 'x') {
snapPoints.vertical.push(p.x);
}
}
});
return snapPoints;
}
eventBus.on('connectionSegment.move.move', 1500, function(event) {
var context = event.context,
snapPoints = getConnectionSegmentSnaps(context),
x = event.x,
y = event.y,
sx, sy;
if (!snapPoints) {
return;
}
// snap
sx = snapTo(snapPoints.vertical, x);
sy = snapTo(snapPoints.horizontal, y);
// correction x/y
var cx = (x - sx),
cy = (y - sy);
// update delta
assign(event, {
dx: event.dx - cx,
dy: event.dy - cy,
x: sx,
y: sy
});
});
// bendpoint snapping //////////////////////
function getBendpointSnaps(context) {
var snapPoints = context.snapPoints,
waypoints = context.connection.waypoints,
bendpointIndex = context.bendpointIndex;
if (snapPoints) {
return snapPoints;
}
var referenceWaypoints = [ waypoints[bendpointIndex - 1], waypoints[bendpointIndex + 1] ];
context.snapPoints = snapPoints = { horizontal: [] , vertical: [] };
forEach(referenceWaypoints, function(p) {
// we snap on existing bendpoints only,
// not placeholders that are inserted during add
if (p) {
p = p.original || p;
snapPoints.horizontal.push(p.y);
snapPoints.vertical.push(p.x);
}
});
return snapPoints;
}
eventBus.on('bendpoint.move.move', 1500, function(event) {
var context = event.context,
snapPoints = getBendpointSnaps(context),
target = context.target,
targetMid = target && mid(target),
x = event.x,
y = event.y,
sx, sy;
if (!snapPoints) {
return;
}
// snap
sx = snapTo(targetMid ? snapPoints.vertical.concat([ targetMid.x ]) : snapPoints.vertical, x);
sy = snapTo(targetMid ? snapPoints.horizontal.concat([ targetMid.y ]) : snapPoints.horizontal, y);
// correction x/y
var cx = (x - sx),
cy = (y - sy);
// update delta
assign(event, {
dx: event.dx - cx,
dy: event.dy - cy,
x: event.x - cx,
y: event.y - cy
});
});
}
BendpointSnapping.$inject = [ 'eventBus' ]; | pedesen/diagram-js | lib/features/bendpoints/BendpointSnapping.js | JavaScript | mit | 4,283 |
var changeSpan;
var i = 0;
var hobbies = [
'Music',
'HTML5',
'Learning',
'Exploring',
'Art',
'Teaching',
'Virtual Reality',
'The Cosmos',
'Unity3D',
'Tilemaps',
'Reading',
'Butterscotch',
'Drawing',
'Taking Photos',
'Smiles',
'The Poetics of Space',
'Making Sounds',
'Board games',
'Travelling',
'Sweetened condensed milk'
];
function changeWord() {
changeSpan.textContent = hobbies[i];
i++;
if (i >= hobbies.length) i = 0;
}
function init() {
console.log('initialising scrolling text');
changeSpan = document.getElementById("scrollingText");
nIntervId = setInterval(changeWord, 950);
changeWord();
}
if (document.addEventListener) {
init();
} else {
init();
} | oddgoo/oddgoo.com | static/js/hobbies.js | JavaScript | mit | 725 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CodePen - A Pen by Justin Kams</title>
</head>
<body>
<html>
<head>
<title>The Basics of The Web and HTML</title>
</head>
<body>
<h2>The Basics of The Web and HTML</h2>
<p><em></em></p>
<p><em><h3>The Basics of the World Wide Web</h3></em>
The world wide web is a collection of computers with html files on them. The computers communcate
and share the html files when the user requests it in the browser. When a person goes to a web
page like <a href="www.google.com">www.google.com</a>, their computer sends a HTTP Request to
a server. The server finds the appropriate<b> HTML</b> document and sends it back to the user's
computer where a web browser interprets the page and displays it on the user's screen.</p>
<p><em><h3>HTML</h3></em>
<b>HTML</b> stands for <em>Hypertext Markup Language</em>. <b>HTML</b> documents form the majority of the content
on the web. <b>HTML</b> documents contain text content which describes <em>"what you see"</em> and markup
which describes <em>"how it looks"</em>. This video gives a good overview.</p>
<p><em><h3>Tags and Elements</h3></em>
<b>HTML</b> documents are made of <b>HTML</b> elements. When writing <b>HTML</b>, we tell browsers the
type of each element by using <b>HTML</b> tags. This video explains the distinction well.</p>
<p><em><h3>HTML Attributes</h3></em>
There are many attributes. One for starters is the anchor tag. The anchor tag is used to include
links in the material. These tags would be nested in the less than greater brackets, and consist
of <em>'a href="link" /a'</em>. View this webpage for a
<a href="http://www.w3schools.com/tags/tag_a.asp">description</a>.
</p>
<p><em><h3>Images</h3></em>
Images can be added to web content. These tags will again have the less than and greater than
brackets surrounding them, and consist of <em>'img src="url" alt="text"'</em>.
These tags are known as void tags and do not need content included. Also the alt attribute at
the end of the tag, diplays text in the event the image request is broken.
</p>
<p><em><h3>Whitespace</h3></em>
Browsers automatically put text on one line, unless told othrwise. To render text on multiple
lines, use the tag <em>'br'</em> which stands for break, or <em>'p'</em>, which stands for
paragraph.
</p>
<p><em><h3>Why Computers are Stupid</h3></em>
Computers are stupid because they interpret instructions literally. This makes them very
unforgiving since a small mistake by a programmer can cause huge problems in a program.</p>
<p><em><h3>Inline vs Block Elements</h3></em>
HTML elements are either inline or block. Block elements form an <em>"invisible box"</em> around the
content inside of them.</p>
<p><em><h3>HTML Document</h3></em>
Lastly a typical html document will be ordered as follows:
<ol>
<li>!DOCTYPE HTML</li>
<li>html</li>
<li>head</li>
<li>/head</li>
<li>body</li>
<li>tags 'content' /tags</li>
<li>/body</li>
<li>/html</li>
</ol>
</p>
</body>
</html>
</body>
</html> | westlyheinrich/getting-started-with-html | index.html | HTML | mit | 3,084 |
<?php
namespace App\Http\ViewComposers;
use App\Models\Character;
use App\Models\Message;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
class CharacterMessagesComposer
{
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$data = $view->getData();
/** @var Character $currentCharacter */
/** @var Character $otherCharacter */
$currentCharacter = Auth::user()->character;
$otherCharacter = Arr::get($data, 'character');
$messages = Message::query()->where(function (Builder $query) use ($currentCharacter, $otherCharacter) {
$query->where([
'to_id' => $currentCharacter->id,
'from_id' => $otherCharacter->id,
]);
})->orWhere(function (Builder $query) use ($currentCharacter, $otherCharacter) {
$query->where([
'to_id' => $otherCharacter->id,
'from_id' => $currentCharacter->id,
]);
})->orderByDesc('created_at')->paginate(5);
$otherCharacter->sentMessages()->whereIn('id', $messages->pluck('id'))->markAsRead();
$contentLimit = Message::CONTENT_LIMIT;
$view->with(compact('messages', 'currentCharacter', 'otherCharacter', 'contentLimit'));
}
}
| mchekin/rpg | app/Http/ViewComposers/CharacterMessagesComposer.php | PHP | mit | 1,435 |
---
layout: default
archive: true
---
<script src="https://apis.google.com/js/platform.js" async defer></script>
<article class="post">
<header>
<h1>{{ page.title }}</h1>
<h2 class="headline">{{ page.date | date:"%B %-d, %Y" }}</h2>
</header>
<section id="post-body">
{{content}}
{% assign post = page %}
{% if post.tags.size > 0 %}
{% capture tags_content %}Posted with {% if post.tags.size == 1 %}<i class="fa fa-tag"></i>{% else %}<i class="fa fa-tags"></i>{% endif %}: {% endcapture %}
{% for post_tag in post.tags %}
{% for data_tag in site.data.tags %}
{% if data_tag.slug == post_tag %}
{% assign tag = data_tag %}
{% endif %}
{% endfor %}
{% if tag %}
{% capture tags_content_temp %}{{ tags_content }}<a href="/blog/tag/{{ tag.slug }}/">{{ tag.name }}</a>{% if forloop.last == false %}, {% endif %}{% endcapture %}
{% assign tags_content = tags_content_temp %}
{% endif %}
{% endfor %}
{% else %}
{% assign tags_content = '' %}
{% endif %}
</section>
</article>
<footer id="post-meta" class="clearfix">
<form style="border:1px solid #ccc;padding:3px;text-align:center;" action="https://tinyletter.com/MozillaTN" method="post" target="popupwindow" onsubmit="window.open('https://tinyletter.com/MozillaTN', 'popupwindow', 'scrollbars=yes,width=800,height=600');return true"><p><label for="tlemail">Enter your email address To our Community Mailing List</label></p><p><input type="text" style="width:140px" name="email" id="tlemail" /></p><input type="hidden" value="1" name="embed"/><input type="submit" value="Subscribe" />
</form>
{% assign author = site.data.people[page.author] %}
<a href="/about/{{ page.author }}">
<img class="avatar" src="{{ author.gravatar}}">
<div>
<span class="dark">{{ author.name }}</span>
</div>
</a>
<p>{{ tags_content }}</p>
<section id="sharing">
{% include share.html %}
</section>
</footer>
{% include pagination.html %}
<!-- Disqus comments -->
{% if site.disqus %}
<div class="archive readmore">
<h3>Comments</h3>
{% include disqus.html %}
</div>
{% endif %}
<!-- Archive post list -->
{% if page.archive %}
<ul id="post-list" class="archive readmore">
<h3>Read more</h3>
{% for post in site.posts limit:10 %}
<li>
<a href="{{ site.baseurl }}{{ post.url | remove_first: '/' }}">{{ post.title }}<aside class="dates">{{ post.date | date:"%b %d" }}</aside></a>
</li>
{% endfor %}
</ul>
{% endif %}
| MozillaTN/mozillatn.github.io | _layouts/post.html | HTML | mit | 2,663 |
from src.tools.dictionaries import PostLoadedDict
# Utility class
################################################
class ServerImplementationDict(PostLoadedDict):
def __missing__(self, key):
try:
return super().__missing__(key)
except KeyError:
return NotImplemented
################################################
class Server():
def __init__(self, shortname, loader):
# Not preloaded
# loaders must produce dictionaries (or an appropriate iterable)
# with the required keys.
# The reason for this is that code for certain servers need not be loaded
# if it's not going to be used at all
# It also prevents import loop collisions.
global __ServerImplementationDict
self.__data = ServerImplementationDict(loader)
self.__shortname = shortname
@property
def shortname(self):
# This is the only property provided from above
return self.__shortname
def __str__(self):
return str(self.__shortname)
# All other properties must come from canonical sources
# provided by the server loader
# CONSTANTS (STRINGS, BOOLEANS, INTS, ETC.)
@property
def name(self):
return self.__data['str_name']
@property
def internal_shortname(self):
return self.__data['str_shortname']
@property
def beta(self):
return self.__data['bool_tester']
# CLASSES
# 1- Credentials:
@property
def Auth(self): # I really don't know how to call this.
return self.__data['cls_auth']
@property
def auth_fields(self):
return self.__data['list_authkeys']
# 2- Server Elements:
@property
def Player(self):
return self.__data['cls_player']
@property
def Tournament(self):
return self.__data['cls_tournament'] | juanchodepisa/sbtk | SBTK_League_Helper/src/interfacing/servers.py | Python | mit | 1,946 |
import {
GraphQLInputObjectType,
GraphQLID,
GraphQLList,
GraphQLBoolean,
} from 'graphql';
import RecipientTypeEnum from './RecipientTypeEnum';
import MessageTypeEnum from './MessageTypeEnum';
import NoteInputType from './NoteInputType';
import TranslationInputType from './TranslationInputType';
import CommunicationInputType from './CommunicationInputType';
const MessageInputType = new GraphQLInputObjectType({
name: 'MessageInput',
fields: {
parentId: {
type: GraphQLID,
},
note: {
type: NoteInputType,
},
communication: {
type: CommunicationInputType,
},
subject: {
type: TranslationInputType,
},
enforceEmail: {
type: GraphQLBoolean,
},
isDraft: {
type: GraphQLBoolean,
},
recipients: {
type: new GraphQLList(GraphQLID),
},
recipientType: { type: RecipientTypeEnum },
messageType: { type: MessageTypeEnum },
},
});
export default MessageInputType;
| nambawan/g-old | src/data/types/MessageInputType.js | JavaScript | mit | 979 |
require "rubygems"
require 'active_support'
require "ruby-debug"
gem 'test-unit'
require "test/unit"
require 'active_support'
require 'active_support/test_case'
require 'shoulda'
require 'rr'
require File.dirname(__FILE__) + '/../lib/ubiquitously'
Ubiquitously.configure("test/config/secrets.yml")
Passport.configure("test/config/tokens.yml")
ActiveSupport::TestCase.class_eval do
def create_user(options)
@user = Ubiquitously::User.new(options.merge(:username => "viatropos"))
end
end
| lancejpollard/ubiquitously | test/test_helper.rb | Ruby | mit | 497 |
{% macro scenario_tabs(selected,num,path, id) %}
<div class="section-tabs js-tabs clearfix mb20">
<ul>
{% set navs = [
{url:"timeline-review",label:"Timeline"},
{url:"details-fme",label:"Details"},
{url:"evidence-portal",label:"Evidence"},
{url:"appointment",label:"Appointment"}
] %}
{% for item in navs %}
<li {% if item.url == selected %} class="active"{% endif %}><a href="/fha/scrutiny-scenarios/scenario7/{{ item.url }}/">{{ item.label }}</a></li>
{% endfor %}
</ul>
</div>
{% endmacro %}
| dwpdigitaltech/healthanddisability | app/views/fha/scrutiny-scenarios/scenario7/_macros_nav_scenario7.html | HTML | mit | 573 |
#include <boost/lexical_cast.hpp>
#include <disccord/models/user.hpp>
namespace disccord
{
namespace models
{
user::user()
: username(""), avatar(), email(), discriminator(0),
bot(false), mfa_enabled(), verified()
{ }
user::~user()
{ }
void user::decode(web::json::value json)
{
entity::decode(json);
username = json.at("username").as_string();
// HACK: use boost::lexical_cast here since it safely
// validates values
auto str_js = json.at("discriminator");
discriminator = boost::lexical_cast<uint16_t>(str_js.as_string());
#define get_field(var, conv) \
if (json.has_field(#var)) { \
auto field = json.at(#var); \
if (!field.is_null()) { \
var = decltype(var)(field.conv()); \
} else { \
var = decltype(var)::no_value(); \
} \
} else { \
var = decltype(var)(); \
}
get_field(avatar, as_string);
bot = json.at("bot").as_bool();
//get_field(bot, as_bool);
get_field(mfa_enabled, as_bool);
get_field(verified, as_bool);
get_field(email, as_string);
#undef get_field
}
void user::encode_to(std::unordered_map<std::string,
web::json::value> &info)
{
entity::encode_to(info);
info["username"] = web::json::value(get_username());
info["discriminator"] =
web::json::value(std::to_string(get_discriminator()));
if (get_avatar().is_specified())
info["avatar"] = get_avatar();
info["bot"] = web::json::value(get_bot());
if (get_mfa_enabled().is_specified())
info["mfa_enabled"] = get_mfa_enabled();
if (get_verified().is_specified())
info["verified"] = get_verified();
if (get_email().is_specified())
info["email"] = get_email();
}
#define define_get_method(field_name) \
decltype(user::field_name) user::get_##field_name() { \
return field_name; \
}
define_get_method(username)
define_get_method(discriminator)
define_get_method(avatar)
define_get_method(bot)
define_get_method(mfa_enabled)
define_get_method(verified)
define_get_method(email)
util::optional<std::string> user::get_avatar_url()
{
if (get_avatar().is_specified())
{
std::string url = "https://cdn.discordapp.com/avatars/" +
std::to_string(get_id()) + "/" +
get_avatar().get_value()+".png?size=1024";
return util::optional<std::string>(url);
}
else
return util::optional<std::string>::no_value();
}
#undef define_get_method
}
}
| FiniteReality/disccord | lib/models/user.cpp | C++ | mit | 3,213 |
package com.full360.voltdbscala
import org.voltdb.client.ClientResponse
/**
* Exception thrown when the status of a client response if not success
* @param message the detail message of this exception
*/
case class ClientResponseStatusException(message: String) extends Exception(message)
object ClientResponseStatusException {
def apply(clientResponse: ClientResponse): ClientResponseStatusException = {
val status = (clientResponse.getStatusString, clientResponse.getStatus)
new ClientResponseStatusException(s"""Stored procedure replied with status: "${status._1}". Code: ${status._2}""")
}
}
/**
* Exception thrown when an asynchronous procedure call is not queued
* @param message the detail message of this exception
*/
case class ProcedureNotQueuedException(message: String) extends Exception(message)
| full360/voltdbscala | src/main/scala/com/full360/voltdbscala/exceptions.scala | Scala | mit | 832 |
//
// UIView+WebCacheOperation.h
// SKWebImage
//
// Created by 侯森魁 on 2019/8/23.
// Copyright © 2019 侯森魁. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "SKWebImageCompat.h"
#import "SKWebImageManager.h"
NS_ASSUME_NONNULL_BEGIN
@interface UIView (WebCacheOperation)
/**
Set the image load operation (storage in a view based dictionary)
@param operation <#operation description#>
*/
- (void)sk_setImageloadOperation:(nullable id)operation forKey:(nullable NSString *)key;
/**
Cancel all operation for the current UiView and key
@param key <#key description#>
*/
- (void)sk_cancelImageLoadOperationWithKey:(nullable NSString *)key;
/**
Just remove the operation corresponding to the UIView and key without cancelling them
@param key <#key description#>
*/
- (void)sk_removeImageLoadOperationWithKey:(nullable NSString *)key;
@end
NS_ASSUME_NONNULL_END
| housenkui/SKStruct | SKProject01/SKWebImage/lib/Categories/UIView+WebCacheOperation.h | C | mit | 899 |
#CSCI 211 - Lab 1
##Introduction to Linux and the g++ Compiler
##Goals:
* Overview: Linux organization
* Introduce several basic Linux commands
* Provide an example of creating, compiling, and running a c++ program
* Set up all the directories for the course assignments
* Provide practice creating, compiling, and running c++ programs
##BUSY WORK DISCLAIMER:
Some teachers (especially in high school) waste your time with busywork.
The tasks I ask you to perform are to teach you information and skills that you must have to do well in computer science. If you learn what I'm showing you, it will save you lots of time throughout the semester.
If you take the attitude "I just want to get done with this busy work so I can leave" it is unlikely that you will be able to complete CSCI, CINS, or EECE. This lab, the other labs, and the assignments are not meant to keep you busy, they are meant to teach you want you need to know to be successful.
Paying attention, learning, and understanding how things work is difficult. If you do not want to pay attention, learn, and understand how things work, I strongly recommend you do not major in CSCI, CINS, or EECE.
##Lab Attendance/Grade
Part of your lab grade is based on attendance. I will take role after my lecture. If you finish the assignments AND turn them into [turnin](https://turnin.ecst.csuchico.edu/ "Tyson's Turnin"), then you may leave early. Speak to me if you need to leave early but have not finished the assignments. **Students who leave early without turning in that weeks assignments will NOT get credit for attending lab.**
##Getting your ecst computer account
(skip this if you already have an ecst account)
In order to log on to the computers in the 211 lab (OCNL 244), you must have an ecst (Engineering College) account.
This is different than the university account (often called a Wildcat account, or University Portal account).
If you have never had an ecst account you can create one by visiting the account creation page. It will take about 1 business day for your new account to become active.
If you already have an ecst account but your forgot your password, you must go to the system administrator's (Elbert Chan) office hours: OCNL 249 Monday - Friday 4:00 - 5:00. You will need your student ID.
If you don't have an account, you can log in with username & password as "student" However, you will not be able to save any of your work.
##Using the Linux Computers in OCNL 251
The computers in OCNL 251 are running the Linux operating system (the Ubuntu distribution with the xfce window manager). They are stand-alone computers except your home directory is on a shared file server in Butte Hall. This means all your files will be available no matter which machine you use (or if you log in remotely to jaguar.ecst.csuchico.edu from home using ssh or putty).
SOMETIMES the network file links (one for home directories, one for web directories) between the 251 lab computers disconnect. The only way to reset them is to reboot the computer. If you can't access your home directory or my directories, the links probably failed and you should reboot the computer.
##Lecture Notes:
###[Linux Tutorial (recommended for everyone)](http://ryanstutorials.net/linuxtutorial/)
###Linux Overview
* Kernel
* Shell (csh, tsh, ksh, bsh, bash)
* Windowing System (X-windows is the most common)
* Windows Manager (Xfce, KDE, Gnome, etc)
###Linux Command structure
Commands in the Linux environment all have textual names. Instead of opening a window that shows the content of a directory you type a command at a prompt in a window. For example, the command "ls" show the contents of the current directory. A program called the shell will print a prompt (usually a "$" but can be anything you want) to indicate that it is ready for you to type a command.
When you type a command the shell looks for a program with that name to execute.
<pre>
$ ls
</pre>
shell looks for an executable file named "ls" in the special collection of directories (called the path)
Why text better than clicking buttons? Consider the problem of editing a group of files. For example, I have a bunch of files with "112" in them and I need to change the "112" to "211" The following command changes 112 to 211 in all the .html files in the current directory:
<pre>
$ for file in *.html; do sed s/112/211/g < $file > tmp; mv tmp $file; done
</pre>
While it may take some time before you can write such complicated commands, once you learn how to use a text based command shell it is much faster than using a point-and-click interface.
####Know What You are Doing
Linux assumes that you really want to do what you say you want to do. In other words, if you use the remove command to delete a file, the file will be deleted. It won't be put into the trash, it will be deleted. Once a file is deleted, it is deleted forever (system backups are done every night, so if the file existed the previous night you can get a copy from the backups).
####Special Keys
* ^C kill the current process
* ^D End of input (end of file) character
When you want to tell a program you are done entering input, type ^D
* ^Z Stop the current process (the process will still exist, but it won't be running). Don't do this until you understand how to restart processes (commands: jobs, fg, bg).
####File Redirection
Programs usually write to the current window. For example, if your program has the following line: cout << "hello\n" hello will be written to the current window.
You can tell the bash shell to redirect standard output (i.e. cout) to a file
<pre>
$ hello_world > hello_world.myout
</pre>
Now when the program hello_world is run, text written to standard output will be place in the file hellow_world.myout
Programs usually read from the keyboard. For example, if your program has the following line: cin >> value; the number typed at the keyboard will be placed into the variable value
You can tell the shell to redirect standard input (i.e. cin) from a file
<pre>
$ add < test_1.in
</pre>
Now when the program add is run, text read from standard input (cin) will be read from the file: test_1.in
####Linux Pipes
One of the most powerful features of the bash shell is the ability to connect the output of one command to the input of another command. Consider these two commands:
<pre>
$ ls this will list all the files in the current directory
$ wc this will count all the characters, words, and lines in the input
</pre>
If we take the output of ls and connected it to the input of wc (we say "pipe the output of ls to the input of wc") we can find out how many files are in the current directory
<pre>
$ ls | wc
</pre>
The | is usually on the key above the Enter key.
Any number of commands can be pipped together.
####Common Linux commands
| Linux Command | Command Details | Examples |
| :------------- | :------------- | :-------- |
| cd | change directory<br> ~ is used to mean your home directory<br> .. is used to mean the parent of current directory |$ cd <br>change to your home directory <br>$ cd ~user <br>change to specified user's home directory (e.g. $ cd ~tyson) <br> $ cd .. <br>change to the parent of the current directory (the directory above the current directory) <br> $ cd 211 <br> if "211" is a sub-directory of the current directory, change to it|
|ls | list the files in the current directory | |
|pwd | show the current directory (called the path)| |
|mkdir | make a new directory|$ mkdir 211 <br> make a new directory in the current directory called "211" <br>$ mkdir ~/211 <br> make a new directory in your home directory called "211" |
|chmod | change the protection (access) of a file or directory if you change the protection of your home directory as follows, no one will be able to access any of your files | $ cd ~/ <br> change to your home directory <br>$ chmod 700 . <br> don't forget the dot (.) t the end of this command |
|rm | delete a file <br> rm -r allows you to delete a directory and everything in it, use it carefully | |
|cp | copy a file | |
| man | show the manual page for a command | $ man cp <br> the -k option searches for keywords in all man pages (useful if you forget the name of a command) <br> $ man -k copy <br> usually this produces too many matches and they scroll by too fast to read <br> $ man -k copy \| less <br> Note: the apopos command does the same thing as "man -k" <br> $ apopos copy \| less |
|which| tells you which executable is executed when you type a command |$ which cp |
####Linux editors:
For 211 we will not be using an integrated development environment (IDE). The reason we are not using an IDE is because I want you to develop a good understanding of the tasks performed by an IDE. Once you understand these tasks well you can switch to an IDE.
When writing programs without an IDE you use a stand alone editor to create your program (vs. using the editor built in to Visual C++). This means you can pick from hundreds of available editors. Here are some common choices (most are available on the computers in 251):
* SciTE: Menu based editor that is easy to use. Similar to notepad. Can download on your home machine so you can use the same editor at home as you use in lab. Cannot use over text-based connections (like putty) (actually there is a way to use it but it takes work to set up).
* nano: Simple text based editor (no mouse), all the commands are always on the screen (on some platforms a similar editor called pico is available and nano is not). You can use nano via a text-based connection (like putty).
* gvim: Graphical version of vim (see below). A little harder to learn how to use.
* vim : Powerful and very popular version of the popular vi editor. Works on most Linux and Microsoft platforms. It is hard to learn how to use but very fast once you learn how to use. Vim Homepage
* emacs: Powerful and very popular editor. It is hard to learn how to use but provides powerful tools once you learn how to use it. Works on most Linux and Microsoft platforms GNU's emacs page
* sublime: Graphical paid editor favorite of many upper class students and is a great editor.
* Atom: New open source graphical editor from GitHub, offers plugins including ones that allow you to connect to SFTP connections and remotely edit code on lab machines from home.
All these editors works from the command line:
<pre>
$ SciTE hello.cpp &
</pre>
**NOTE: SciTE in OCNL 251 is broken and cannot create a new file. You have to create the file BEFORE you edit it:**
<pre>
$ touch hello.cpp
// the touch command will create a new file if the given file does not exist
$ SciTE hello.cpp &
</pre>
Note: The & at the end of this command tells the shell to create a new process to run the given command. That means that while the editor window is running you can continue to use the command prompt.
All of these are available on Linux and MacOS. Vim and Emacs are hard to learn, so if you don't already know one, I suggest you start using SciTE. In a couple weeks I will give lab on vim.
If you plan to use Putty to do your assignments at home (not recommended), then vim or nano is a better choice (it requires some extra setup to use gvim or SciTE over putty).
Whatever editor you end up using, become an expert.
##Turning in Lab Assignments
Some of the lab exercises must be turned in using [turnin.ecst.csuchico.edu](https://turnin.ecst.csuchico.edu/ "Tyson's Turnin") (see instructions for [turning in file](https://github.com/CSUChico-CSCI211/CSCI211-Course-Materials/blob/master/Assignments/Turnin.md "How to Turnin")) for you to get credit. For this lab you must turn in files for exercises 4 and 5. At the end of each exercise I will indicate what files must be turned in.
My goal is to provide assignments that you can complete during lab. However, if you cannot finish the assignments during lab, you have until midnight on the Friday Saturday following lab to turn them in (most semesters the deadline is Friday, but since there is a Friday afternoon lab in Spring 2015, the deadline is Saturday; you should try to turn them in Friday, it is easy to forget about assignments due on Saturday).
Some of the lab exercises do not have to be turned in. Usually these assignments provide the information you need for subsequent lab assignments and programming assignments. I strongly suggest you complete all lab assignments.
##Exercise 1: Setting up your 211 environment
The following steps set up the directories for the entire semester. Make sure you follow the instructions carefully.
These instructions will work on the lab computers AND on your Linux/OSX laptop/desktop. If you have your laptop today and plan to bring it to every lab, you can follow these instructions only on your laptop. If you do not plan on bringing a laptop to lab, log in to a lab computer and then follow these instructions.
The following will create two directories "211" and "bin" in the directory in which you execute these commands. Life will be much easier if you do this in your home directory (either on the Department's computer or on your own laptop). After the semester you can move the directory to a different location. You can also create a symbolic link (shortcut) from another directory.
When I provide a "$" with some text after it, type that text (a command) into the shell. When typing commands DO NOT type the // or the text after the //
<pre>
$ cd // go to your home directory
$ chmod 700 . // change the protection so no one can steal your files (you can skip this on your laptop)
</pre>
There are three methods to download the needed file. If your computer has the utility wget, use the first. Otherwise use the second.
* Method 1: your computer has the wget command (type "which wget" at the $, if a filename is printed then wget is installed)
<pre>
$ wget www.ecst.csuchico.edu/~tyson/211/downloads/211.tar // copy 211.tar from my web page to current directory
</pre>
* Method 2: your computer does not have wget
<pre>
$ sftp [email protected] // USERNAME must be your ecst username
</pre>
If you get an error message, type this command ($ rm .ssh/known_hosts) and retype the above sftp command
If you don't get an error message, you should be prompted for your ecst password
Once you log in you will see the sftp prompt "sftp> "
For the following, type everything after the "sftp> "
<pre>
Connected to jaguar.ecst.csuchico.edu.
sftp> cd /user/faculty/tyson/211/downloads // change directory on jaguar to the 211 downloads directory
sftp> get 211.tar // copy the file "211.tar" from jaguar to your computer
...
sftp> quit // exit sftp
</pre>
* Method 3: use a web browser
Save the file 211.tar into your home directory (simply clicking on 211.tar will download it to your downloads directory, move it to your home directory).
While this might seem like the easiest method, knowing both wget and sftp is very worthwhile.
The "tar" file you just downloaded is like a .zip file. It contains all the directories and files you need this semester.
When expanded it will create a directory called "211" If you already have a directory or file named "211" you must rename it
<pre>
$ mv 211 211.old // only do this if you already have a 211 directory or file
</pre>
Unpack 211.tar (this creates the directory 211 with a subdirectory for each assignment)
<pre>
$ tar -xf 211.tar // extract all the directories and files
$ ls // you should see the directories "211" and "bin"
$ ls 211 // you should see a bunch of lab and project directories
$ cd 211/lab01_hello // change to the directory for the following exercise
</pre>
If you are working on a computer in the lab, you can repeat this process on your home computer/laptop. You can copy files to/from jaguar and your home computer/laptop using sftp.
##Exercise 2: Creating, compiling, and running a C++ program
For this lab you will be writing three programs. It is a very good idea to put each program in its own directory. If you get in the habit of putting each program in its own directory you will save time later in the semester. I regularly see students waste time because they attempt to put multiple programs in one directory. The above step created three directories for lab 1: ~/211/lab01_hello ~/211/lab01_print ~/211/lab01_add.
In your directory for lab 1 hello (~211/lab01_hello if you follow my instructions above), create the file hello.cpp (use any editor, I recommend that you use scite if you don't know vim (use vim if you know vim)). Start the editor with "hello.cpp" as the filename:
<pre>
$ touch hello.cpp // only in OCNL 251 because SciTE is broken
$ SciTE hello.cpp &
</pre>
the & starts the process in the background and allows you to use the editor AND the command window at the same time
-or-
<pre>
$ vim hello.cpp
</pre>
Now edit the file so it contains the following text. Save the file and exit the editor.
<pre>
#include <iostream>
using namespace std;
int
main()
{
cout << "hello world" << endl;
return 0;
}
</pre>
Compile this file using the command:
<pre>
$ g++ hello.cpp
</pre>
if you got an error, use the editor to fix the error
This should have created the file a.out, use "$ ls -l" to find out if a.out is in your directory. Notice that a.out automatically has execute protection ("x"). When a file has execute permission you can execute it.
<pre>
$ ls -l a.out
</pre>
Run your hello program. You can execute the program by typing a.out at the Linux prompt.
<pre>
$ a.out
</pre>
If a.out doesn't work, try ./a.out. If "./a.out" worked and "a.out" did not work, read about how to fix your path.
You do not have to turn in this exercise. The following two exercises must be turned in.
##Exercise 3: Write a program that reads two numbers, adds them together, and prints the result
Change the directory to your lab01_add directory
<pre>
$ cd ../lab01_add
</pre>
If that did not work, try using the "full directory path" or "full path"
<pre>
$ cd ~/211/lab01_add
</pre>
When your program is run, it should work like this (the "a.out" "40" and "2" are typed by the user; the "40 + 2 = 42" is printed by the program):
<pre>
$ a.out
40
2
40 + 2 = 42
$
</pre>
For this exercise you will need to read in an integer. You can read an integer in C++ like this:
<pre>
cin >> value1;
</pre>
Where "value1" has been declared as an integer before this line (C++ integers are declared just like in Java).
Create a new file called add.cpp using an editor. Write the add program so it reads and adds the two numbers.
Compile and run your program to make sure it works correctly. Your output must EXACTLY match my output (<number><space><+><space><number><space><=><space><number><newline>)
Some sample input and output are available in your lab01_add/tests directory.
<pre>
$ ls tests
t01.in t01.out t02.in t02.out t03.in t03.out
$
</pre>
In this directory you will find files like t0.in1 and t01.out. t01.in is the input for your program and t01.out is the expected output. I will use all the tests in this directory to grade your program. If you pass these tests you will get full credit (these are the same tests used when by turnin.ecst.csuchico.edu).
An easy way to see the content of a small file is to use the Linux cat command:
<pre>
$ cat tests/t01.in
40 2
$ cat tests/t01.out
40 + 2 = 42
$
</pre>
See [Introduction to Testing](https://github.com/CSUChico-CSCI211/CSCI211-Course-Materials/blob/master/Assignments/Testing.md "Testing") for full description of how to test your assignments. If you understand the described mechanism now, it will make your semester much easier, and will improve your grade. One of the most important aspects of this lab is for you to understand the testing mechanism.
Once your program is working, turn add.cpp in on [turnin.ecst.csuchico.edu](https://turnin.ecst.csuchico.edu/ "Tyson's Turnin"). See instructions for [turning in files.](https://github.com/CSUChico-CSCI211/CSCI211-Course-Materials/blob/master/Assignments/Turnin.md "How to Turnin")
You must pass all the posted tests to get credit for a lab assignment.
Lab exercises are due midnight the Saturday night following lab.
##Exercise 4: Write a program that reads a number and prints "hello" that number of times:
<pre>
$ a.out
5
0 hello
1 hello
2 hello
3 hello
4 hello
$
</pre>
All the characters shown above were printed by the program, except the 5<enter> which was typed by the user.
Change directory to the lab01_print directory. Create a new file called print.cpp.
Use a for loop to implement this program.
When your program is working, test it with the posted tests (see the testing and turn in instructions for exercise 3; the only difference is that the tests are in the directory lab01_print/tests).
Make sure your program passes all the tests.
Turn in print.cpp to [turnin.ecst.csuchico.edu](https://turnin.ecst.csuchico.edu/ "Tyson's Turnin").
##Exercise 5: Make sure you understand the [testing mechanism](https://github.com/CSUChico-CSCI211/CSCI211-Course-Materials/blob/master/Assignments/Testing.md "Testing")
The main point of these assignments is to introduce you to the testing mechanism.
Students who don't understand how < and > are used to test assignments struggle throughout the semester.
##Exercise Deadline
All labs are due at 11:59pm the Saturday following lab. For this lab you must turn in add.cpp and print.cpp.
If you are not able to complete all the exercises, turn in your partial work for partial credit.
| CSUChico-CSCI211/CSCI211-Course-Materials | Labs/Lab1.md | Markdown | mit | 21,981 |
//
//
/////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
//
//////////////////////////////////////////////////////////////////////////////
//
//
// truetypetext.h - General-purpose TrueType functions
//
// DESCRIPTION:
//
// This header file contains declarations of general-purpose truetype text
// functions provided with the AcUtil library and DLL.
//
#ifndef _TRUETYPETEXT_H_
#define _TRUETYPETEXT_H_
#define UC_DEGREE_SYMBOL 0x00B0
#define UC_PLUSMINUS_SYMBOL 0x00B1
#define UC_PHI_SYMBOL 0x00D8 // The Character 'phi' (substitute for diameter)
#define UC_DIAMETER_SYMBOL 0x2205 // Most fonts do not have this.
typedef void (*LineSegmentCallback) (const AcGePoint3d &, const AcGePoint3d &, const void *);
struct TextParams {
double height; // Text Height
double width_scale; // Width Scale Factor
double oblique_angle; // Obliquing/Italics Angle
double rotation_angle; // Rotation Angle
double spacing; // Inter Character Spacing Percent
short flags; // Text Generation Flags
};
class Scores {
private:
int m_overline;
int m_underline;
int m_strikethrough;
AcGePoint3d m_position;
AcGePoint3d m_over_point[2];
AcGePoint3d m_under_point[2];
AcGePoint3d m_strikethrough_point[2];
AcGePoint3d m_bbox[4];
TextParams const * m_pTextParams;
LineSegmentCallback m_pLineSegmentCB;
void * m_pAction;
AcGiContext * m_pContext;
#define ON 1
#define OFF 0
public:
Scores(AcGiContext * pContext, TextParams const * pTextParams, LineSegmentCallback pLineSegment, void * pAction);
~Scores () {};
void over_score (const wchar_t* text, int length);
void under_score (const wchar_t * text, int length);
void strikethrough_score(const wchar_t * text, int length);
void close_scores (const wchar_t * text, int length);
void draw_vector (AcGePoint3d const & p1, AcGePoint3d const & p2);
};
void process_uc_string (
WCHAR * uc_string,
int & uc_length,
TextParams const * tp,
BOOL draw_scores,
LineSegmentCallback line_segment = NULL,
void * action = NULL);
void process_underoverline(
const WCHAR * uc_string,
int uc_length,
TextParams const * tp,
LineSegmentCallback line_segment,
void * action = NULL);
int convert_to_unicode(
const char * pMultiByteString,
int nMultiByteLength,
WCHAR * pUnicodeString,
int & nUnicodeLength,
bool bInformUser);
int convert_to_unicode(
UINT iCharset,
const char * pMultiByteString,
int nMultiByteLength,
WCHAR * pUnicodeString,
int & nUnicodeLength,
bool bInformUser);
class TrueTypeUnicodeBuffer
{
public:
TrueTypeUnicodeBuffer(LPCTSTR text, int length, bool raw, int charset) :
m_bDynamicBuffer(false),
m_bValid(true)
{
if (length < -1) {
m_iLen = -length - 1;
m_pBuffer = (LPWSTR)text;
return;
}
if (length != -1)
m_iLen = length;
else {
const size_t nLen = ::wcslen(text);
#ifdef ASSERT
#define TrueTypeText_Assert ASSERT
#elif defined(assert)
#define TrueTypeText_Assert assert
#elif defined(_ASSERTE)
#define TrueTypeText_Assert _ASSERTE
#else
#define TrueTypeText_Assert(x)
#endif
TrueTypeText_Assert(nLen < 0x7FFFFFFE); // 2G-1 sanity check
TrueTypeText_Assert(nLen == (int)nLen); // 64-bit portability
m_iLen = (int)nLen;
}
if (!raw) {
// only need temporary string if converting %% sequences
size_t nSize;
if (m_iLen + 1 > m_kBufferLen) {
m_bDynamicBuffer = true;
m_pBuffer = new WCHAR [m_iLen + 1];
nSize = m_iLen + 1;
if (!m_pBuffer) {
m_bValid = false;
return;
}
} else {
m_pBuffer = m_sBuffer;
nSize = m_kBufferLen;
}
_tcsncpy_s(m_pBuffer, nSize, text, m_iLen);
m_pBuffer[m_iLen] = 0;
} else {
// It is okay to cast away constness here -- we only call process_underoverline
// which takes a const pointer
m_pBuffer = const_cast<wchar_t *>(text);
}
}
~TrueTypeUnicodeBuffer()
{
if (m_bDynamicBuffer)
delete [] m_pBuffer;
}
LPWSTR buf() const { return m_pBuffer; }
int len() const { return m_iLen; }
bool valid() const { return m_bValid; }
private:
static const int m_kBufferLen = 256;
bool m_bValid;
LPWSTR m_pBuffer;
int m_iLen;
bool m_bDynamicBuffer;
WCHAR m_sBuffer[m_kBufferLen];
};
#endif // _TRUETYPETEXT_H_
| kevinzhwl/ObjectARXCore | 2015/inc/truetypetext.h | C | mit | 5,684 |
Subsets and Splits