text
stringlengths 2
99.9k
| meta
dict |
---|---|
#ifndef MINIOS_XENBUS_H__
#define MINIOS_XENBUS_H__
#include <xen/io/xenbus.h>
#include <mini-os/waittypes.h>
#include <mini-os/queue.h>
#include <mini-os/spinlock.h>
typedef unsigned long xenbus_transaction_t;
#define XBT_NIL ((xenbus_transaction_t)0)
/* Initialize the XenBus system. */
void init_xenbus(void);
/* Read the value associated with a path. Returns a malloc'd error
string on failure and sets *value to NULL. On success, *value is
set to a malloc'd copy of the value. */
char *xenbus_read(xenbus_transaction_t xbt, const char *path, char **value);
/* All accesses to an active xenbus_event_queue must occur with this
* lock held. The public functions here will do that for you, but
* your own accesses to the queue (including the contained waitq)
* must be protected by the lock. */
extern spinlock_t xenbus_req_lock;
/* Queue for events (watches or async request replies - see below) */
struct xenbus_event {
union {
struct {
/* must be first, both for the bare minios xs.c, and for
* xenbus_wait_for_watch's handling */
char *path;
char *token;
};
struct xsd_sockmsg *reply;
};
struct xenbus_watch *watch;
MINIOS_STAILQ_ENTRY(xenbus_event) entry;
};
struct xenbus_event_queue {
MINIOS_STAILQ_HEAD(, xenbus_event) events;
void (*wakeup)(struct xenbus_event_queue*); /* can be safely ignored */
struct wait_queue_head waitq;
};
void xenbus_event_queue_init(struct xenbus_event_queue *queue);
char *xenbus_watch_path_token(xenbus_transaction_t xbt, const char *path, const char *token, struct xenbus_event_queue *events);
char *xenbus_unwatch_path_token(xenbus_transaction_t xbt, const char *path, const char *token);
void xenbus_wait_for_watch(struct xenbus_event_queue *queue);
char **xenbus_wait_for_watch_return(struct xenbus_event_queue *queue);
char* xenbus_wait_for_value(const char *path, const char *value, struct xenbus_event_queue *queue);
char *xenbus_wait_for_state_change(const char* path, XenbusState *state, struct xenbus_event_queue *queue);
char *xenbus_switch_state(xenbus_transaction_t xbt, const char* path, XenbusState state);
/* When no token is provided, use a global queue. */
#define XENBUS_WATCH_PATH_TOKEN "xenbus_watch_path"
extern struct xenbus_event_queue xenbus_default_watch_queue;
#define xenbus_watch_path(xbt, path) xenbus_watch_path_token(xbt, path, XENBUS_WATCH_PATH_TOKEN, NULL)
#define xenbus_unwatch_path(xbt, path) xenbus_unwatch_path_token(xbt, path, XENBUS_WATCH_PATH_TOKEN)
/* Associates a value with a path. Returns a malloc'd error string on
failure. */
char *xenbus_write(xenbus_transaction_t xbt, const char *path, const char *value);
struct write_req {
const void *data;
unsigned len;
};
/* Send a message to xenbus, in the same fashion as xb_write, and
block waiting for a reply. The reply is malloced and should be
freed by the caller. */
struct xsd_sockmsg *
xenbus_msg_reply(int type,
xenbus_transaction_t trans,
struct write_req *io,
int nr_reqs);
/* Removes the value associated with a path. Returns a malloc'd error
string on failure. */
char *xenbus_rm(xenbus_transaction_t xbt, const char *path);
/* List the contents of a directory. Returns a malloc'd error string
on failure and sets *contents to NULL. On success, *contents is
set to a malloc'd array of pointers to malloc'd strings. The array
is NULL terminated. May block. */
char *xenbus_ls(xenbus_transaction_t xbt, const char *prefix, char ***contents);
/* Reads permissions associated with a path. Returns a malloc'd error
string on failure and sets *value to NULL. On success, *value is
set to a malloc'd copy of the value. */
char *xenbus_get_perms(xenbus_transaction_t xbt, const char *path, char **value);
/* Sets the permissions associated with a path. Returns a malloc'd
error string on failure. */
char *xenbus_set_perms(xenbus_transaction_t xbt, const char *path, domid_t dom, char perm);
/* Start a xenbus transaction. Returns the transaction in xbt on
success or a malloc'd error string otherwise. */
char *xenbus_transaction_start(xenbus_transaction_t *xbt);
/* End a xenbus transaction. Returns a malloc'd error string if it
fails. abort says whether the transaction should be aborted.
Returns 1 in *retry iff the transaction should be retried. */
char *xenbus_transaction_end(xenbus_transaction_t, int abort,
int *retry);
/* Read path and parse it as an integer. Returns -1 on error. */
int xenbus_read_integer(const char *path);
/* Contraction of snprintf and xenbus_write(path/node). */
char* xenbus_printf(xenbus_transaction_t xbt,
const char* node, const char* path,
const char* fmt, ...)
__attribute__((__format__(printf, 4, 5)));
/* Utility function to figure out our domain id */
domid_t xenbus_get_self_id(void);
/*
* ----- asynchronous low-level interface -----
*/
/*
* Use of queue->wakeup:
*
* If queue->wakeup is set, it will be called instead of
* wake_up(&queue->waitq);
*
* queue->wakeup is initialised (to a function which just calls
* wake_up) by xenbus_event_queue_init. The user who wants something
* different should set ->wakeup after the init, but before the queue
* is used for xenbus_id_allocate or xenbus_watch_prepare.
*
* queue->wakeup() is called with the req_lock held.
*/
/* Allocate an identifier for a xenbus request. Blocks if none are
* available. Cannot fail. On return, we may use the returned value
* as the id in a xenbus request.
*
* for_queue must already be allocated, but may be uninitialised.
*
* for_queue->watch is not touched by the xenbus machinery for
* handling requests/replies but should probably be initialised by the
* caller (probably to NULL) because this will help the caller
* distinguish the reply from any watch events which might end up in
* the same queue.
*
* reply_queue must exist and have been initialised.
*
* When the response arrives, the reply message will stored in
* for_queue->reply and for_queue will be queued on reply_queue. The
* id must be then explicitly released (or, used again, if desired).
* After ->reply is done with the caller must pass it to free().
* (Do not use the id for more than one request at a time.) */
int xenbus_id_allocate(struct xenbus_event_queue *reply_queue,
struct xenbus_event *for_queue);
void xenbus_id_release(int id);
/* Allocating a token for a watch.
*
* To use this:
* - Include struct xenbus_watch in your own struct.
* - Set events; then call prepare. This will set token.
* You may then use token in a WATCH request.
* - You must UNWATCH before you call release.
* Do not modify token yourself.
* entry is private for the xenbus driver.
*
* When the watch fires, a new struct xenbus_event will be allocated
* and queued on events. The field xenbus_event->watch will have been
* set to watch by the xenbus machinery, and xenbus_event->path will
* be the watch path. After the caller is done with the event,
* its pointer should simply be passed to free(). */
struct xenbus_watch {
char *token;
struct xenbus_event_queue *events;
MINIOS_LIST_ENTRY(xenbus_watch) entry;
};
void xenbus_watch_init(struct xenbus_watch *watch); /* makes release a noop */
void xenbus_watch_prepare(struct xenbus_watch *watch); /* need not be init'd */
void xenbus_watch_release(struct xenbus_watch *watch); /* idempotent */
/* Send data to xenbus. This can block. All of the requests are seen
* by xenbus as if sent atomically. The header is added
* automatically, using type %type, req_id %req_id, and trans_id
* %trans_id. */
void xenbus_xb_write(int type, int req_id, xenbus_transaction_t trans_id,
const struct write_req *req, int nr_reqs);
void xenbus_free(void*);
/* If the caller is in a scope which uses a different malloc arena,
* it must use this rather than free() when freeing data received
* from xenbus. */
/* Reset the XenBus system. */
void fini_xenbus(void);
#endif /* MINIOS_XENBUS_H__ */
| {
"pile_set_name": "Github"
} |
import "js/phantomjs/test-case.jsx";
import "js/phantomjs.jsx";
class _Test extends PhantomTestCase {
function testPhantom() : void {
this.expect(phantom.version.major, 'phantom.version.major').toBeGE(1);
this.expect(phantom.version.minor, 'phantom.version.minor').toBeGE(0);
this.expect(phantom.version.patch, 'phantom.version.patch').toBeGE(0);
}
function testSystem() : void {
this.expect(system.platform, 'system.platform').notToBe(null);
this.expect(system.env instanceof Map.<string>).toBe(true);
this.expect(system.args instanceof Array.<string>).toBe(true);
}
function testFS() : void {
this.expect(fs.workingDirectory, 'fs.workingDirectory').notToBe(null);
}
function testWebPage() : void {
var page = webpage.create();
this.expect(page, 'webpage.create()').notToBe(null);
}
function testWebServer() : void {
var server = webserver.create();
this.expect(server, 'webserver.create()').notToBe(null);
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
| {
"pile_set_name": "Github"
} |
import tensorflow as tf
import math
class Vis_lstm_model:
def init_weight(self, dim_in, dim_out, name=None, stddev=1.0):
return tf.Variable(tf.truncated_normal([dim_in, dim_out], stddev=stddev/math.sqrt(float(dim_in))), name=name)
def init_bias(self, dim_out, name=None):
return tf.Variable(tf.zeros([dim_out]), name=name)
def __init__(self, options):
with tf.device('/cpu:0'):
self.options = options
# +1 for zero padding
self.Wemb = tf.Variable(tf.random_uniform([options['q_vocab_size'] + 1, options['embedding_size']], -1.0, 1.0), name = 'Wemb')
self.Wimg = self.init_weight(options['fc7_feature_length'], options['embedding_size'], name = 'Wimg')
self.bimg = self.init_bias(options['embedding_size'], name = 'bimg')
# TODO: Assumed embedding size and rnn-size to be same
self.lstm_W = []
self.lstm_U = []
self.lstm_b = []
for i in range(options['num_lstm_layers']):
W = self.init_weight(options['rnn_size'], 4 * options['rnn_size'], name = ('rnnw_' + str(i)))
U = self.init_weight(options['rnn_size'], 4 * options['rnn_size'], name = ('rnnu_' + str(i)))
b = self.init_bias(4 * options['rnn_size'], name = ('rnnb_' + str(i)))
self.lstm_W.append(W)
self.lstm_U.append(U)
self.lstm_b.append(b)
self.ans_sm_W = self.init_weight(options['rnn_size'], options['ans_vocab_size'], name = 'ans_sm_W')
self.ans_sm_b = self.init_bias(options['ans_vocab_size'], name = 'ans_sm_b')
def forward_pass_lstm(self, word_embeddings):
x = word_embeddings
output = None
for l in range(self.options['num_lstm_layers']):
h = [None for i in range(self.options['lstm_steps'])]
c = [None for i in range(self.options['lstm_steps'])]
layer_output = []
for lstm_step in range(self.options['lstm_steps']):
if lstm_step == 0:
lstm_preactive = tf.matmul(x[lstm_step], self.lstm_W[l]) + self.lstm_b[l]
else:
lstm_preactive = tf.matmul(h[lstm_step-1], self.lstm_U[l]) + tf.matmul(x[lstm_step], self.lstm_W[l]) + self.lstm_b[l]
i, f, o, new_c = tf.split(lstm_preactive, num_or_size_splits = 4, axis = 1)
i = tf.nn.sigmoid(i)
f = tf.nn.sigmoid(f)
o = tf.nn.sigmoid(o)
new_c = tf.nn.tanh(new_c)
if lstm_step == 0:
c[lstm_step] = i * new_c
else:
c[lstm_step] = f * c[lstm_step-1] + i * new_c
# BUG IN THE LSTM --> Haven't corrected this yet, Will have to retrain the model.
h[lstm_step] = o * tf.nn.tanh(c[lstm_step])
# h[lstm_step] = o * tf.nn.tanh(new_c)
layer_output.append(h[lstm_step])
x = layer_output
output = layer_output
return output
def build_model(self):
fc7_features = tf.placeholder('float32',[ None, self.options['fc7_feature_length'] ], name = 'fc7')
sentence = tf.placeholder('int32',[None, self.options['lstm_steps'] - 1], name = "sentence")
answer = tf.placeholder('float32', [None, self.options['ans_vocab_size']], name = "answer")
word_embeddings = []
for i in range(self.options['lstm_steps']-1):
word_emb = tf.nn.embedding_lookup(self.Wemb, sentence[:,i])
word_emb = tf.nn.dropout(word_emb, self.options['word_emb_dropout'], name = "word_emb" + str(i))
word_embeddings.append(word_emb)
image_embedding = tf.matmul(fc7_features, self.Wimg) + self.bimg
image_embedding = tf.nn.tanh(image_embedding)
image_embedding = tf.nn.dropout(image_embedding, self.options['image_dropout'], name = "vis_features")
# Image as the last word in the lstm
word_embeddings.append(image_embedding)
lstm_output = self.forward_pass_lstm(word_embeddings)
lstm_answer = lstm_output[-1]
logits = tf.matmul(lstm_answer, self.ans_sm_W) + self.ans_sm_b
# ce = tf.nn.softmax_cross_entropy_with_logits(logits, answer, name = 'ce')
ce = tf.nn.softmax_cross_entropy_with_logits(labels=answer, logits= logits, name = 'ce')
answer_probab = tf.nn.softmax(logits, name='answer_probab')
predictions = tf.argmax(answer_probab,1)
correct_predictions = tf.equal(tf.argmax(answer_probab,1), tf.argmax(answer,1))
accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
loss = tf.reduce_sum(ce, name = 'loss')
input_tensors = {
'fc7' : fc7_features,
'sentence' : sentence,
'answer' : answer
}
return input_tensors, loss, accuracy, predictions
def build_generator(self):
fc7_features = tf.placeholder('float32',[ None, self.options['fc7_feature_length'] ], name = 'fc7')
sentence = tf.placeholder('int32',[None, self.options['lstm_steps'] - 1], name = "sentence")
word_embeddings = []
for i in range(self.options['lstm_steps']-1):
word_emb = tf.nn.embedding_lookup(self.Wemb, sentence[:,i])
word_embeddings.append(word_emb)
image_embedding = tf.matmul(fc7_features, self.Wimg) + self.bimg
image_embedding = tf.nn.tanh(image_embedding)
word_embeddings.append(image_embedding)
lstm_output = self.forward_pass_lstm(word_embeddings)
lstm_answer = lstm_output[-1]
logits = tf.matmul(lstm_answer, self.ans_sm_W) + self.ans_sm_b
answer_probab = tf.nn.softmax(logits, name='answer_probab')
predictions = tf.argmax(answer_probab,1)
input_tensors = {
'fc7' : fc7_features,
'sentence' : sentence
}
return input_tensors, predictions, answer_probab
| {
"pile_set_name": "Github"
} |
---
title: Help & Questions
type: index
weight: 5
---
Join the chat room on [Gitter](https://gitter.im/Laradock/laradock) and get help and support from the community.
You can as well can open an [issue](https://github.com/laradock/laradock/issues) on Github (will be labeled as Question) and discuss it with people on [Gitter](https://gitter.im/Laradock/laradock).
| {
"pile_set_name": "Github"
} |
{
"timeStamp": 1566347101850,
"date": "2019-08-21",
"name": "Ezhikkara Grama Panchayat, Ernakulam District",
"district": "Ernakulam",
"block": "Paravur",
"area": "15.27km",
"localbody_code": "G070103",
"no_of_wards": 14,
"population": 17201,
"male": 8447,
"female": 8754,
"population_density": 1126,
"sex_ratio": 1036,
"literacy_rate": 92.34,
"literacy_rate_male": 96.41,
"literacy_rate_female": 88.47,
"president": "PACHANDRIKA",
"wards": [
{
"ward_number": "1",
"name": "PERUMPADANNA",
"person": {
"id": "2015062600101",
"name": "USHA RADHAKRISHNAN"
}
},
{
"ward_number": "2",
"name": "PARAYATTUPARAMBU",
"person": {
"id": "2015062600201",
"name": "V.S SIVARAMAN"
}
},
{
"ward_number": "3",
"name": "VADAKKUPURAM",
"person": {
"id": "2015062600301",
"name": "SHEEBA SAILESH"
}
},
{
"ward_number": "4",
"name": "KALIKULANGARA",
"person": {
"id": "2015062600401",
"name": "K.K. NARAYANAN"
}
},
{
"ward_number": "5",
"name": "NATHIATTUKUNNAM",
"person": {
"id": "2015062600501",
"name": "V.K SAJEEVAN"
}
},
{
"ward_number": "6",
"name": "KUNDEKKAVU",
"person": {
"id": "2015062600601",
"name": "P A CHANDRIKA"
}
},
{
"ward_number": "7",
"name": "AYAPPILLY",
"person": {
"id": "2015062600701",
"name": "GEETHA PRATHAPAN"
}
},
{
"ward_number": "8",
"name": "PALLIYAKKAL",
"person": {
"id": "2015062600801",
"name": "DELEELA PETER"
}
},
{
"ward_number": "9",
"name": "CHATHANAD",
"person": {
"id": "2015062600901",
"name": "K.S. BHUVANACHANDRAN"
}
},
{
"ward_number": "10",
"name": "PULINGANAD",
"person": {
"id": "2015062601001",
"name": "SUNILRAJ E R"
}
},
{
"ward_number": "11",
"name": "KADAKKARA",
"person": {
"id": "2015062601101",
"name": "K MOHANAN"
}
},
{
"ward_number": "12",
"name": "EZHIKKARA",
"person": {
"id": "2015062601201",
"name": "SMERA A R"
}
},
{
"ward_number": "13",
"name": "KEDAMANGALAM",
"person": {
"id": "2015062601301",
"name": "RATHEESH M S"
}
},
{
"ward_number": "14",
"name": "CHEETHUKKALAM-CHAKKATHARA",
"person": {
"id": "2015062601401",
"name": "SHEELA MURALI"
}
}
]
}
| {
"pile_set_name": "Github"
} |
package com.macro.mall.dao;
import com.macro.mall.dto.PmsProductCategoryWithChildrenItem;
import java.util.List;
/**
* 商品分类自定义Dao
* Created by macro on 2018/5/25.
*/
public interface PmsProductCategoryDao {
/**
* 获取商品分类及其子分类
*/
List<PmsProductCategoryWithChildrenItem> listWithChildren();
}
| {
"pile_set_name": "Github"
} |
module.exports = [
{
description: 'transpiles a class declaration',
options: { namedFunctionExpressions: false },
input: `
class Foo {
constructor ( answer ) {
this.answer = answer;
}
}`,
output: `
var Foo = function ( answer ) {
this.answer = answer;
};`
},
{
description: 'transpiles a class declaration with a non-constructor method',
options: { namedFunctionExpressions: false },
input: `
class Foo {
constructor ( answer ) {
this.answer = answer;
}
bar ( str ) {
return str + 'bar';
}
}`,
output: `
var Foo = function ( answer ) {
this.answer = answer;
};
Foo.prototype.bar = function ( str ) {
return str + 'bar';
};`
},
{
description:
'transpiles a class declaration without a constructor function',
options: { namedFunctionExpressions: false },
input: `
class Foo {
bar ( str ) {
return str + 'bar';
}
}`,
output: `
var Foo = function () {};
Foo.prototype.bar = function ( str ) {
return str + 'bar';
};`
},
{
description: 'no unnecessary deshadowing of method names',
options: { namedFunctionExpressions: false },
input: `
var bar = 'x';
class Foo {
bar ( str ) {
return str + 'bar';
}
}`,
output: `
var bar = 'x';
var Foo = function () {};
Foo.prototype.bar = function ( str ) {
return str + 'bar';
};`
},
{
description: 'transpiles a class declaration with a static method',
options: { namedFunctionExpressions: false },
input: `
class Foo {
bar ( str ) {
return str + 'bar';
}
static baz ( str ) {
return str + 'baz';
}
}`,
output: `
var Foo = function () {};
Foo.prototype.bar = function ( str ) {
return str + 'bar';
};
Foo.baz = function ( str ) {
return str + 'baz';
};`
},
{
description: 'transpiles a subclass',
options: { namedFunctionExpressions: false },
input: `
class Foo extends Bar {
baz ( str ) {
return str + 'baz';
}
}`,
output: `
var Foo = /*@__PURE__*/(function (Bar) {
function Foo () {
Bar.apply(this, arguments);
}
if ( Bar ) Foo.__proto__ = Bar;
Foo.prototype = Object.create( Bar && Bar.prototype );
Foo.prototype.constructor = Foo;
Foo.prototype.baz = function ( str ) {
return str + 'baz';
};
return Foo;
}(Bar));`
},
{
description: 'transpiles a subclass with super calls',
options: { namedFunctionExpressions: false },
input: `
class Foo extends Bar {
constructor ( x ) {
super( x );
this.y = 'z';
}
baz ( a, b, c ) {
super.baz( a, b, c );
}
}`,
output: `
var Foo = /*@__PURE__*/(function (Bar) {
function Foo ( x ) {
Bar.call( this, x );
this.y = 'z';
}
if ( Bar ) Foo.__proto__ = Bar;
Foo.prototype = Object.create( Bar && Bar.prototype );
Foo.prototype.constructor = Foo;
Foo.prototype.baz = function ( a, b, c ) {
Bar.prototype.baz.call( this, a, b, c );
};
return Foo;
}(Bar));`
},
{
description: 'transpiles a subclass with super calls with spread arguments',
options: { namedFunctionExpressions: false },
input: `
class Foo extends Bar {
baz ( ...args ) {
super.baz(...args);
}
boz ( x, y, ...z ) {
super.boz(x, y, ...z);
}
fab ( x, ...y ) {
super.qux(...x, ...y);
}
fob ( x, y, ...z ) {
((x, y, z) => super.qux(x, ...y, ...z))(x, y, z);
}
}`,
output: `
var Foo = /*@__PURE__*/(function (Bar) {
function Foo () {
Bar.apply(this, arguments);
}
if ( Bar ) Foo.__proto__ = Bar;
Foo.prototype = Object.create( Bar && Bar.prototype );
Foo.prototype.constructor = Foo;
Foo.prototype.baz = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
Bar.prototype.baz.apply(this, args);
};
Foo.prototype.boz = function ( x, y ) {
var z = [], len = arguments.length - 2;
while ( len-- > 0 ) z[ len ] = arguments[ len + 2 ];
Bar.prototype.boz.apply(this, [ x, y ].concat( z ));
};
Foo.prototype.fab = function ( x ) {
var y = [], len = arguments.length - 1;
while ( len-- > 0 ) y[ len ] = arguments[ len + 1 ];
Bar.prototype.qux.apply(this, x.concat( y ));
};
Foo.prototype.fob = function ( x, y ) {
var this$1 = this;
var z = [], len = arguments.length - 2;
while ( len-- > 0 ) z[ len ] = arguments[ len + 2 ];
(function (x, y, z) { return Bar.prototype.qux.apply(this$1, [ x ].concat( y, z )); })(x, y, z);
};
return Foo;
}(Bar));`
},
{
description: 'transpiles export default class',
options: {
transforms: { moduleExport: false },
namedFunctionExpressions: false
},
input: `
export default class Foo {
bar () {}
}`,
output: `
var Foo = function () {};
Foo.prototype.bar = function () {};
export default Foo;`
},
{
description: 'transpiles export default subclass',
options: {
transforms: { moduleExport: false },
namedFunctionExpressions: false
},
input: `
export default class Foo extends Bar {
bar () {}
}`,
output: `
var Foo = /*@__PURE__*/(function (Bar) {
function Foo () {
Bar.apply(this, arguments);
}
if ( Bar ) Foo.__proto__ = Bar;
Foo.prototype = Object.create( Bar && Bar.prototype );
Foo.prototype.constructor = Foo;
Foo.prototype.bar = function () {};
return Foo;
}(Bar));
export default Foo;`
},
{
description: 'transpiles export default subclass with subsequent statement',
options: {
transforms: { moduleExport: false },
namedFunctionExpressions: false
},
input: `
export default class Foo extends Bar {
bar () {}
}
new Foo().bar();`,
output: `
var Foo = /*@__PURE__*/(function (Bar) {
function Foo () {
Bar.apply(this, arguments);
}
if ( Bar ) Foo.__proto__ = Bar;
Foo.prototype = Object.create( Bar && Bar.prototype );
Foo.prototype.constructor = Foo;
Foo.prototype.bar = function () {};
return Foo;
}(Bar));
export default Foo;
new Foo().bar();`
},
{
description: 'transpiles empty class',
options: { namedFunctionExpressions: false },
input: `class Foo {}`,
output: `var Foo = function () {};`
},
{
description: 'transpiles an anonymous empty class expression',
options: { namedFunctionExpressions: false },
input: `
var Foo = class {};`,
output: `
var Foo = /*@__PURE__*/(function () {
function Foo () {}
return Foo;
}());`
},
{
description: 'transpiles an anonymous class expression with a constructor',
options: { namedFunctionExpressions: false },
input: `
var Foo = class {
constructor ( x ) {
this.x = x;
}
};`,
output: `
var Foo = /*@__PURE__*/(function () {
function Foo ( x ) {
this.x = x;
}
return Foo;
}());`
},
{
description:
'transpiles an anonymous class expression with a non-constructor method',
options: { namedFunctionExpressions: false },
input: `
var Foo = class {
bar ( x ) {
console.log( x );
}
};`,
output: `
var Foo = /*@__PURE__*/(function () {
function Foo () {}
Foo.prototype.bar = function ( x ) {
console.log( x );
};
return Foo;
}());`
},
{
description: 'allows constructor to be in middle of body',
options: { namedFunctionExpressions: false },
input: `
class Foo {
before () {
// code goes here
}
constructor () {
// constructor goes here
}
after () {
// code goes here
}
}`,
output: `
var Foo = function () {
// constructor goes here
};
Foo.prototype.before = function () {
// code goes here
};
Foo.prototype.after = function () {
// code goes here
};`
},
{
description: 'allows constructor to be at end of body',
options: { namedFunctionExpressions: false },
input: `
class Foo {
before () {
// code goes here
}
constructor () {
// constructor goes here
}
}`,
output: `
var Foo = function () {
// constructor goes here
};
Foo.prototype.before = function () {
// code goes here
};`
},
{
description: 'transpiles getters and setters',
options: { namedFunctionExpressions: false },
input: `
class Circle {
constructor ( radius ) {
this.radius = radius;
}
get area () {
return Math.PI * Math.pow( this.radius, 2 );
}
set area ( area ) {
this.radius = Math.sqrt( area / Math.PI );
}
static get description () {
return 'round';
}
}`,
output: `
var Circle = function ( radius ) {
this.radius = radius;
};
var prototypeAccessors = { area: { configurable: true } };
var staticAccessors = { description: { configurable: true } };
prototypeAccessors.area.get = function () {
return Math.PI * Math.pow( this.radius, 2 );
};
prototypeAccessors.area.set = function ( area ) {
this.radius = Math.sqrt( area / Math.PI );
};
staticAccessors.description.get = function () {
return 'round';
};
Object.defineProperties( Circle.prototype, prototypeAccessors );
Object.defineProperties( Circle, staticAccessors );`
},
{
description: 'transpiles getters and setters in subclass',
options: { namedFunctionExpressions: false },
input: `
class Circle extends Shape {
constructor ( radius ) {
super();
this.radius = radius;
}
get area () {
return Math.PI * Math.pow( this.radius, 2 );
}
set area ( area ) {
this.radius = Math.sqrt( area / Math.PI );
}
static get description () {
return 'round';
}
}`,
output: `
var Circle = /*@__PURE__*/(function (Shape) {
function Circle ( radius ) {
Shape.call(this);
this.radius = radius;
}
if ( Shape ) Circle.__proto__ = Shape;
Circle.prototype = Object.create( Shape && Shape.prototype );
Circle.prototype.constructor = Circle;
var prototypeAccessors = { area: { configurable: true } };
var staticAccessors = { description: { configurable: true } };
prototypeAccessors.area.get = function () {
return Math.PI * Math.pow( this.radius, 2 );
};
prototypeAccessors.area.set = function ( area ) {
this.radius = Math.sqrt( area / Math.PI );
};
staticAccessors.description.get = function () {
return 'round';
};
Object.defineProperties( Circle.prototype, prototypeAccessors );
Object.defineProperties( Circle, staticAccessors );
return Circle;
}(Shape));`
},
{
description: 'can be disabled with `transforms.classes: false`',
options: {
namedFunctionExpressions: false,
transforms: { classes: false }
},
input: `
class Foo extends Bar {
constructor ( answer ) {
super();
this.answer = answer;
}
}`,
output: `
class Foo extends Bar {
constructor ( answer ) {
super();
this.answer = answer;
}
}`
},
{
description: 'declaration extends from an expression (#15)',
options: { namedFunctionExpressions: false },
input: `
const q = {a: class {}};
class b extends q.a {
c () {}
}`,
output: `
var q = {a: /*@__PURE__*/(function () {
function anonymous () {}
return anonymous;
}())};
var b = /*@__PURE__*/(function (superclass) {
function b () {
superclass.apply(this, arguments);
}
if ( superclass ) b.__proto__ = superclass;
b.prototype = Object.create( superclass && superclass.prototype );
b.prototype.constructor = b;
b.prototype.c = function () {};
return b;
}(q.a));`
},
{
description: 'expression extends from an expression (#15)',
options: { namedFunctionExpressions: false },
input: `
const q = {a: class {}};
const b = class b extends q.a {
c () {}
};`,
output: `
var q = {a: /*@__PURE__*/(function () {
function anonymous () {}
return anonymous;
}())};
var b = /*@__PURE__*/(function (superclass) {
function b () {
superclass.apply(this, arguments);
}
if ( superclass ) b.__proto__ = superclass;
b.prototype = Object.create( superclass && superclass.prototype );
b.prototype.constructor = b;
b.prototype.c = function () {};
return b;
}(q.a));`
},
{
description: 'expression extends from an expression with super calls (#31)',
options: { namedFunctionExpressions: false },
input: `
class b extends x.y.z {
constructor() {
super();
}
}`,
output: `
var b = /*@__PURE__*/(function (superclass) {
function b() {
superclass.call(this);
}
if ( superclass ) b.__proto__ = superclass;
b.prototype = Object.create( superclass && superclass.prototype );
b.prototype.constructor = b;
return b;
}(x.y.z));`
},
{
description: 'anonymous expression extends named class (#31)',
options: { namedFunctionExpressions: false },
input: `
SubClass = class extends SuperClass {
constructor() {
super();
}
};`,
output: `
SubClass = /*@__PURE__*/(function (SuperClass) {
function SubClass() {
SuperClass.call(this);
}
if ( SuperClass ) SubClass.__proto__ = SuperClass;
SubClass.prototype = Object.create( SuperClass && SuperClass.prototype );
SubClass.prototype.constructor = SubClass;
return SubClass;
}(SuperClass));`
},
{
description:
'verify deindent() does not corrupt string literals in class methods (#159)',
options: { namedFunctionExpressions: false },
input: `
class Foo {
bar() {
var s = "0\t1\t\t2\t\t\t3\t\t\t\t4\t\t\t\t\t5";
return s + '\t';
}
baz() {
return \`\t\`;
}
}
`,
output: `
var Foo = function () {};
Foo.prototype.bar = function () {
var s = "0\t1\t\t2\t\t\t3\t\t\t\t4\t\t\t\t\t5";
return s + '\t';
};
Foo.prototype.baz = function () {
return "\\t";
};
`
},
{
description: 'deindents a function body with destructuring (#22)',
options: { namedFunctionExpressions: false },
input: `
class Foo {
constructor ( options ) {
const {
a,
b
} = options;
}
}`,
output: `
var Foo = function ( options ) {
var a = options.a;
var b = options.b;
};`
},
{
description: 'allows super in static methods',
options: { namedFunctionExpressions: false },
input: `
class Foo extends Bar {
static baz () {
super.baz();
}
}`,
output: `
var Foo = /*@__PURE__*/(function (Bar) {
function Foo () {
Bar.apply(this, arguments);
}
if ( Bar ) Foo.__proto__ = Bar;
Foo.prototype = Object.create( Bar && Bar.prototype );
Foo.prototype.constructor = Foo;
Foo.baz = function () {
Bar.baz.call(this);
};
return Foo;
}(Bar));`
},
{
description: 'allows zero space between class id and body (#46)',
options: { namedFunctionExpressions: false },
input: `
class A{
x(){}
}
var B = class B{
x(){}
};
class C extends D{
x(){}
}
var E = class E extends F{
x(){}
}`,
output: `
var A = function () {};
A.prototype.x = function (){};
var B = /*@__PURE__*/(function () {
function B () {}
B.prototype.x = function (){};
return B;
}());
var C = /*@__PURE__*/(function (D) {
function C () {
D.apply(this, arguments);
}
if ( D ) C.__proto__ = D;
C.prototype = Object.create( D && D.prototype );
C.prototype.constructor = C;
C.prototype.x = function (){};
return C;
}(D));
var E = /*@__PURE__*/(function (F) {
function E () {
F.apply(this, arguments);
}
if ( F ) E.__proto__ = F;
E.prototype = Object.create( F && F.prototype );
E.prototype.constructor = E;
E.prototype.x = function (){};
return E;
}(F))`
},
{
description: 'transpiles a class with an accessor and no constructor (#48)',
options: { namedFunctionExpressions: false },
input: `
class Foo {
static get bar() { return 'baz' }
}`,
output: `
var Foo = function () {};
var staticAccessors = { bar: { configurable: true } };
staticAccessors.bar.get = function () { return 'baz' };
Object.defineProperties( Foo, staticAccessors );`
},
{
description:
'uses correct indentation for inserted statements in constructor (#39)',
options: { namedFunctionExpressions: false },
input: `
class Foo {
constructor ( options, { a2, b2 } ) {
const { a, b } = options;
const render = () => {
requestAnimationFrame( render );
this.render();
};
render();
}
render () {
// code goes here...
}
}`,
output: `
var Foo = function ( options, ref ) {
var this$1 = this;
var a2 = ref.a2;
var b2 = ref.b2;
var a = options.a;
var b = options.b;
var render = function () {
requestAnimationFrame( render );
this$1.render();
};
render();
};
Foo.prototype.render = function () {
// code goes here...
};`
},
{
description:
'uses correct indentation for inserted statements in subclass constructor (#39)',
options: { namedFunctionExpressions: false },
input: `
class Foo extends Bar {
constructor ( options, { a2, b2 } ) {
super();
const { a, b } = options;
const render = () => {
requestAnimationFrame( render );
this.render();
};
render();
}
render () {
// code goes here...
}
}`,
output: `
var Foo = /*@__PURE__*/(function (Bar) {
function Foo ( options, ref ) {
var this$1 = this;
var a2 = ref.a2;
var b2 = ref.b2;
Bar.call(this);
var a = options.a;
var b = options.b;
var render = function () {
requestAnimationFrame( render );
this$1.render();
};
render();
}
if ( Bar ) Foo.__proto__ = Bar;
Foo.prototype = Object.create( Bar && Bar.prototype );
Foo.prototype.constructor = Foo;
Foo.prototype.render = function () {
// code goes here...
};
return Foo;
}(Bar));`
},
{
description: 'allows subclass to use rest parameters',
options: { namedFunctionExpressions: false },
input: `
class SubClass extends SuperClass {
constructor( ...args ) {
super( ...args );
}
}`,
output: `
var SubClass = /*@__PURE__*/(function (SuperClass) {
function SubClass() {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
SuperClass.apply( this, args );
}
if ( SuperClass ) SubClass.__proto__ = SuperClass;
SubClass.prototype = Object.create( SuperClass && SuperClass.prototype );
SubClass.prototype.constructor = SubClass;
return SubClass;
}(SuperClass));`
},
{
description: 'allows subclass to use rest parameters with other arguments',
options: { namedFunctionExpressions: false },
input: `
class SubClass extends SuperClass {
constructor( ...args ) {
super( 1, ...args, 2 );
}
}`,
output: `
var SubClass = /*@__PURE__*/(function (SuperClass) {
function SubClass() {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
SuperClass.apply( this, [ 1 ].concat( args, [2] ) );
}
if ( SuperClass ) SubClass.__proto__ = SuperClass;
SubClass.prototype = Object.create( SuperClass && SuperClass.prototype );
SubClass.prototype.constructor = SubClass;
return SubClass;
}(SuperClass));`
},
{
description: 'transpiles computed class properties',
options: { namedFunctionExpressions: false },
input: `
class Foo {
[a.b.c] () {
// code goes here
}
}`,
output: `
var Foo = function () {};
Foo.prototype[a.b.c] = function () {
// code goes here
};`
},
{
description: 'transpiles static computed class properties',
options: { namedFunctionExpressions: false },
input: `
class Foo {
static [a.b.c] () {
// code goes here
}
}`,
output: `
var Foo = function () {};
Foo[a.b.c] = function () {
// code goes here
};`
},
{
skip: true,
description: 'transpiles computed class accessors',
options: { namedFunctionExpressions: false },
input: `
class Foo {
get [a.b.c] () {
// code goes here
}
}`,
output: `
var Foo = function () {};
var prototypeAccessors = {};
var ref = a.b.c;
prototypeAccessors[ref] = {};
prototypeAccessors[ref].get = function () {
// code goes here
};
Object.defineProperties( Foo.prototype, prototypeAccessors );`
},
{
description: 'transpiles reserved class properties (!68)',
options: { namedFunctionExpressions: false },
input: `
class Foo {
catch () {
// code goes here
}
}`,
output: `
var Foo = function () {};
Foo.prototype.catch = function () {
// code goes here
};`
},
{
description: 'transpiles static reserved class properties (!68)',
options: { namedFunctionExpressions: false },
input: `
class Foo {
static catch () {
// code goes here
}
}`,
output: `
var Foo = function () {};
Foo.catch = function () {
// code goes here
};`
},
{
description: 'uses correct `this` when transpiling `super` (#89)',
options: { namedFunctionExpressions: false },
input: `
class A extends B {
constructor () {
super();
this.doSomething(() => {
super.doSomething();
});
}
}`,
output: `
var A = /*@__PURE__*/(function (B) {
function A () {
var this$1 = this;
B.call(this);
this.doSomething(function () {
B.prototype.doSomething.call(this$1);
});
}
if ( B ) A.__proto__ = B;
A.prototype = Object.create( B && B.prototype );
A.prototype.constructor = A;
return A;
}(B));`
},
{
description: 'methods with computed names',
options: { namedFunctionExpressions: false },
input: `
class A {
[x](){}
[0](){}
[1 + 2](){}
[normal + " Method"](){}
}
`,
output: `
var A = function () {};
A.prototype[x] = function (){};
A.prototype[0] = function (){};
A.prototype[1 + 2] = function (){};
A.prototype[normal + " Method"] = function (){};
`
},
{
description:
'static methods with computed names with varied spacing (#139)',
options: { namedFunctionExpressions: false },
input: `
class B {
static[.000004](){}
static [x](){}
static [x-y](){}
static[\`Static computed \${name}\`](){}
}
`,
output: `
var B = function () {};
B[.000004] = function (){};
B[x] = function (){};
B[x-y] = function (){};
B[("Static computed " + name)] = function (){};
`
},
{
description: 'methods with numeric or string names (#139)',
options: { namedFunctionExpressions: false },
input: `
class C {
0(){}
0b101(){}
80(){}
.12e3(){}
0o753(){}
12e34(){}
0xFFFF(){}
"var"(){}
}
`,
output: `
var C = function () {};
C.prototype[0] = function (){};
C.prototype[5] = function (){};
C.prototype[80] = function (){};
C.prototype[.12e3] = function (){};
C.prototype[491] = function (){};
C.prototype[12e34] = function (){};
C.prototype[0xFFFF] = function (){};
C.prototype["var"] = function (){};
`
},
{
description:
'static methods with numeric or string names with varied spacing (#139)',
options: { namedFunctionExpressions: false },
input: `
class D {
static .75(){}
static"Static Method"(){}
static "foo"(){}
}
`,
output: `
var D = function () {};
D[.75] = function (){};
D["Static Method"] = function (){};
D["foo"] = function (){};
`
}
// TODO more tests. e.g. getters and setters.
// 'super.*' is not allowed before super()
];
| {
"pile_set_name": "Github"
} |
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Formatting;
namespace RefactoringEssentials.CSharp.CodeRefactorings
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Convert '??' to '?:'")]
public class ConvertCoalescingToConditionalExpressionCodeRefactoringProvider : CodeRefactoringProvider
{
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
var span = context.Span;
if (!span.IsEmpty)
return;
var cancellationToken = context.CancellationToken;
if (cancellationToken.IsCancellationRequested)
return;
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (model.IsFromGeneratedCode(cancellationToken))
return;
var node = root.FindNode(span) as BinaryExpressionSyntax;
if (node == null || !node.OperatorToken.IsKind(SyntaxKind.QuestionQuestionToken))
return;
context.RegisterRefactoring(
CodeActionFactory.Create(
span,
DiagnosticSeverity.Info,
GettextCatalog.GetString("Replace '??' operator with '?:' expression"), t2 =>
{
var left = node.Left;
var info = model.GetTypeInfo(left, t2);
if (info.ConvertedType.IsNullableType())
left = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, CSharpUtil.AddParensIfRequired(left), SyntaxFactory.IdentifierName("Value"));
var ternary = SyntaxFactory.ConditionalExpression(
SyntaxFactory.BinaryExpression(
SyntaxKind.NotEqualsExpression,
node.Left,
SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)
),
left,
node.Right
).WithAdditionalAnnotations(Formatter.Annotation);
return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(node, ternary)));
}
)
);
}
}
} | {
"pile_set_name": "Github"
} |
---
sidebarDepth: 3
sidebar: auto
---
# Tight Layout guide
How to use tight-layout to fit plots within your figure cleanly.
*tight_layout* automatically adjusts subplot params so that the
subplot(s) fits in to the figure area. This is an experimental
feature and may not work for some cases. It only checks the extents
of ticklabels, axis labels, and titles.
An alternative to *tight_layout* is [constrained_layout](constrainedlayout_guide.html).
## Simple Example
In matplotlib, the location of axes (including subplots) are specified in
normalized figure coordinates. It can happen that your axis labels or
titles (or sometimes even ticklabels) go outside the figure area, and are thus
clipped.
``` python
# sphinx_gallery_thumbnail_number = 7
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['savefig.facecolor'] = "0.8"
def example_plot(ax, fontsize=12):
ax.plot([1, 2])
ax.locator_params(nbins=3)
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
plt.close('all')
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
```

To prevent this, the location of axes needs to be adjusted. For
subplots, this can be done by adjusting the subplot params
([Move the edge of an axes to make room for tick labels](https://matplotlib.orgfaq/howto_faq.html#howto-subplots-adjust)). Matplotlib v1.1 introduces a new
command [``tight_layout()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.tight_layout.html#matplotlib.pyplot.tight_layout) that does this
automatically for you.
``` python
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
plt.tight_layout()
```

Note that [``matplotlib.pyplot.tight_layout()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.tight_layout.html#matplotlib.pyplot.tight_layout) will only adjust the
subplot params when it is called. In order to perform this adjustment each
time the figure is redrawn, you can call ``fig.set_tight_layout(True)``, or,
equivalently, set the ``figure.autolayout`` rcParam to ``True``.
When you have multiple subplots, often you see labels of different
axes overlapping each other.
``` python
plt.close('all')
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
```

[``tight_layout()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.tight_layout.html#matplotlib.pyplot.tight_layout) will also adjust spacing between
subplots to minimize the overlaps.
``` python
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout()
```

[``tight_layout()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.tight_layout.html#matplotlib.pyplot.tight_layout) can take keyword arguments of
*pad*, *w_pad* and *h_pad*. These control the extra padding around the
figure border and between subplots. The pads are specified in fraction
of fontsize.
``` python
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
```

[``tight_layout()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.tight_layout.html#matplotlib.pyplot.tight_layout) will work even if the sizes of
subplots are different as far as their grid specification is
compatible. In the example below, *ax1* and *ax2* are subplots of a 2x2
grid, while *ax3* is of a 1x2 grid.
``` python
plt.close('all')
fig = plt.figure()
ax1 = plt.subplot(221)
ax2 = plt.subplot(223)
ax3 = plt.subplot(122)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
plt.tight_layout()
```

It works with subplots created with
[``subplot2grid()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.subplot2grid.html#matplotlib.pyplot.subplot2grid). In general, subplots created
from the gridspec ([Customizing Figure Layouts Using GridSpec and Other Functions](gridspec.html)) will work.
``` python
plt.close('all')
fig = plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0))
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout()
```

Although not thoroughly tested, it seems to work for subplots with
aspect != "auto" (e.g., axes with images).
``` python
arr = np.arange(100).reshape((10, 10))
plt.close('all')
fig = plt.figure(figsize=(5, 4))
ax = plt.subplot(111)
im = ax.imshow(arr, interpolation="none")
plt.tight_layout()
```

## Caveats
- [``tight_layout()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.tight_layout.html#matplotlib.pyplot.tight_layout) only considers ticklabels, axis
labels, and titles. Thus, other artists may be clipped and also may
overlap.
- It assumes that the extra space needed for ticklabels, axis labels,
and titles is independent of original location of axes. This is
often true, but there are rare cases where it is not.
- pad=0 clips some of the texts by a few pixels. This may be a bug or
a limitation of the current algorithm and it is not clear why it
happens. Meanwhile, use of pad at least larger than 0.3 is
recommended.
## Use with GridSpec
GridSpec has its own [``tight_layout()``](https://matplotlib.orgapi/_as_gen/matplotlib.gridspec.GridSpec.html#matplotlib.gridspec.GridSpec.tight_layout) method
(the pyplot api [``tight_layout()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.tight_layout.html#matplotlib.pyplot.tight_layout) also works).
``` python
import matplotlib.gridspec as gridspec
plt.close('all')
fig = plt.figure()
gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
gs1.tight_layout(fig)
```

You may provide an optional *rect* parameter, which specifies the bounding box
that the subplots will be fit inside. The coordinates must be in normalized
figure coordinates and the default is (0, 0, 1, 1).
``` python
fig = plt.figure()
gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
```

For example, this can be used for a figure with multiple gridspecs.
``` python
fig = plt.figure()
gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
gs2 = gridspec.GridSpec(3, 1)
for ss in gs2:
ax = fig.add_subplot(ss)
example_plot(ax)
ax.set_title("")
ax.set_xlabel("")
ax.set_xlabel("x-label", fontsize=12)
gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5)
# We may try to match the top and bottom of two grids ::
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.update(top=top, bottom=bottom)
gs2.update(top=top, bottom=bottom)
plt.show()
```

While this should be mostly good enough, adjusting top and bottom
may require adjustment of hspace also. To update hspace & vspace, we
call [``tight_layout()``](https://matplotlib.orgapi/_as_gen/matplotlib.gridspec.GridSpec.html#matplotlib.gridspec.GridSpec.tight_layout) again with updated
rect argument. Note that the rect argument specifies the area including the
ticklabels, etc. Thus, we will increase the bottom (which is 0 for the normal
case) by the difference between the *bottom* from above and the bottom of each
gridspec. Same thing for the top.
``` python
fig = plt.gcf()
gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
example_plot(ax1)
example_plot(ax2)
gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
gs2 = gridspec.GridSpec(3, 1)
for ss in gs2:
ax = fig.add_subplot(ss)
example_plot(ax)
ax.set_title("")
ax.set_xlabel("")
ax.set_xlabel("x-label", fontsize=12)
gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5)
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.update(top=top, bottom=bottom)
gs2.update(top=top, bottom=bottom)
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom),
0.5, 1 - (gs1.top-top)])
gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom),
None, 1 - (gs2.top-top)],
h_pad=0.5)
```

## Legends and Annotations
Pre Matplotlib 2.2, legends and annotations were excluded from the bounding
box calculations that decide the layout. Subsequently these artists were
added to the calculation, but sometimes it is undesirable to include them.
For instance in this case it might be good to have the axes shring a bit
to make room for the legend:
``` python
fig, ax = plt.subplots(figsize=(4, 3))
lines = ax.plot(range(10), label='A simple plot')
ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',)
fig.tight_layout()
plt.show()
```

However, sometimes this is not desired (quite often when using
``fig.savefig('outname.png', bbox_inches='tight')``). In order to
remove the legend from the bounding box calculation, we simply set its
bounding ``leg.set_in_layout(False)`` and the legend will be ignored.
``` python
fig, ax = plt.subplots(figsize=(4, 3))
lines = ax.plot(range(10), label='B simple plot')
leg = ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',)
leg.set_in_layout(False)
fig.tight_layout()
plt.show()
```

## Use with AxesGrid1
While limited, the axes_grid1 toolkit is also supported.
``` python
from mpl_toolkits.axes_grid1 import Grid
plt.close('all')
fig = plt.figure()
grid = Grid(fig, rect=111, nrows_ncols=(2, 2),
axes_pad=0.25, label_mode='L',
)
for ax in grid:
example_plot(ax)
ax.title.set_visible(False)
plt.tight_layout()
```

## Colorbar
If you create a colorbar with the [``colorbar()``](https://matplotlib.orgapi/_as_gen/matplotlib.pyplot.colorbar.html#matplotlib.pyplot.colorbar)
command, the created colorbar is an instance of Axes, *not* Subplot, so
tight_layout does not work. With Matplotlib v1.1, you may create a
colorbar as a subplot using the gridspec.
``` python
plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none")
plt.colorbar(im, use_gridspec=True)
plt.tight_layout()
```

Another option is to use AxesGrid1 toolkit to
explicitly create an axes for colorbar.
``` python
from mpl_toolkits.axes_grid1 import make_axes_locatable
plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none")
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", "5%", pad="3%")
plt.colorbar(im, cax=cax)
plt.tight_layout()
```

**Total running time of the script:** ( 0 minutes 3.417 seconds)
## Download
- [Download Python source code: tight_layout_guide.py](https://matplotlib.org/_downloads/08204f760ca1d178acca434333c21c5c/tight_layout_guide.py)
- [Download Jupyter notebook: tight_layout_guide.ipynb](https://matplotlib.org/_downloads/967ce4dd04ce9628b993a5a4e402046a/tight_layout_guide.ipynb)
| {
"pile_set_name": "Github"
} |
# Please note that this is only a sample, we recommend you to change it to fit
# your needs.
# You should override this file using a post-build script.
# See http://buildroot.org/manual.html#rootfs-custom
# and http://elinux.org/RPiconfig for a description of config.txt syntax
# We always use the same names, the real used variant is selected by
# BR2_PACKAGE_RPI_FIRMWARE_{DEFAULT,X,CD} choice
start_file=start.elf
fixup_file=fixup.dat
kernel=zImage
# To use an external initramfs file
#initramfs rootfs.cpio.gz
# Disable overscan assuming the display supports displaying the full resolution
# If the text shown on the screen disappears off the edge, comment this out
disable_overscan=1
# How much memory in MB to assign to the GPU on Pi models having
# 256, 512 or 1024 MB total memory
gpu_mem_256=100
gpu_mem_512=100
gpu_mem_1024=100
| {
"pile_set_name": "Github"
} |
{
"word": "Caption",
"definitions": [
"A title or brief explanation accompanying an illustration, cartoon, or poster.",
"A piece of text appearing on a cinema or television screen as part of a film or broadcast.",
"The heading of a legal document."
],
"parts-of-speech": "Noun"
} | {
"pile_set_name": "Github"
} |
#load-save.modal.fade.gl_keep(tabindex="-1" role="dialog")
.modal-dialog.modal-lg
.modal-content
.modal-header
h5.modal-title Load and save editor text
button.close(type="button" data-dismiss="modal" aria-hidden="true" aria-label="Close")
span(aria-hidden="true")
| ×
.modal-body
.card
.card-header
ul.nav.nav-tabs.card-header-tabs(role="tablist")
li.nav-item(role="presentation"): a.nav-link.active(href="#load-examples" role="tab" data-toggle="tab") Examples
li.nav-item(role="presentation"): a.nav-link(href="#load-browser-local" role="tab" data-toggle="tab") Browser-local storage
li.nav-item(role="presentation"): a.nav-link(href="#load-browser-local-history" role="tab" data-toggle="tab") Browser-local history
li.nav-item(role="presentation"): a.nav-link(href="#load-file-system" role="tab" data-toggle="tab") File system
.card-body.tab-content
#load-examples.tab-pane.active(role="tabpanel")
h4.card-title Load from examples:
ul.examples.small-v-scrollable
li.template: a(href="javascript:;")
#load-browser-local.tab-pane(role="tabpanel")
h4.card-title Load from browser-local storage:
ul.local-storage.small-v-scrollable
li.template: a(href="javascript:;")
.input-group
input.save-name(type="text" size="20" placeholder="Set name of state")
.input-group-append
button.btn.btn-light.save-button(type="button") Save to browser-local storage
#load-browser-local-history.tab-pane(role="tabpanel")
h4.card-title Load from browser-local history:
ul.local-history.small-v-scrollable
li.template: a(href="javascript:;")
#load-file-system.tab-pane(role="tabpanel")
h4.card-title Load/save to your system
label.btn.btn-outline-secondary.btn-file(role="button") Load from a local file
input.local-file(type="file")
label.btn.btn-outline-secondary.btn-file.save-btn(role="button") Save to file
input.save-file(type="button")
.modal-footer
button.btn.btn-light(type="button" data-dismiss="modal" aria-label="Close") Close
#alert.modal.fade.gl_keep(tabindex="-1" role="dialog")
.modal-dialog.modal-lg
.modal-content
.modal-header
h5.modal-title Something alert worthy
button.close(type="button" data-dismiss="modal" aria-hidden="true" aria-label="Close")
span(aria-hidden="true")
| ×
.modal-body
.modal-footer
button.btn.btn-light(type="button" data-dismiss="modal") Close
#yes-no.modal.fade.gl_keep(tabindex="-1" role="dialog")
.modal-dialog.modal-lg
.modal-content
.modal-header
h5.modal-title Well, do you or not?
button.close(type="button" data-dismiss="modal" aria-hidden="true" aria-label="Close")
span(aria-hidden="true")
| ×
.modal-body
.modal-footer
button.btn.btn-light.no(type="button" data-dismiss="modal") No
button.btn.btn-light.yes(type="button" data-dismiss="modal") Yes
#settings.modal.fade.gl_keep(tabindex="-1" role="dialog")
.modal-dialog.modal-lg
.modal-content
.modal-header
h5.modal-title Compiler Explorer Settings
button.close(type="button" data-dismiss="modal" aria-hidden="true" aria-label="Close")
span(aria-hidden="true")
| ×
.modal-body
.card
.card-header
| These settings control how Compiler Explorer acts for you. They are not
| preserved as part of shared URLs, and are persisted locally using browser
| local storage.
.card-body
.card-title
h4 Site behaviour
.form-group(role="group")
label
| Default language
small
span.fas.fa-info-circle(title="New editors only (Reset UI to clear yours)" aria-label="New editors only (Reset UI to clear yours)")
select.defaultLanguage
.checkbox
label
input.allowStoreCodeDebug(type="checkbox")
| Allow my source code to be temporarily stored for diagnostic purposes in the event of an error
div
label
| Theme
select.theme
.checkbox
label
input.newEditorLastLang(type="checkbox")
| Use last selected language when opening new Editors
.checkbox
label
input.enableCommunityAds(type="checkbox")
| Show community events
.card
.card-body
.card-title
h4 Keybindings
.form-group(role="group")
.checkbox
label
input.useVim(type="checkbox")
| Vim
.card
.card-body
.card-title
h4 Editor
.form-group(role="group")
div
label
| Desired Font Family in editors
input.editorsFFont(type="text" style="width:100%")
.checkbox
label
input.editorsFLigatures(type="checkbox")
| Enable font ligatures
.checkbox
label
input.autoCloseBrackets(type="checkbox")
| Automatically insert matching brackets and parentheses
.checkbox
label
input.autoIndent(type="checkbox")
| Automatically indent code (reload page after changing)
.checkbox
label
input.hoverShowSource(type="checkbox")
| Highlight linked code lines on hover
.checkbox
label
input.hoverShowAsmDoc(type="checkbox")
| Show asm description on hover
.checkbox
label
input.showQuickSuggestions(type="checkbox")
| Show quick suggestions
.checkbox
label
input.useCustomContextMenu(type="checkbox")
| Use custom context menu
.checkbox
label
input.showMinimap(type="checkbox")
| Show editor minimap
.checkbox
label
input.keepSourcesOnLangChange(type="checkbox")
| Keep editor source on language change
.checkbox
label
input.useSpaces(type="checkbox")
| Use spaces for indentation
div
label
| Tab width
input.tabWidth(type="numeric")
div
label
| Format based on
select.formatBase
.checkbox
label
input.enableCtrlS(type="checkbox")
| Make
kbd Ctrl
| +
kbd S
| save to local file instead of creating a share link
.checkbox
label
input.wordWrap(type="checkbox")
| Enable Word Wrapping
.card
.card-body
.card-title
h4 Compilation
.form-group(role="group")
div
.checkbox
label
input.compileOnChange(type="checkbox")
| Compile automatically when source changes
div Delay before compiling:
b 0.25s
.slider.slider-horizontal.delay
b 3s
.checkbox
label
input.colourise(type="checkbox")
| Colourise lines to show how the source maps to the output
label
| Colour scheme
select.colourScheme
.modal-footer
button.btn.btn-light(type="button" data-dismiss="modal") Close
#simplecook.gl_keep(tabindex="-1" role="dialog" style="display:none")
.message
.btn-group.btn-group-sm
button.btn.btn-light.btn-sm.cookies(title="Read cookie policy" aria-label="Read new cookie policy")
span.fas.fa-info-circle
| Read the new cookie policy
p.new-cookie-msg Compiler Explorer uses cookies and other related techs to serve you
.btn-group.btn-group-sm(role="group" aria-label="Consent options" style="float:right")
button.btn.btn-light.btn-sm.cook-do-consent.consent-cookie-yes(title="Consent cookie policy" aria-label="Consent cookie policy")
span.fas.fa-thumbs-up
| Consent
button.btn.btn-light.btn-sm.cook-dont-consent.consent-cookie-no(title="Do not consent cookie policy" aria-label="Oppose cookie policy")
span.fas.fa-thumbs-down
| Don't consent
#notifications
#shareembedlink.modal.fade.gl_keep(tabindex="-1" role="dialog")
.modal-dialog.modal-lg
.modal-content
.modal-header
h5.modal-title Share embedded
button.close(type="button" data-dismiss="modal" aria-hidden="true" aria-label="Close")
span(aria-hidden="true")
| ×
.modal-body
.card
.card-body
.input-group-append
input.form-control.input-sm.permalink(type="text" placeholder="Loading" readonly size="1024" style="font-size: 10px")
button.input-group-btn.btn.btn-outline-secondary.btn-sm.clippy(type="button" data-clipboard-target="#shareembedlink .permalink" title="Copy to clipboard")
span.fa.fa-clipboard
#embedsettings.form-group(role="group")
.checkbox
label
input.readOnly(type="checkbox")
| Read Only
.checkbox
label
input.hideEditorToolbars(type="checkbox")
| Hide Editor Toolbars
#history.modal.fade.gl_keep(tabindex="-1" role="dialog")
.modal-dialog.modal-lg
.modal-content
.modal-header
h5.modal-title History
button.close(type="button" data-dismiss="modal" aria-hidden="true" aria-label="Close")
span(aria-hidden="true")
| ×
.modal-body
.card
.card-body
ul.nav.nav-tabs(role="tablist")
li.nav-item
a.nav-link.active(data-toggle="tab" role="tab" href="#load-history" aria-controls="load-history" aria-selected="true")
| History
li.nav-item
a.nav-link(data-toggle="tab" role="tab" href="#load-history-diff-display" aria-controls="load-history-diff-display" aria-selected="false")
| Diff
div.tab-content#historyTabs(style="height:600px;overflow-y:scroll")
div.tab-pane.show.active#load-history(role="tabpanel")
ul.historiccode
li.template
input.base(type="radio" name="base")
input.comp(type="radio" name="comp")
|
a(href="javascript:;")
div.tab-pane#load-history-diff-display(role="tabpanel")
.checkbox
label.control-label(for="inline-diff-checkbox")
input.inline-diff-checkbox(type="checkbox" value="")
| Inline diff
div.monaco-placeholder#history-diff
.modal-footer
button.btn.btn-light(type="button" data-dismiss="modal" aria-label="Close") Close
#library-selection.modal.fade.gl_keep(tabindex="-1" role="dialog")
.modal-dialog.modal-lg
.modal-content
.modal-header
h5.modal-title Libraries
button.close(type="button" data-dismiss="modal" aria-hidden="true" aria-label="Close")
span(aria-hidden="true")
| ×
.modal-body
.card
.card-body
.container
.row
.col-lg
div(style='text-align: center')
input.lib-search-input(value="" placeholder="Search text")
button.btn.btn-primary.lib-search-button(type="button") Search
.row
.col-lg.libs-how-to-use To add a library, search for one you want and select the version in the dropdown. Or if you have favorited it before, just click the library name in the Favorites section.
.row
.col-lg
.row
.libs-selected-col.col-md
div
h6 Selected
.libs-selected-items
.libs-results-col.col-md
h6 Results
.lib-results-items
.libs-favorites-col.col-md
h6 Favorites
.lib-favorites
| {
"pile_set_name": "Github"
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twitter.distributedlog.service;
import com.google.common.base.Optional;
import com.twitter.util.Future;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Implement handling for an unrecoverable error.
*/
public interface FatalErrorHandler {
/**
* This method is invoked when an unrecoverable error has occurred
* and no progress can be made. It should implement a shutdown routine.
*/
void notifyFatalError();
} | {
"pile_set_name": "Github"
} |
The steps to get this Core project working are:
1. Create a ViewModels folder and add a ViewModel:
public class FirstViewModel : Cirrious.MvvmCross.ViewModels.MvxViewModel
{
public string Hello { get { return "Hello MvvmCross"; } }
}
2. Add an App.cs class - in it place the code to start the app with the FirstViewModel:
public class App : Cirrious.MvvmCross.ViewModels.MvxApplication
{
public override void Initialize()
{
CreatableTypes()
.EndingWith("Service")
.AsInterfaces()
.RegisterAsLazySingleton();
RegisterAppStart<ViewModels.FirstViewModel>();
}
}
| {
"pile_set_name": "Github"
} |
// Decompiled by Jad v1.5.8f. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: Program.java
package acm.program;
import java.awt.*;
import java.awt.event.ComponentEvent;
// Referenced classes of package acm.program:
// Program
class ProgramContentPaneLayout extends BorderLayout
{
public ProgramContentPaneLayout(Program program)
{
myProgram = program;
}
public void layoutContainer(Container container)
{
super.layoutContainer(container);
if(!myProgram.isAncestorOf(container))
{
Dimension dimension = container.getSize();
Insets insets = container.getInsets();
int i = insets.left;
int j = insets.top;
int k = dimension.width - insets.left - insets.right;
int l = dimension.height - insets.top - insets.bottom;
myProgram.setBounds(i, j, k, l);
ComponentEvent componentevent = new ComponentEvent(myProgram, 101);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(componentevent);
}
}
private Program myProgram;
}
| {
"pile_set_name": "Github"
} |
Open J
======
Not actively maintained
-----------------------
OpenJ is not very actively maintained. Please see: http://www.jsoftware.com/source.htm and https://github.com/iocane/unbox for alternatives.
About
-----
From [jsoftware.com] [jsw]
> J is a modern, high-level, general-purpose, high-performance
> programming language. J is portable and runs on Windows,
> Unix, Mac, and PocketPC handhelds, both as a GUI and in a
> console. True 64-bit J systems are available for XP64 or
> Linux64, on AMD64 or Intel EM64T platforms. J systems can be
> installed and distributed for free.
[jsw]: http://jsoftware.com/ "JSoftware"
J goes GNU
----------
> Date: Sun, 6 Mar 2011 11:12:31 -0500
> From: Eric Iverson <[email protected]>
> To: Programming forum <[email protected]>
> Subject: [Jprogramming] J Source under GPL
>
> J Source is now available under GPL version 3.
>
> If interested you will probably want to join the new source forum.
>
> See the Source page at the web site for info on getting the source.
>
> J Source discussions should take place in the source forum.
> ----------------------------------------------------------------------
> For information about J forums see
> http://www.jsoftware.com/forums.htm
| {
"pile_set_name": "Github"
} |
Object.defineProperty (module.exports, "__esModule", { value: true });
module.exports.Context3DCompareMode = module.exports.default = {
ALWAYS: "always",
EQUAL: "equal",
GREATER: "greater",
GREATER_EQUAL: "greaterEqual",
LESS: "less",
LESS_EQUAL: "lessEqual",
NEVER: "never",
NOT_EQUAL: "notEqual"
}; | {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright 2017 Bstek
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package com.bstek.ureport.expression.model.expr;
import java.util.ArrayList;
import java.util.List;
import com.bstek.ureport.build.Context;
import com.bstek.ureport.expression.model.Condition;
import com.bstek.ureport.expression.model.Expression;
import com.bstek.ureport.expression.model.data.ExpressionData;
import com.bstek.ureport.model.Cell;
/**
* @author Jacky.gao
* @since 2016年11月18日
*/
public abstract class BaseExpression implements Expression{
private static final long serialVersionUID = 3853234856946931008L;
protected String expr;
@Override
public final ExpressionData<?> execute(Cell cell,Cell currentCell, Context context) {
ExpressionData<?> data=compute(cell,currentCell,context);
return data;
}
protected abstract ExpressionData<?> compute(Cell cell,Cell currentCell, Context context);
protected List<Cell> filterCells(Cell cell,Context context,Condition condition,List<Cell> targetCells) {
if(condition==null){
return targetCells;
}
List<Cell> list=new ArrayList<Cell>();
for(Cell targetCell:targetCells){
boolean conditionResult=true;
List<Object> dataList=targetCell.getBindData();
if(dataList==null){
conditionResult=false;
}else{
for(Object obj:dataList){
boolean result=condition.filter(cell,targetCell, obj, context);
if(!result){
conditionResult=false;
break;
}
}
}
if(!conditionResult){
continue;
}
list.add(targetCell);
}
return list;
}
public void setExpr(String expr) {
this.expr = expr;
}
public String getExpr() {
return expr;
}
}
| {
"pile_set_name": "Github"
} |
#include <assert.h>
#include <pb_decode.h>
#include <string.h>
#include <stdio.h>
#include "test_helpers.h"
#include "anytest.pb.h"
#include "google/protobuf/duration.pb.h"
int main()
{
BaseMessage msg = BaseMessage_init_zero;
uint8_t buffer[256];
pb_istream_t stream;
size_t count;
bool status;
/* Read the data into buffer */
SET_BINARY_MODE(stdin);
count = fread(buffer, 1, sizeof(buffer), stdin);
stream = pb_istream_from_buffer(buffer, count);
/* Decode the base message */
if (!pb_decode(&stream, BaseMessage_fields, &msg))
{
printf("Parsing failed: %s\n", PB_GET_ERROR(&stream));
return 1;
}
assert(msg.start == 1234);
assert(msg.end == 5678);
/* Decode the Any message if we know the type */
if (strcmp(msg.details.type_url, "type.googleapis.com/google.protobuf.Duration") == 0)
{
google_protobuf_Duration duration = google_protobuf_Duration_init_zero;
stream = pb_istream_from_buffer(msg.details.value.bytes, msg.details.value.size);
status = pb_decode(&stream, google_protobuf_Duration_fields, &duration);
assert(status);
assert(duration.seconds == 99999);
assert(duration.nanos == 100);
return 0;
}
else
{
fprintf(stderr, "Unknown Any type\n");
return 2;
}
}
| {
"pile_set_name": "Github"
} |
'use strict'
module.exports = writeFile
module.exports.sync = writeFileSync
module.exports._getTmpname = getTmpname // for testing
module.exports._cleanupOnExit = cleanupOnExit
var fs = require('graceful-fs')
var MurmurHash3 = require('imurmurhash')
var onExit = require('signal-exit')
var path = require('path')
var activeFiles = {}
// if we run inside of a worker_thread, `process.pid` is not unique
/* istanbul ignore next */
var threadId = (function getId () {
try {
var workerThreads = require('worker_threads')
/// if we are in main thread, this is set to `0`
return workerThreads.threadId
} catch (e) {
// worker_threads are not available, fallback to 0
return 0
}
})()
var invocations = 0
function getTmpname (filename) {
return filename + '.' +
MurmurHash3(__filename)
.hash(String(process.pid))
.hash(String(threadId))
.hash(String(++invocations))
.result()
}
function cleanupOnExit (tmpfile) {
return function () {
try {
fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile)
} catch (_) {}
}
}
function writeFile (filename, data, options, callback) {
if (options) {
if (options instanceof Function) {
callback = options
options = {}
} else if (typeof options === 'string') {
options = { encoding: options }
}
} else {
options = {}
}
var Promise = options.Promise || global.Promise
var truename
var fd
var tmpfile
/* istanbul ignore next -- The closure only gets called when onExit triggers */
var removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile))
var absoluteName = path.resolve(filename)
new Promise(function serializeSameFile (resolve) {
// make a queue if it doesn't already exist
if (!activeFiles[absoluteName]) activeFiles[absoluteName] = []
activeFiles[absoluteName].push(resolve) // add this job to the queue
if (activeFiles[absoluteName].length === 1) resolve() // kick off the first one
}).then(function getRealPath () {
return new Promise(function (resolve) {
fs.realpath(filename, function (_, realname) {
truename = realname || filename
tmpfile = getTmpname(truename)
resolve()
})
})
}).then(function stat () {
return new Promise(function stat (resolve) {
if (options.mode && options.chown) resolve()
else {
// Either mode or chown is not explicitly set
// Default behavior is to copy it from original file
fs.stat(truename, function (err, stats) {
if (err || !stats) resolve()
else {
options = Object.assign({}, options)
if (options.mode == null) {
options.mode = stats.mode
}
if (options.chown == null && process.getuid) {
options.chown = { uid: stats.uid, gid: stats.gid }
}
resolve()
}
})
}
})
}).then(function thenWriteFile () {
return new Promise(function (resolve, reject) {
fs.open(tmpfile, 'w', options.mode, function (err, _fd) {
fd = _fd
if (err) reject(err)
else resolve()
})
})
}).then(function write () {
return new Promise(function (resolve, reject) {
if (Buffer.isBuffer(data)) {
fs.write(fd, data, 0, data.length, 0, function (err) {
if (err) reject(err)
else resolve()
})
} else if (data != null) {
fs.write(fd, String(data), 0, String(options.encoding || 'utf8'), function (err) {
if (err) reject(err)
else resolve()
})
} else resolve()
})
}).then(function syncAndClose () {
return new Promise(function (resolve, reject) {
if (options.fsync !== false) {
fs.fsync(fd, function (err) {
if (err) fs.close(fd, () => reject(err))
else fs.close(fd, resolve)
})
} else {
fs.close(fd, resolve)
}
})
}).then(function chown () {
fd = null
if (options.chown) {
return new Promise(function (resolve, reject) {
fs.chown(tmpfile, options.chown.uid, options.chown.gid, function (err) {
if (err) reject(err)
else resolve()
})
})
}
}).then(function chmod () {
if (options.mode) {
return new Promise(function (resolve, reject) {
fs.chmod(tmpfile, options.mode, function (err) {
if (err) reject(err)
else resolve()
})
})
}
}).then(function rename () {
return new Promise(function (resolve, reject) {
fs.rename(tmpfile, truename, function (err) {
if (err) reject(err)
else resolve()
})
})
}).then(function success () {
removeOnExitHandler()
callback()
}, function fail (err) {
return new Promise(resolve => {
return fd ? fs.close(fd, resolve) : resolve()
}).then(() => {
removeOnExitHandler()
fs.unlink(tmpfile, function () {
callback(err)
})
})
}).then(function checkQueue () {
activeFiles[absoluteName].shift() // remove the element added by serializeSameFile
if (activeFiles[absoluteName].length > 0) {
activeFiles[absoluteName][0]() // start next job if one is pending
} else delete activeFiles[absoluteName]
})
}
function writeFileSync (filename, data, options) {
if (typeof options === 'string') options = { encoding: options }
else if (!options) options = {}
try {
filename = fs.realpathSync(filename)
} catch (ex) {
// it's ok, it'll happen on a not yet existing file
}
var tmpfile = getTmpname(filename)
if (!options.mode || !options.chown) {
// Either mode or chown is not explicitly set
// Default behavior is to copy it from original file
try {
var stats = fs.statSync(filename)
options = Object.assign({}, options)
if (!options.mode) {
options.mode = stats.mode
}
if (!options.chown && process.getuid) {
options.chown = { uid: stats.uid, gid: stats.gid }
}
} catch (ex) {
// ignore stat errors
}
}
var fd
var cleanup = cleanupOnExit(tmpfile)
var removeOnExitHandler = onExit(cleanup)
try {
fd = fs.openSync(tmpfile, 'w', options.mode)
if (Buffer.isBuffer(data)) {
fs.writeSync(fd, data, 0, data.length, 0)
} else if (data != null) {
fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8'))
}
if (options.fsync !== false) {
fs.fsyncSync(fd)
}
fs.closeSync(fd)
if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid)
if (options.mode) fs.chmodSync(tmpfile, options.mode)
fs.renameSync(tmpfile, filename)
removeOnExitHandler()
} catch (err) {
if (fd) {
try {
fs.closeSync(fd)
} catch (ex) {
// ignore close errors at this stage, error may have closed fd already.
}
}
removeOnExitHandler()
cleanup()
throw err
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package field
import (
"fmt"
"strings"
"testing"
)
func TestMakeFuncs(t *testing.T) {
testCases := []struct {
fn func() *Error
expected ErrorType
}{
{
func() *Error { return Invalid(NewPath("f"), "v", "d") },
ErrorTypeInvalid,
},
{
func() *Error { return NotSupported(NewPath("f"), "v", nil) },
ErrorTypeNotSupported,
},
{
func() *Error { return Duplicate(NewPath("f"), "v") },
ErrorTypeDuplicate,
},
{
func() *Error { return NotFound(NewPath("f"), "v") },
ErrorTypeNotFound,
},
{
func() *Error { return Required(NewPath("f"), "d") },
ErrorTypeRequired,
},
{
func() *Error { return InternalError(NewPath("f"), fmt.Errorf("e")) },
ErrorTypeInternal,
},
}
for _, testCase := range testCases {
err := testCase.fn()
if err.Type != testCase.expected {
t.Errorf("expected Type %q, got %q", testCase.expected, err.Type)
}
}
}
func TestErrorUsefulMessage(t *testing.T) {
{
s := Invalid(nil, nil, "").Error()
t.Logf("message: %v", s)
if !strings.Contains(s, "null") {
t.Errorf("error message did not contain 'null': %s", s)
}
}
s := Invalid(NewPath("foo"), "bar", "deet").Error()
t.Logf("message: %v", s)
for _, part := range []string{"foo", "bar", "deet", ErrorTypeInvalid.String()} {
if !strings.Contains(s, part) {
t.Errorf("error message did not contain expected part '%v'", part)
}
}
type complicated struct {
Baz int
Qux string
Inner interface{}
KV map[string]int
}
s = Invalid(
NewPath("foo"),
&complicated{
Baz: 1,
Qux: "aoeu",
Inner: &complicated{Qux: "asdf"},
KV: map[string]int{"Billy": 2},
},
"detail",
).Error()
t.Logf("message: %v", s)
for _, part := range []string{
"foo", ErrorTypeInvalid.String(),
"Baz", "Qux", "Inner", "KV", "detail",
"1", "aoeu", "Billy", "2",
// "asdf", TODO: reenable once we have a better nested printer
} {
if !strings.Contains(s, part) {
t.Errorf("error message did not contain expected part '%v'", part)
}
}
}
func TestToAggregate(t *testing.T) {
testCases := struct {
ErrList []ErrorList
NumExpectedErrs []int
}{
[]ErrorList{
nil,
{},
{Invalid(NewPath("f"), "v", "d")},
{Invalid(NewPath("f"), "v", "d"), Invalid(NewPath("f"), "v", "d")},
{Invalid(NewPath("f"), "v", "d"), InternalError(NewPath(""), fmt.Errorf("e"))},
},
[]int{
0,
0,
1,
1,
2,
},
}
if len(testCases.ErrList) != len(testCases.NumExpectedErrs) {
t.Errorf("Mismatch: length of NumExpectedErrs does not match length of ErrList")
}
for i, tc := range testCases.ErrList {
agg := tc.ToAggregate()
numErrs := 0
if agg != nil {
numErrs = len(agg.Errors())
}
if numErrs != testCases.NumExpectedErrs[i] {
t.Errorf("[%d] Expected %d, got %d", i, testCases.NumExpectedErrs[i], numErrs)
}
if len(tc) == 0 {
if agg != nil {
t.Errorf("[%d] Expected nil, got %#v", i, agg)
}
} else if agg == nil {
t.Errorf("[%d] Expected non-nil", i)
}
}
}
func TestErrListFilter(t *testing.T) {
list := ErrorList{
Invalid(NewPath("test.field"), "", ""),
Invalid(NewPath("field.test"), "", ""),
Duplicate(NewPath("test"), "value"),
}
if len(list.Filter(NewErrorTypeMatcher(ErrorTypeDuplicate))) != 2 {
t.Errorf("should not filter")
}
if len(list.Filter(NewErrorTypeMatcher(ErrorTypeInvalid))) != 1 {
t.Errorf("should filter")
}
}
func TestNotSupported(t *testing.T) {
notSupported := NotSupported(NewPath("f"), "v", []string{"a", "b", "c"})
expected := `Unsupported value: "v": supported values: "a", "b", "c"`
if notSupported.ErrorBody() != expected {
t.Errorf("Expected: %s\n, but got: %s\n", expected, notSupported.ErrorBody())
}
}
| {
"pile_set_name": "Github"
} |
package com.dslplatform.json.generated.ocd.javaasserts;
import org.junit.Assert;
public class MoneyAsserts {
static void assertSingleEquals(final String message, final java.math.BigDecimal expected, final java.math.BigDecimal actual) {
try {
expected.setScale(2);
}
catch (final ArithmeticException e) {
Assert.fail(message + "expected was a DecimalWithScaleOf9, but its scale was " + expected.scale() + " - WARNING: This is a preconditions failure in expected, this assertion will never succeed!");
}
try {
expected.setScale(2);
}
catch (final ArithmeticException e) {
Assert.fail(message + "actual was a DecimalWithScaleOf9, but its scale was " + actual.scale());
}
if (expected == actual || expected.compareTo(actual) == 0) return;
Assert.fail(message + "expected was \"" + expected + "\", but actual was \"" + actual + "\"");
}
static void assertOneEquals(final String message, final java.math.BigDecimal expected, final java.math.BigDecimal actual) {
if (expected == null) Assert.fail(message + "expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!");
if (expected == actual) return;
if (actual == null) Assert.fail(message + "expected was \"" + expected + "\", but actual was <null>");
assertSingleEquals(message, expected, actual);
}
public static void assertOneEquals(final java.math.BigDecimal expected, final java.math.BigDecimal actual) {
assertOneEquals("OneMoney mismatch: ", expected, actual);
}
private static void assertNullableEquals(final String message, final java.math.BigDecimal expected, final java.math.BigDecimal actual) {
if (expected == actual) return;
if (expected == null) Assert.fail(message + "expected was <null>, but actual was \"" + actual + "\"");
if (actual == null) Assert.fail(message + "expected was \"" + expected + "\", but actual was <null>");
assertSingleEquals(message, expected, actual);
}
public static void assertNullableEquals(final java.math.BigDecimal expected, final java.math.BigDecimal actual) {
assertNullableEquals("NullableMoney mismatch: ", expected, actual);
}
private static void assertArrayOfOneEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) {
if (expecteds.length != actuals.length) {
Assert.fail(message + "expecteds was an array of length " + expecteds.length + ", but actuals was an array of length " + actuals.length);
}
for (int i = 0; i < expecteds.length; i++) {
assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expecteds[i], actuals[i]);
}
}
private static void assertOneArrayOfOneEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) {
if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!");
for (int i = 0; i < expecteds.length; i ++) {
if (expecteds[i] == null) {
Assert.fail(message + "expecteds contained a <null> element at index " + i + " - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!");
}
}
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was an array of length " + expecteds.length + ", but actuals was <null>");
assertArrayOfOneEquals(message, expecteds, actuals);
}
public static void assertOneArrayOfOneEquals(final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) {
assertOneArrayOfOneEquals("OneArrayOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableArrayOfOneEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was an array of length " + actuals.length);
if (actuals == null) Assert.fail(message + " expecteds was an array of length " + expecteds.length + ", but actuals was <null>");
assertArrayOfOneEquals(message, expecteds, actuals);
}
public static void assertNullableArrayOfOneEquals(final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) {
assertNullableArrayOfOneEquals("NullableArrayOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertArrayOfNullableEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) {
if (expecteds.length != actuals.length) {
Assert.fail(message + "expecteds was an array of length " + expecteds.length + ", but actuals was an array of length " + actuals.length);
}
for (int i = 0; i < expecteds.length; i++) {
assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expecteds[i], actuals[i]);
}
}
private static void assertOneArrayOfNullableEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) {
if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!");
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was an array of length " + expecteds.length + ", but actuals was <null>");
assertArrayOfNullableEquals(message, expecteds, actuals);
}
public static void assertOneArrayOfNullableEquals(final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) {
assertOneArrayOfNullableEquals("OneArrayOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableArrayOfNullableEquals(final String message, final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was an array of length " + actuals.length);
if (actuals == null) Assert.fail(message + " expecteds was an array of length " + expecteds.length + ", but actuals was <null>");
assertArrayOfNullableEquals(message, expecteds, actuals);
}
public static void assertNullableArrayOfNullableEquals(final java.math.BigDecimal[] expecteds, final java.math.BigDecimal[] actuals) {
assertNullableArrayOfNullableEquals("NullableArrayOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertListOfOneEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) {
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a list of size " + expectedsSize + ", but actuals was a list of size " + actualsSize);
}
final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator();
final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator();
for (int i = 0; i < expectedsSize; i++) {
final java.math.BigDecimal expected = expectedsIterator.next();
final java.math.BigDecimal actual = actualsIterator.next();
assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual);
}
}
private static void assertOneListOfOneEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) {
int i = 0;
for (final java.math.BigDecimal expected : expecteds) {
if (expected == null) {
Assert.fail(message + "element mismatch occurred at index " + i + ": expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!");
}
i++;
}
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a list of size " + expecteds.size() + ", but actuals was <null>");
assertListOfOneEquals(message, expecteds, actuals);
}
public static void assertOneListOfOneEquals(final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) {
assertOneListOfOneEquals("OneListOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableListOfOneEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a list of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a list of size " + expecteds.size() + ", but actuals was <null>");
assertListOfOneEquals(message, expecteds, actuals);
}
public static void assertNullableListOfOneEquals(final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) {
assertNullableListOfOneEquals("NullableListOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertListOfNullableEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) {
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a list of size " + expectedsSize + ", but actuals was a list of size " + actualsSize);
}
final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator();
final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator();
for (int i = 0; i < expectedsSize; i++) {
final java.math.BigDecimal expected = expectedsIterator.next();
final java.math.BigDecimal actual = actualsIterator.next();
assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual);
}
}
private static void assertOneListOfNullableEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) {
if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!");
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a list of size " + expecteds.size() + ", but actuals was <null>");
assertListOfNullableEquals(message, expecteds, actuals);
}
public static void assertOneListOfNullableEquals(final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) {
assertOneListOfNullableEquals("OneListOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableListOfNullableEquals(final String message, final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a list of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a list of size " + expecteds.size() + ", but actuals was <null>");
assertListOfNullableEquals(message, expecteds, actuals);
}
public static void assertNullableListOfNullableEquals(final java.util.List<java.math.BigDecimal> expecteds, final java.util.List<java.math.BigDecimal> actuals) {
assertNullableListOfNullableEquals("NullableListOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertSetOfOneEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) {
if (actuals.contains(null)) {
Assert.fail(message + "actuals contained a <null> element");
}
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a set of size " + expectedsSize + ", but actuals was a set of size " + actualsSize);
}
expectedsLoop: for (final java.math.BigDecimal expected : expecteds) {
if (actuals.contains(expected)) continue;
for (final java.math.BigDecimal actual : actuals) {
try {
assertOneEquals(expected, actual);
continue expectedsLoop;
}
catch (final AssertionError e) {}
}
Assert.fail(message + "actuals did not contain the expecteds element \"" + expected + "\"");
}
}
private static void assertOneSetOfOneEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) {
if (expecteds.contains(null)) {
Assert.fail(message + "expecteds contained a <null> element - WARNING: This is a preconditions failure in expected, this assertion will never succeed!");
}
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a set of size " + expecteds.size() + ", but actuals was <null>");
assertSetOfOneEquals(message, expecteds, actuals);
}
public static void assertOneSetOfOneEquals(final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) {
assertOneSetOfOneEquals("OneSetOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableSetOfOneEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a set of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a set of size " + expecteds.size() + ", but actuals was <null>");
assertSetOfOneEquals(message, expecteds, actuals);
}
public static void assertNullableSetOfOneEquals(final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) {
assertNullableSetOfOneEquals("NullableSetOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertSetOfNullableEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) {
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a set of size " + expectedsSize + ", but actuals was a set of size " + actualsSize);
}
expectedsLoop: for (final java.math.BigDecimal expected : expecteds) {
if (actuals.contains(expected)) continue;
for (final java.math.BigDecimal actual : actuals) {
try {
assertNullableEquals(expected, actual);
continue expectedsLoop;
}
catch (final AssertionError e) {}
}
Assert.fail(message + "actuals did not contain the expecteds element \"" + expected + "\"");
}
}
private static void assertOneSetOfNullableEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) {
if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!");
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a set of size " + expecteds.size() + ", but actuals was <null>");
assertSetOfNullableEquals(message, expecteds, actuals);
}
public static void assertOneSetOfNullableEquals(final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) {
assertOneSetOfNullableEquals("OneSetOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableSetOfNullableEquals(final String message, final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a set of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a set of size " + expecteds.size() + ", but actuals was <null>");
assertSetOfNullableEquals(message, expecteds, actuals);
}
public static void assertNullableSetOfNullableEquals(final java.util.Set<java.math.BigDecimal> expecteds, final java.util.Set<java.math.BigDecimal> actuals) {
assertNullableSetOfNullableEquals("NullableSetOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertQueueOfOneEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) {
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a queue of size " + expectedsSize + ", but actuals was a queue of size " + actualsSize);
}
final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator();
final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator();
for (int i = 0; i < expectedsSize; i++) {
final java.math.BigDecimal expected = expectedsIterator.next();
final java.math.BigDecimal actual = actualsIterator.next();
assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual);
}
}
private static void assertOneQueueOfOneEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) {
int i = 0;
for (final java.math.BigDecimal expected : expecteds) {
if (expected == null) {
Assert.fail(message + "element mismatch occurred at index " + i + ": expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!");
}
i++;
}
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a queue of size " + expecteds.size() + ", but actuals was <null>");
assertQueueOfOneEquals(message, expecteds, actuals);
}
public static void assertOneQueueOfOneEquals(final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) {
assertOneQueueOfOneEquals("OneQueueOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableQueueOfOneEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a queue of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a queue of size " + expecteds.size() + ", but actuals was <null>");
assertQueueOfOneEquals(message, expecteds, actuals);
}
public static void assertNullableQueueOfOneEquals(final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) {
assertNullableQueueOfOneEquals("NullableQueueOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertQueueOfNullableEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) {
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a queue of size " + expectedsSize + ", but actuals was a queue of size " + actualsSize);
}
final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator();
final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator();
for (int i = 0; i < expectedsSize; i++) {
final java.math.BigDecimal expected = expectedsIterator.next();
final java.math.BigDecimal actual = actualsIterator.next();
assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual);
}
}
private static void assertOneQueueOfNullableEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) {
if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!");
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a queue of size " + expecteds.size() + ", but actuals was <null>");
assertQueueOfNullableEquals(message, expecteds, actuals);
}
public static void assertOneQueueOfNullableEquals(final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) {
assertOneQueueOfNullableEquals("OneQueueOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableQueueOfNullableEquals(final String message, final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a queue of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a queue of size " + expecteds.size() + ", but actuals was <null>");
assertQueueOfNullableEquals(message, expecteds, actuals);
}
public static void assertNullableQueueOfNullableEquals(final java.util.Queue<java.math.BigDecimal> expecteds, final java.util.Queue<java.math.BigDecimal> actuals) {
assertNullableQueueOfNullableEquals("NullableQueueOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertLinkedListOfOneEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) {
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a linked list of size " + expectedsSize + ", but actuals was a linked list of size " + actualsSize);
}
final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator();
final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator();
for (int i = 0; i < expectedsSize; i++) {
final java.math.BigDecimal expected = expectedsIterator.next();
final java.math.BigDecimal actual = actualsIterator.next();
assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual);
}
}
private static void assertOneLinkedListOfOneEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) {
int i = 0;
for (final java.math.BigDecimal expected : expecteds) {
if (expected == null) {
Assert.fail(message + "element mismatch occurred at index " + i + ": expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!");
}
i++;
}
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a linked list of size " + expecteds.size() + ", but actuals was <null>");
assertLinkedListOfOneEquals(message, expecteds, actuals);
}
public static void assertOneLinkedListOfOneEquals(final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) {
assertOneLinkedListOfOneEquals("OneLinkedListOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableLinkedListOfOneEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a linked list of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a linked list of size " + expecteds.size() + ", but actuals was <null>");
assertLinkedListOfOneEquals(message, expecteds, actuals);
}
public static void assertNullableLinkedListOfOneEquals(final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) {
assertNullableLinkedListOfOneEquals("NullableLinkedListOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertLinkedListOfNullableEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) {
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a linked list of size " + expectedsSize + ", but actuals was a linked list of size " + actualsSize);
}
final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator();
final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator();
for (int i = 0; i < expectedsSize; i++) {
final java.math.BigDecimal expected = expectedsIterator.next();
final java.math.BigDecimal actual = actualsIterator.next();
assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual);
}
}
private static void assertOneLinkedListOfNullableEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) {
if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!");
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a linked list of size " + expecteds.size() + ", but actuals was <null>");
assertLinkedListOfNullableEquals(message, expecteds, actuals);
}
public static void assertOneLinkedListOfNullableEquals(final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) {
assertOneLinkedListOfNullableEquals("OneLinkedListOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableLinkedListOfNullableEquals(final String message, final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a linked list of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a linked list of size " + expecteds.size() + ", but actuals was <null>");
assertLinkedListOfNullableEquals(message, expecteds, actuals);
}
public static void assertNullableLinkedListOfNullableEquals(final java.util.LinkedList<java.math.BigDecimal> expecteds, final java.util.LinkedList<java.math.BigDecimal> actuals) {
assertNullableLinkedListOfNullableEquals("NullableLinkedListOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertStackOfOneEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) {
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a stack of size " + expectedsSize + ", but actuals was a stack of size " + actualsSize);
}
final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator();
final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator();
for (int i = 0; i < expectedsSize; i++) {
final java.math.BigDecimal expected = expectedsIterator.next();
final java.math.BigDecimal actual = actualsIterator.next();
assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual);
}
}
private static void assertOneStackOfOneEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) {
int i = 0;
for (final java.math.BigDecimal expected : expecteds) {
if (expected == null) {
Assert.fail(message + "element mismatch occurred at index " + i + ": expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!");
}
i++;
}
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a stack of size " + expecteds.size() + ", but actuals was <null>");
assertStackOfOneEquals(message, expecteds, actuals);
}
public static void assertOneStackOfOneEquals(final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) {
assertOneStackOfOneEquals("OneStackOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableStackOfOneEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a stack of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a stack of size " + expecteds.size() + ", but actuals was <null>");
assertStackOfOneEquals(message, expecteds, actuals);
}
public static void assertNullableStackOfOneEquals(final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) {
assertNullableStackOfOneEquals("NullableStackOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertStackOfNullableEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) {
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a stack of size " + expectedsSize + ", but actuals was a stack of size " + actualsSize);
}
final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator();
final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator();
for (int i = 0; i < expectedsSize; i++) {
final java.math.BigDecimal expected = expectedsIterator.next();
final java.math.BigDecimal actual = actualsIterator.next();
assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual);
}
}
private static void assertOneStackOfNullableEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) {
if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!");
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a stack of size " + expecteds.size() + ", but actuals was <null>");
assertStackOfNullableEquals(message, expecteds, actuals);
}
public static void assertOneStackOfNullableEquals(final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) {
assertOneStackOfNullableEquals("OneStackOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableStackOfNullableEquals(final String message, final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a stack of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a stack of size " + expecteds.size() + ", but actuals was <null>");
assertStackOfNullableEquals(message, expecteds, actuals);
}
public static void assertNullableStackOfNullableEquals(final java.util.Stack<java.math.BigDecimal> expecteds, final java.util.Stack<java.math.BigDecimal> actuals) {
assertNullableStackOfNullableEquals("NullableStackOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertVectorOfOneEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) {
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a vector of size " + expectedsSize + ", but actuals was a vector of size " + actualsSize);
}
final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator();
final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator();
for (int i = 0; i < expectedsSize; i++) {
final java.math.BigDecimal expected = expectedsIterator.next();
final java.math.BigDecimal actual = actualsIterator.next();
assertOneEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual);
}
}
private static void assertOneVectorOfOneEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) {
int i = 0;
for (final java.math.BigDecimal expected : expecteds) {
if (expected == null) {
Assert.fail(message + "element mismatch occurred at index " + i + ": expected was <null> - WARNING: This is a preconditions failure in expected, this assertion will never succeed!");
}
i++;
}
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a vector of size " + expecteds.size() + ", but actuals was <null>");
assertVectorOfOneEquals(message, expecteds, actuals);
}
public static void assertOneVectorOfOneEquals(final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) {
assertOneVectorOfOneEquals("OneVectorOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableVectorOfOneEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a vector of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a vector of size " + expecteds.size() + ", but actuals was <null>");
assertVectorOfOneEquals(message, expecteds, actuals);
}
public static void assertNullableVectorOfOneEquals(final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) {
assertNullableVectorOfOneEquals("NullableVectorOfOneMoney mismatch: ", expecteds, actuals);
}
private static void assertVectorOfNullableEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) {
final int expectedsSize = expecteds.size();
final int actualsSize = actuals.size();
if (expectedsSize != actualsSize) {
Assert.fail(message + "expecteds was a vector of size " + expectedsSize + ", but actuals was a vector of size " + actualsSize);
}
final java.util.Iterator<java.math.BigDecimal> expectedsIterator = expecteds.iterator();
final java.util.Iterator<java.math.BigDecimal> actualsIterator = actuals.iterator();
for (int i = 0; i < expectedsSize; i++) {
final java.math.BigDecimal expected = expectedsIterator.next();
final java.math.BigDecimal actual = actualsIterator.next();
assertNullableEquals(message + "element mismatch occurred at index " + i + ": ", expected, actual);
}
}
private static void assertOneVectorOfNullableEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) {
if (expecteds == null) Assert.fail(message + "expecteds was <null> - WARNING: This is a preconditions failure in expecteds, this assertion will never succeed!");
if (expecteds == actuals) return;
if (actuals == null) Assert.fail(message + "expecteds was a vector of size " + expecteds.size() + ", but actuals was <null>");
assertVectorOfNullableEquals(message, expecteds, actuals);
}
public static void assertOneVectorOfNullableEquals(final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) {
assertOneVectorOfNullableEquals("OneVectorOfNullableMoney mismatch: ", expecteds, actuals);
}
private static void assertNullableVectorOfNullableEquals(final String message, final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) {
if (expecteds == actuals) return;
if (expecteds == null) Assert.fail(message + "expecteds was <null>, but actuals was a vector of size " + actuals.size());
if (actuals == null) Assert.fail(message + " expecteds was a vector of size " + expecteds.size() + ", but actuals was <null>");
assertVectorOfNullableEquals(message, expecteds, actuals);
}
public static void assertNullableVectorOfNullableEquals(final java.util.Vector<java.math.BigDecimal> expecteds, final java.util.Vector<java.math.BigDecimal> actuals) {
assertNullableVectorOfNullableEquals("NullableVectorOfNullableMoney mismatch: ", expecteds, actuals);
}
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the Dektrium project
*
* (c) Dektrium project <http://github.com/dektrium>
*
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/
namespace dektrium\user\clients;
use yii\authclient\clients\Twitter as BaseTwitter;
use yii\helpers\ArrayHelper;
/**
* @author Dmitry Erofeev <[email protected]>
*/
class Twitter extends BaseTwitter implements ClientInterface
{
/**
* @return string
*/
public function getUsername()
{
return ArrayHelper::getValue($this->getUserAttributes(), 'screen_name');
}
/**
* @return string|null User's email, Twitter does not provide user's email address
* unless elevated permissions have been granted
* https://dev.twitter.com/rest/reference/get/account/verify_credentials
*/
public function getEmail()
{
return ArrayHelper::getValue($this->getUserAttributes(), 'email');
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 5bedcafb25855d84394b9b7eb5869bc4
timeCreated: 1465480747
licenseType: Pro
ModelImporter:
serializedVersion: 19
fileIDToRecycleName:
100000: Controls
100002: //RootNode
100004: Eyes
100006: Head
100008: HeadEnd
100010: LeftArm
100012: LeftEar
100014: LeftEarEnd
100016: LeftFoot
100018: LeftFootEnd
100020: LeftHand
100022: LeftHandEnd
100024: LeftHip
100026: LeftLeg1
100028: LeftLeg2
100030: LeftLeg3
100032: LeftShoulder
100034: LeftUpperArm
100036: Mouth
100038: MouthEnd
100040: Neck
100042: Pelvis
100044: RightArm
100046: RightEar
100048: RightEarEnd
100050: RightFoot
100052: RightFootEnd
100054: RightHand
100056: RightHandEnd
100058: RightHip
100060: RightLeg1
100062: RightLeg2
100064: RightLeg3
100066: RightShoulder
100068: RightUpperArm
100070: Skeleton
100072: Spine
100074: Tail1
100076: Tail2
100078: Tail3
100080: Tail3 1
400000: Controls
400002: //RootNode
400004: Eyes
400006: Head
400008: HeadEnd
400010: LeftArm
400012: LeftEar
400014: LeftEarEnd
400016: LeftFoot
400018: LeftFootEnd
400020: LeftHand
400022: LeftHandEnd
400024: LeftHip
400026: LeftLeg1
400028: LeftLeg2
400030: LeftLeg3
400032: LeftShoulder
400034: LeftUpperArm
400036: Mouth
400038: MouthEnd
400040: Neck
400042: Pelvis
400044: RightArm
400046: RightEar
400048: RightEarEnd
400050: RightFoot
400052: RightFootEnd
400054: RightHand
400056: RightHandEnd
400058: RightHip
400060: RightLeg1
400062: RightLeg2
400064: RightLeg3
400066: RightShoulder
400068: RightUpperArm
400070: Skeleton
400072: Spine
400074: Tail1
400076: Tail2
400078: Tail3
400080: Tail3 1
7400000: Dog_Death
9500000: //RootNode
materials:
importMaterials: 1
materialName: 0
materialSearch: 1
animations:
legacyGenerateAnimations: 4
bakeSimulation: 0
resampleCurves: 1
optimizeGameObjects: 0
motionNodeName:
animationImportErrors:
animationImportWarnings:
animationRetargetingWarnings:
animationDoRetargetingWarnings: 0
animationCompression: 1
animationRotationError: 0.5
animationPositionError: 0.5
animationScaleError: 0.5
animationWrapMode: 0
extraExposedTransformPaths: []
clipAnimations:
- serializedVersion: 16
name: Dog_Death
takeName: Take 001
firstFrame: 0
lastFrame: 18
wrapMode: 0
orientationOffsetY: 0
level: 0
cycleOffset: 0
loop: 0
hasAdditiveReferencePose: 0
loopTime: 0
loopBlend: 0
loopBlendOrientation: 0
loopBlendPositionY: 0
loopBlendPositionXZ: 0
keepOriginalOrientation: 0
keepOriginalPositionY: 1
keepOriginalPositionXZ: 0
heightFromFeet: 0
mirror: 0
bodyMask: 01000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000
curves: []
events: []
transformMask:
- path:
weight: 1
- path: Controls
weight: 1
- path: Skeleton
weight: 1
- path: Skeleton/Spine
weight: 1
- path: Skeleton/Spine/LeftShoulder
weight: 1
- path: Skeleton/Spine/LeftShoulder/LeftUpperArm
weight: 1
- path: Skeleton/Spine/LeftShoulder/LeftUpperArm/LeftArm
weight: 1
- path: Skeleton/Spine/LeftShoulder/LeftUpperArm/LeftArm/LeftHand
weight: 1
- path: Skeleton/Spine/LeftShoulder/LeftUpperArm/LeftArm/LeftHand/LeftHandEnd
weight: 1
- path: Skeleton/Spine/Neck
weight: 1
- path: Skeleton/Spine/Neck/Head
weight: 1
- path: Skeleton/Spine/Neck/Head/Eyes
weight: 1
- path: Skeleton/Spine/Neck/Head/HeadEnd
weight: 1
- path: Skeleton/Spine/Neck/Head/LeftEar
weight: 1
- path: Skeleton/Spine/Neck/Head/LeftEar/LeftEarEnd
weight: 1
- path: Skeleton/Spine/Neck/Head/Mouth
weight: 1
- path: Skeleton/Spine/Neck/Head/Mouth/MouthEnd
weight: 1
- path: Skeleton/Spine/Neck/Head/RightEar
weight: 1
- path: Skeleton/Spine/Neck/Head/RightEar/RightEarEnd
weight: 1
- path: Skeleton/Spine/Pelvis
weight: 1
- path: Skeleton/Spine/Pelvis/LeftHip
weight: 1
- path: Skeleton/Spine/Pelvis/LeftHip/LeftLeg1
weight: 1
- path: Skeleton/Spine/Pelvis/LeftHip/LeftLeg1/LeftLeg2
weight: 1
- path: Skeleton/Spine/Pelvis/LeftHip/LeftLeg1/LeftLeg2/LeftLeg3
weight: 1
- path: Skeleton/Spine/Pelvis/LeftHip/LeftLeg1/LeftLeg2/LeftLeg3/LeftFoot
weight: 1
- path: Skeleton/Spine/Pelvis/LeftHip/LeftLeg1/LeftLeg2/LeftLeg3/LeftFoot/LeftFootEnd
weight: 1
- path: Skeleton/Spine/Pelvis/RightHip
weight: 1
- path: Skeleton/Spine/Pelvis/RightHip/RightLeg1
weight: 1
- path: Skeleton/Spine/Pelvis/RightHip/RightLeg1/RightLeg2
weight: 1
- path: Skeleton/Spine/Pelvis/RightHip/RightLeg1/RightLeg2/RightLeg3
weight: 1
- path: Skeleton/Spine/Pelvis/RightHip/RightLeg1/RightLeg2/RightLeg3/RightFoot
weight: 1
- path: Skeleton/Spine/Pelvis/RightHip/RightLeg1/RightLeg2/RightLeg3/RightFoot/RightFootEnd
weight: 1
- path: Skeleton/Spine/Pelvis/Tail1
weight: 1
- path: Skeleton/Spine/Pelvis/Tail1/Tail2
weight: 1
- path: Skeleton/Spine/Pelvis/Tail1/Tail2/Tail3
weight: 1
- path: Skeleton/Spine/Pelvis/Tail1/Tail2/Tail3/Tail3 1
weight: 1
- path: Skeleton/Spine/RightShoulder
weight: 1
- path: Skeleton/Spine/RightShoulder/RightUpperArm
weight: 1
- path: Skeleton/Spine/RightShoulder/RightUpperArm/RightArm
weight: 1
- path: Skeleton/Spine/RightShoulder/RightUpperArm/RightArm/RightHand
weight: 1
- path: Skeleton/Spine/RightShoulder/RightUpperArm/RightArm/RightHand/RightHandEnd
weight: 1
maskType: 3
maskSource: {instanceID: 0}
additiveReferencePoseFrame: 0
isReadable: 0
meshes:
lODScreenPercentages: []
globalScale: 1
meshCompression: 0
addColliders: 0
importBlendShapes: 1
swapUVChannels: 0
generateSecondaryUV: 0
useFileUnits: 1
optimizeMeshForGPU: 1
keepQuads: 0
weldVertices: 1
secondaryUVAngleDistortion: 8
secondaryUVAreaDistortion: 15.000001
secondaryUVHardAngle: 88
secondaryUVPackMargin: 4
useFileScale: 1
tangentSpace:
normalSmoothAngle: 60
normalImportMode: 0
tangentImportMode: 3
importAnimation: 1
copyAvatar: 0
humanDescription:
serializedVersion: 2
human: []
skeleton: []
armTwist: 0.5
foreArmTwist: 0.5
upperLegTwist: 0.5
legTwist: 0.5
armStretch: 0.05
legStretch: 0.05
feetSpacing: 0
rootMotionBoneName:
rootMotionBoneRotation: {x: 0, y: 0, z: 0, w: 1}
hasTranslationDoF: 0
hasExtraRoot: 0
skeletonHasParents: 0
lastHumanDescriptionAvatarSource: {instanceID: 0}
animationType: 2
humanoidOversampling: 1
additionalBone: 0
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
Aggregation Examples
====================
There are several methods of performing aggregations in MongoDB. These
examples cover the new aggregation framework, using map reduce and using the
group method.
.. testsetup::
from pymongo import MongoClient
client = MongoClient()
client.drop_database('aggregation_example')
Setup
-----
To start, we'll insert some example data which we can perform
aggregations on:
.. doctest::
>>> from pymongo import MongoClient
>>> db = MongoClient().aggregation_example
>>> result = db.things.insert_many([{"x": 1, "tags": ["dog", "cat"]},
... {"x": 2, "tags": ["cat"]},
... {"x": 2, "tags": ["mouse", "cat", "dog"]},
... {"x": 3, "tags": []}])
>>> result.inserted_ids
[ObjectId('...'), ObjectId('...'), ObjectId('...'), ObjectId('...')]
.. _aggregate-examples:
Aggregation Framework
---------------------
This example shows how to use the
:meth:`~pymongo.collection.Collection.aggregate` method to use the aggregation
framework. We'll perform a simple aggregation to count the number of
occurrences for each tag in the ``tags`` array, across the entire collection.
To achieve this we need to pass in three operations to the pipeline.
First, we need to unwind the ``tags`` array, then group by the tags and
sum them up, finally we sort by count.
As python dictionaries don't maintain order you should use :class:`~bson.son.SON`
or :class:`collections.OrderedDict` where explicit ordering is required
eg "$sort":
.. note::
aggregate requires server version **>= 2.1.0**.
.. doctest::
>>> from bson.son import SON
>>> pipeline = [
... {"$unwind": "$tags"},
... {"$group": {"_id": "$tags", "count": {"$sum": 1}}},
... {"$sort": SON([("count", -1), ("_id", -1)])}
... ]
>>> import pprint
>>> pprint.pprint(list(db.things.aggregate(pipeline)))
[{u'_id': u'cat', u'count': 3},
{u'_id': u'dog', u'count': 2},
{u'_id': u'mouse', u'count': 1}]
To run an explain plan for this aggregation use the
:meth:`~pymongo.database.Database.command` method::
>>> db.command('aggregate', 'things', pipeline=pipeline, explain=True)
{u'ok': 1.0, u'stages': [...]}
As well as simple aggregations the aggregation framework provides projection
capabilities to reshape the returned data. Using projections and aggregation,
you can add computed fields, create new virtual sub-objects, and extract
sub-fields into the top-level of results.
.. seealso:: The full documentation for MongoDB's `aggregation framework
<http://docs.mongodb.org/manual/applications/aggregation>`_
Map/Reduce
----------
Another option for aggregation is to use the map reduce framework. Here we
will define **map** and **reduce** functions to also count the number of
occurrences for each tag in the ``tags`` array, across the entire collection.
Our **map** function just emits a single `(key, 1)` pair for each tag in
the array:
.. doctest::
>>> from bson.code import Code
>>> mapper = Code("""
... function () {
... this.tags.forEach(function(z) {
... emit(z, 1);
... });
... }
... """)
The **reduce** function sums over all of the emitted values for a given key:
.. doctest::
>>> reducer = Code("""
... function (key, values) {
... var total = 0;
... for (var i = 0; i < values.length; i++) {
... total += values[i];
... }
... return total;
... }
... """)
.. note:: We can't just return ``values.length`` as the **reduce** function
might be called iteratively on the results of other reduce steps.
Finally, we call :meth:`~pymongo.collection.Collection.map_reduce` and
iterate over the result collection:
.. doctest::
>>> result = db.things.map_reduce(mapper, reducer, "myresults")
>>> for doc in result.find().sort("_id"):
... pprint.pprint(doc)
...
{u'_id': u'cat', u'value': 3.0}
{u'_id': u'dog', u'value': 2.0}
{u'_id': u'mouse', u'value': 1.0}
Advanced Map/Reduce
-------------------
PyMongo's API supports all of the features of MongoDB's map/reduce engine.
One interesting feature is the ability to get more detailed results when
desired, by passing `full_response=True` to
:meth:`~pymongo.collection.Collection.map_reduce`. This returns the full
response to the map/reduce command, rather than just the result collection:
.. doctest::
>>> pprint.pprint(
... db.things.map_reduce(mapper, reducer, "myresults", full_response=True))
{...u'ok': 1.0,... u'result': u'myresults'...}
All of the optional map/reduce parameters are also supported, simply pass them
as keyword arguments. In this example we use the `query` parameter to limit the
documents that will be mapped over:
.. doctest::
>>> results = db.things.map_reduce(
... mapper, reducer, "myresults", query={"x": {"$lt": 2}})
>>> for doc in results.find().sort("_id"):
... pprint.pprint(doc)
...
{u'_id': u'cat', u'value': 1.0}
{u'_id': u'dog', u'value': 1.0}
You can use :class:`~bson.son.SON` or :class:`collections.OrderedDict` to
specify a different database to store the result collection:
.. doctest::
>>> from bson.son import SON
>>> pprint.pprint(
... db.things.map_reduce(
... mapper,
... reducer,
... out=SON([("replace", "results"), ("db", "outdb")]),
... full_response=True))
{...u'ok': 1.0,... u'result': {u'collection': u'results', u'db': u'outdb'}...}
.. seealso:: The full list of options for MongoDB's `map reduce engine <http://www.mongodb.org/display/DOCS/MapReduce>`_
| {
"pile_set_name": "Github"
} |
<html>
<head>
<style>
.d {
height:10em;
border:75px solid #CCC;
}
</style>
</head>
<body>
<ul class="d">
<li>a</li>
</ul>
</body>
</html>
| {
"pile_set_name": "Github"
} |
-----BEGIN CERTIFICATE-----
MIIDWjCCAwWgAwIBAgIBATAMBggqhkjOPQQDAQUAMFAxCzAJBgNVBAYTAkRFMQ0w
CwYDVQQKDARidW5kMQwwCgYDVQQLDANic2kxDTALBgNVBAUTBDQ1NjcxFTATBgNV
BAMMDGNzY2EtZ2VybWFueTAeFw0wNzA3MTkxNTI3MThaFw0yODAxMTkxNTE4MDBa
MFAxCzAJBgNVBAYTAkRFMQ0wCwYDVQQKDARidW5kMQwwCgYDVQQLDANic2kxDTAL
BgNVBAUTBDQ1NjcxFTATBgNVBAMMDGNzY2EtZ2VybWFueTCCARMwgdQGByqGSM49
AgEwgcgCAQEwKAYHKoZIzj0BAQIdANfBNKomQ2aGKhgwJXXR14ewnwdXl9qJ9X7I
wP8wPAQcaKXmLKnObBwpmAOmwVMLUU4YKtiwBCpZytKfQwQcJYD2PM/kQTiHBxOx
qSNp4z4hNdJm27NyOGxACwQ5BA2QKa0sflz0NAgjsqh9xoyeTOMXTB5u/e4SwH1Y
qlb3csBybyTGuJ5OzawkNUuemcqj9tN2FALNAh0A18E0qiZDZoYqGDAlddD7mNEW
vEtt3ryjpaeTnwIBAQM6AAQBNkpLDwEC6VAqudxoVdkLBlpvXl5IOV+DCdV8Eauv
8hdWYH72dX7JiGyiItg8oEsamfpDxam84aOCARAwggEMMDYGA1UdEQQvMC2BGGNz
Y2EtZ2VybWFueUBic2kuYnVuZC5kZYYRZmF4Ois0OTIyODk1ODI3MjIwDgYDVR0P
AQH/BAQDAgEGMB0GA1UdDgQWBBQAlkUt5Yj5ZsTM3xYd0fP1NBtx5zAfBgNVHSME
GDAWgBQAlkUt5Yj5ZsTM3xYd0fP1NBtx5zBBBgNVHSAEOjA4MDYGCQQAfwAHAwEB
ATApMCcGCCsGAQUFBwIBFhtodHRwOi8vd3d3LmJzaS5idW5kLmRlL2NzY2EwEgYD
VR0TAQH/BAgwBgEB/wIBADArBgNVHRAEJDAigA8yMDA3MDcxOTE1MjcxOFqBDzIw
MjcxMTE5MTUxODAwWjAMBggqhkjOPQQDAQUAA0EAMD4CHQDGtB6DAhf9TJO1np4r
E3NOCcGC+mP67kEVqO3VAh0A0nk42gG4lRqQZKG2lq7fGBt0logpwTjw6y9iOw==
-----END CERTIFICATE-----
| {
"pile_set_name": "Github"
} |
<div class="apiDetail">
<div>
<h2><span>String</span><span class="path">setting.async.</span>type</h2>
<h3>Overview<span class="h3_info">[ depends on <span class="highlight_green">jquery.ztree.core</span> js ]</span></h3>
<div class="desc">
<p></p>
<div class="longdesc">
<p>Http request tyoe in ajax. It is valid when <span class="highlight_red">[setting.async.enable = true]</span></p>
<p>Default: "post"</p>
</div>
</div>
<h3>String Format</h3>
<div class="desc">
<p> "post" - http request mode</p>
<p> "get" - http request mode</p>
<p class="highlight_red">Both zTree and jQuery's this 'type' for ajax requests.</p>
</div>
<h3>Examples of setting</h3>
<h4>1. Set http request mode is 'get'</h4>
<pre xmlns=""><code>var setting = {
async: {
enable: true,
type: "get",
url: "http://host/getNode.php",
autoParam: ["id", "name"]
}
};
......</code></pre>
</div>
</div> | {
"pile_set_name": "Github"
} |
{
appid: '0',
description: '${description}',
projectname: '${projectName}',
_ttEnv: {
appid: '体验appId',
setting: {
urlCheck: true,
es6: true,
postcss: true,
minified: true,
newFeature: true
}
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* DO NOT EDIT THIS FILE!
*
* This file was automatically generated from external sources.
*
* Any manual change here will be lost the next time the SDK
* is updated. You've been warned!
*/
namespace DTS\eBaySDK\Product\Types;
/**
*
* @property \DTS\eBaySDK\Product\Types\StringValue $text
* @property \DTS\eBaySDK\Product\Types\NumericValue $number
* @property \DTS\eBaySDK\Product\Types\URIValue $URL
*/
class Value extends \DTS\eBaySDK\Types\BaseType
{
/**
* @var array Properties belonging to objects of this class.
*/
private static $propertyTypes = [
'text' => [
'type' => 'DTS\eBaySDK\Product\Types\StringValue',
'repeatable' => false,
'attribute' => false,
'elementName' => 'text'
],
'number' => [
'type' => 'DTS\eBaySDK\Product\Types\NumericValue',
'repeatable' => false,
'attribute' => false,
'elementName' => 'number'
],
'URL' => [
'type' => 'DTS\eBaySDK\Product\Types\URIValue',
'repeatable' => false,
'attribute' => false,
'elementName' => 'URL'
]
];
/**
* @param array $values Optional properties and values to assign to the object.
*/
public function __construct(array $values = [])
{
list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);
parent::__construct($parentValues);
if (!array_key_exists(__CLASS__, self::$properties)) {
self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
}
if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
self::$xmlNamespaces[__CLASS__] = 'xmlns="http://www.ebay.com/marketplace/marketplacecatalog/v1/services"';
}
$this->setValues(__CLASS__, $childValues);
}
}
| {
"pile_set_name": "Github"
} |
<template>
<div><x-child-rendered-throw></x-child-rendered-throw></div>
</template> | {
"pile_set_name": "Github"
} |
import styled from 'styles/styled-components';
const AtPrefix = styled.span`
color: black;
margin-left: 0.4em;
`;
export default AtPrefix;
| {
"pile_set_name": "Github"
} |
require 'tzinfo/timezone_definition'
module TZInfo
module Definitions
module Atlantic
module South_Georgia
include TimezoneDefinition
timezone 'Atlantic/South_Georgia' do |tz|
tz.offset :o0, -8768, 0, :LMT
tz.offset :o1, -7200, 0, :GST
tz.transition 1890, 1, :o1, 1627673806, 675
end
end
end
end
end
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2017-2020, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __AXIMG_T_HOST__
#define __AXIMG_T_HOST__
#include <systemc.h>
#include <ac_reset_signal_is.h>
#include <axi/axi4.h>
#include <nvhls_connections.h>
#include <queue>
#include <deque>
/**
* \brief A testbench component to verify AxiMasterGate.
* \ingroup AXI
*
* \tparam Cfg A valid AXI config.
*
* \par Overview
*
* This component connects to the request-response (non-AXI) interface of AXIMasterGate.
* It launches read and write requests and checks for appropriate responses.
*/
template <typename Cfg>
SC_MODULE(Host) {
public:
sc_in<bool> reset_bar;
sc_in<bool> clk;
Connections::Out<WrRequest<Cfg> > wrRequestOut;
Connections::In<WrResp<Cfg> > wrRespIn;
Connections::Out<RdRequest<Cfg> > rdRequestOut;
Connections::In<RdResp<Cfg> > rdRespIn;
static const int bytesPerBeat = Cfg::dataWidth >> 3;
sc_out<bool> done_write;
sc_out<bool> done_read;
static const int write_count = 400;
static const int read_count = 50;
std::deque<unsigned int> read_ref;
std::queue<typename axi::axi4<Cfg>::Data> dataQ;
SC_CTOR(Host) : reset_bar("reset_bar"), clk("clk") {
SC_THREAD(run_wr_source);
sensitive << clk.pos();
async_reset_signal_is(reset_bar, false);
SC_THREAD(run_wr_sink);
sensitive << clk.pos();
async_reset_signal_is(reset_bar, false);
SC_THREAD(run_rd_source);
sensitive << clk.pos();
async_reset_signal_is(reset_bar, false);
SC_THREAD(run_rd_sink);
sensitive << clk.pos();
async_reset_signal_is(reset_bar, false);
}
struct Data { // don't really need this except to test out gen_random_payload
static const int width = Cfg::dataWidth;
NVUINTW(width) d;
template <unsigned int Size>
void Marshall(Marshaller<Size>& m) {
m& d;
}
};
protected:
void run_wr_source() {
wrRequestOut.Reset();
int addr = 0;
int ctr = 0;
wait(20); // If we start sending requests before resetting the ReorderBufs, bad things happen
while (1) {
wait();
if (ctr < write_count) {
WrRequest<Cfg> wrRequest;
wrRequest.addr = addr;
int len = rand() % 6;
wrRequest.len = len;
wrRequest.last = 0;
for (int i = 0; i <= len; ++i) {
if (i == len) {
wrRequest.last = 1;
ctr++;
}
wrRequest.data = nvhls::gen_random_payload<Data>().d;
std::cout << "@" << sc_time_stamp()
<< " write source initiated a request:"
<< "\t addr = " << hex << wrRequest.addr
<< "\t data = " << hex << wrRequest.data
<< "\t len = " << dec << wrRequest.len
<< std::endl;
wrRequestOut.Push(wrRequest);
dataQ.push(wrRequest.data);
addr += bytesPerBeat;
}
}
}
}
void run_wr_sink() {
wrRespIn.Reset();
done_write = 0;
int ctr = 0;
while (1) {
wait();
WrResp<Cfg> wrResp = wrRespIn.Pop();
std::cout << "@" << sc_time_stamp() << " write sink received response:"
<< "\t resp = " << dec << wrResp.resp
<< std::endl;
if (++ctr == write_count) done_write = 1;
}
}
void run_rd_source() {
rdRequestOut.Reset();
int addr = 0;
int ctr = 0;
wait(2000); // Let writes run well ahead of reads
while (1) {
wait();
if (ctr < read_count) {
if (rand() % 5 == 0) { // Really need to pace ourselves here
RdRequest<Cfg> rdRequest;
rdRequest.addr = addr;
int len = rand() % 3;
rdRequest.len = len;
std::cout << "@" << sc_time_stamp() << " read source initiated a request:"
<< "\t addr = " << hex << rdRequest.addr
<< "\t len = " << dec << rdRequest.len
<< std::endl;
rdRequestOut.Push(rdRequest);
addr += (len+1)*bytesPerBeat;
ctr++;
}
}
}
}
void run_rd_sink() {
rdRespIn.Reset();
done_read = 0;
int ctr = 0;
while (1) {
wait();
RdResp<Cfg> rdResp = rdRespIn.Pop();
typename axi::axi4<Cfg>::Data rd_data_expected = dataQ.front(); dataQ.pop();
std::cout << "@" << sc_time_stamp() << " read sink received response:"
<< "\t last = " << rdResp.last
<< "\t data = " << hex << rdResp.data
<< "\t expected = " << hex << rd_data_expected
<< std::endl;
NVHLS_ASSERT_MSG(rdResp.data == rd_data_expected, "Read response data did not match expected value");
if (rdResp.last == 1) ctr++;
if (ctr == read_count) done_read = 1;
}
}
};
#endif
| {
"pile_set_name": "Github"
} |
448
| {
"pile_set_name": "Github"
} |
layer at (0,0) size 800x600
RenderView at (0,0) size 800x600
layer at (0,0) size 800x188
RenderBlock {HTML} at (0,0) size 800x188
RenderBody {BODY} at (8,8) size 784x172
RenderBlock (anonymous) at (0,0) size 784x18
RenderInline {DIV} at (0,0) size 528x16 [color=#FFFFFF] [bgcolor=#FF0000]
RenderText {#text} at (0,1) size 528x16
text run at (0,1) width 528: "Ahem_font_required_for_this_test."
RenderText {#text} at (0,0) size 0x0
RenderBlock {P} at (0,34) size 784x18
RenderText {#text} at (0,0) size 439x18
text run at (0,0) width 439: "There should be no red below, only a green square bordered in green."
RenderTable {TABLE} at (0,68) size 104x104
RenderTableSection {TBODY} at (0,0) size 104x104
RenderTableRow {TR} at (0,2) size 104x100
RenderTableCell {TD} at (2,2) size 100x100 [color=#800000] [bgcolor=#FF0000] [r=0 c=0 rs=1 cs=1]
RenderBlock {DIV} at (0,0) size 100x20 [color=#008000]
RenderText {#text} at (0,0) size 100x20
text run at (0,0) width 100: "XXXXX"
RenderBlock {DIV} at (0,20) size 100x20 [color=#008000]
RenderInline {SPAN} at (0,0) size 100x20 [bgcolor=#00FF00]
RenderText {#text} at (0,0) size 100x20
text run at (0,0) width 100: "X X"
RenderBlock {DIV} at (0,40) size 100x20 [color=#008000]
RenderInline {SPAN} at (0,0) size 100x20 [bgcolor=#00FF00]
RenderText {#text} at (0,0) size 100x20
text run at (0,0) width 100: "X\x{200B} \x{200B} \x{200B} \x{200B}X"
RenderBlock {DIV} at (0,60) size 100x20 [color=#008000]
RenderInline {SPAN} at (0,0) size 100x20 [bgcolor=#00FF00]
RenderText {#text} at (0,0) size 100x20
text run at (0,0) width 100: "X \x{200B} \x{200B} X"
RenderBlock {DIV} at (0,80) size 100x20 [color=#008000]
RenderText {#text} at (0,0) size 100x20
text run at (0,0) width 100: "XXXXX"
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Author</key>
<string>igoraksenov</string>
<key>CodecID</key>
<integer>1634</integer>
<key>CodecName</key>
<string>ALC662</string>
<key>Files</key>
<dict>
<key>Layouts</key>
<array>
<dict>
<key>Comment</key>
<string>Mirone 3 ports (Pink, Green, Blue)</string>
<key>Id</key>
<integer>5</integer>
<key>Path</key>
<string>layout5.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Mirone 5/6 ports (Gray, Black, Orange, Pink, Green, Blue)</string>
<key>Id</key>
<integer>7</integer>
<key>Path</key>
<string>layout7.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>5 ports (Green, Pink, Green, Pink, Blue) - Irving23</string>
<key>Id</key>
<integer>11</integer>
<key>Path</key>
<string>layout11.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom ALC662 by stich86 for Lenovo ThinkCentre M800</string>
<key>Id</key>
<integer>12</integer>
<key>Path</key>
<string>layout12.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom ALC662 by Vandroiy for Asus X66Ic</string>
<key>Id</key>
<integer>13</integer>
<key>Path</key>
<string>layout13.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>MacPeet - ALC662 for Acer Aspire A7600U All in One</string>
<key>Id</key>
<integer>15</integer>
<key>Path</key>
<string>layout15.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>phucnguyen.2411 - ALC662v3 for Lenovo ThinkCentre M92P SFF</string>
<key>Id</key>
<integer>16</integer>
<key>Path</key>
<string>layout16.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom ALC662 by aloha_cn for HP Compaq Elite 8000 SFF</string>
<key>Id</key>
<integer>17</integer>
<key>Path</key>
<string>layout17.xml.zlib</string>
</dict>
</array>
<key>Platforms</key>
<array>
<dict>
<key>Comment</key>
<string>Mirone resources</string>
<key>Id</key>
<integer>5</integer>
<key>Path</key>
<string>PlatformsM.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Mirone resources</string>
<key>Id</key>
<integer>7</integer>
<key>Path</key>
<string>PlatformsM.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Irving23 resources</string>
<key>Id</key>
<integer>11</integer>
<key>Path</key>
<string>Platforms11.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom ALC662 by stich86 for Lenovo ThinkCentre M800</string>
<key>Id</key>
<integer>12</integer>
<key>Path</key>
<string>Platforms12.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom ALC662 by Vandroiy for Asus X66Ic</string>
<key>Id</key>
<integer>13</integer>
<key>Path</key>
<string>Platforms13.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>MacPeet - ALC662 for Acer Aspire A7600U All in One</string>
<key>Id</key>
<integer>15</integer>
<key>Path</key>
<string>Platforms15.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>phucnguyen.2411 - ALC662v3 for Lenovo ThinkCentre M92P SFF</string>
<key>Id</key>
<integer>16</integer>
<key>Path</key>
<string>Platforms16.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom ALC662 by aloha_cn for HP Compaq Elite 8000 SFF</string>
<key>Id</key>
<integer>17</integer>
<key>Path</key>
<string>Platforms17.xml.zlib</string>
</dict>
</array>
</dict>
<key>Patches</key>
<array>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>xgYASIu/aAE=</data>
<key>MinKernel</key>
<integer>18</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>xgYBSIu/aAE=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcYGAEmLvCQ=</data>
<key>MaxKernel</key>
<integer>13</integer>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcYGAUmLvCQ=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcYGAEiLu2g=</data>
<key>MinKernel</key>
<integer>14</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcYGAUiLu2g=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcaGQwEAAAA=</data>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcaGQwEAAAE=</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>hQjsEA==</data>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAAAAA==</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>hAjsEA==</data>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAAAAA==</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>hBnUEQ==</data>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>YgbsEA==</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>gxnUEQ==</data>
<key>MaxKernel</key>
<integer>15</integer>
<key>MinKernel</key>
<integer>15</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAAAAA==</data>
</dict>
</array>
<key>Revisions</key>
<array>
<integer>1048833</integer>
<integer>1049344</integer>
</array>
<key>Vendor</key>
<string>Realtek</string>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
import FWCore.ParameterSet.Config as cms
process = cms.Process("analysis")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(10)
process.load('Configuration.StandardSequences.Services_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')
process.load('JetMETCorrections.Configuration.JetCorrectionProducers_cff')
process.load('RecoMET.METPUSubtraction.mvaPFMET_cff')
# Other statements
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_mc', '')
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(20) )
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring(
"root://eoscms//eos/cms/store/relval/CMSSW_7_5_0_pre4/RelValZMM_13/GEN-SIM-RECO/PU50ns_MCRUN2_75_V0-v1/00000/24B4BCD7-22F8-E411-A740-0025905A48F2.root"
),
skipEvents = cms.untracked.uint32(0)
)
process.output = cms.OutputModule("PoolOutputModule",
outputCommands = cms.untracked.vstring('keep *'),
fileName = cms.untracked.string("MVaTest.root")
)
process.ana = cms.Sequence(process.pfMVAMEtSequence)
process.p = cms.Path(process.ana)
process.outpath = cms.EndPath(process.output)
| {
"pile_set_name": "Github"
} |
var convert = require('./convert'),
func = convert('invert', require('../invert'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"pile_set_name": "Github"
} |
<?php
namespace Oro\Bundle\LocaleBundle\Migrations\Schema\v1_1;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope;
use Oro\Bundle\EntityExtendBundle\Extend\RelationType;
use Oro\Bundle\EntityExtendBundle\Migration\Extension\ExtendExtension;
use Oro\Bundle\EntityExtendBundle\Migration\Extension\ExtendExtensionAwareInterface;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
use Oro\Bundle\ScopeBundle\Migrations\Schema\OroScopeBundleInstaller;
class OroLocaleBundleScopeRelations implements Migration, ExtendExtensionAwareInterface
{
/**
* @var ExtendExtension
*/
private $extendExtension;
/**
* {@inheritdoc}
*/
public function setExtendExtension(ExtendExtension $extendExtension)
{
$this->extendExtension = $extendExtension;
}
/**
* {@inheritdoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
$this->addRelationsToScope($schema);
}
/**
* @param Schema $schema
*/
protected function addRelationsToScope(Schema $schema)
{
$this->extendExtension->addManyToOneRelation(
$schema,
OroScopeBundleInstaller::ORO_SCOPE,
'localization',
'oro_localization',
'id',
[
'extend' => [
'owner' => ExtendScope::OWNER_CUSTOM,
'cascade' => ['all'],
'on_delete' => 'CASCADE',
'nullable' => true
]
],
RelationType::MANY_TO_ONE
);
}
}
| {
"pile_set_name": "Github"
} |
package com.muses.taoshop;
import java.lang.ref.SoftReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* <pre>
* ThreadLocal测试类
* </pre>
*
* @author nicky
* @version 1.00.00
* <pre>
* 修改记录
* 修改后版本: 修改人: 修改日期: 2018.12.22 22:51 修改内容:
* </pre>
*/
public class ThreadLocalTest implements Runnable {
private int i ;
private static final ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>();
public ThreadLocalTest(int i){
this.i = i;
}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
threadLocal.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
try {
Date t = threadLocal.get().parse("2018-12-22 19:30:"+i%60);
System.out.println(i+":"+t.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
ExecutorService es = Executors.newFixedThreadPool(10);
for(int i =0;i<=1000;i++){
es.execute(new ThreadLocalTest(i));
}
threadLocal.remove();
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkBlurMaskFilter.h"
#include "SkCanvas.h"
#include "SkMath.h"
#include "SkPaint.h"
#include "SkRandom.h"
///////////////////////////////////////////////////////////////////////////////
#define ILLEGAL_MODE ((SkXfermode::Mode)-1)
static const int outset = 100;
static const SkColor bgColor = SK_ColorWHITE;
static const int strokeWidth = 4;
static void create(SkBitmap* bm, SkIRect bound, SkBitmap::Config config) {
bm->setConfig(config, bound.width(), bound.height());
bm->allocPixels();
}
static void drawBG(SkCanvas* canvas) {
canvas->drawColor(bgColor);
}
struct BlurTest {
void (*addPath)(SkPath*);
int viewLen;
SkIRect views[9];
};
//Path Draw Procs
//Beware that paths themselves my draw differently depending on the clip.
static void draw50x50Rect(SkPath* path) {
path->addRect(0, 0, SkIntToScalar(50), SkIntToScalar(50));
}
//Tests
static BlurTest tests[] = {
{ draw50x50Rect, 3, {
//inner half of blur
{ 0, 0, 50, 50 },
//blur, but no path.
{ 50 + strokeWidth/2, 50 + strokeWidth/2, 100, 100 },
//just an edge
{ 40, strokeWidth, 60, 50 - strokeWidth },
}},
};
/** Assumes that the ref draw was completely inside ref canvas --
implies that everything outside is "bgColor".
Checks that all overlap is the same and that all non-overlap on the
ref is "bgColor".
*/
static bool compare(const SkBitmap& ref, const SkIRect& iref,
const SkBitmap& test, const SkIRect& itest)
{
const int xOff = itest.fLeft - iref.fLeft;
const int yOff = itest.fTop - iref.fTop;
SkAutoLockPixels alpRef(ref);
SkAutoLockPixels alpTest(test);
for (int y = 0; y < test.height(); ++y) {
for (int x = 0; x < test.width(); ++x) {
SkColor testColor = test.getColor(x, y);
int refX = x + xOff;
int refY = y + yOff;
SkColor refColor;
if (refX >= 0 && refX < ref.width() &&
refY >= 0 && refY < ref.height())
{
refColor = ref.getColor(refX, refY);
} else {
refColor = bgColor;
}
if (refColor != testColor) {
return false;
}
}
}
return true;
}
static void test_blur(skiatest::Reporter* reporter) {
SkPaint paint;
paint.setColor(SK_ColorGRAY);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(SkIntToScalar(strokeWidth));
SkScalar radius = SkIntToScalar(5);
for (int style = 0; style < SkBlurMaskFilter::kBlurStyleCount; ++style) {
SkBlurMaskFilter::BlurStyle blurStyle =
static_cast<SkBlurMaskFilter::BlurStyle>(style);
const uint32_t flagPermutations = SkBlurMaskFilter::kAll_BlurFlag;
for (uint32_t flags = 0; flags < flagPermutations; ++flags) {
SkMaskFilter* filter;
filter = SkBlurMaskFilter::Create(radius, blurStyle, flags);
SkMaskFilter::BlurInfo info;
sk_bzero(&info, sizeof(info));
SkMaskFilter::BlurType type = filter->asABlur(&info);
REPORTER_ASSERT(reporter, type ==
static_cast<SkMaskFilter::BlurType>(style + 1));
REPORTER_ASSERT(reporter, info.fRadius == radius);
REPORTER_ASSERT(reporter, info.fIgnoreTransform ==
SkToBool(flags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag));
REPORTER_ASSERT(reporter, info.fHighQuality ==
SkToBool(flags & SkBlurMaskFilter::kHighQuality_BlurFlag));
paint.setMaskFilter(filter);
filter->unref();
for (size_t test = 0; test < SK_ARRAY_COUNT(tests); ++test) {
SkPath path;
tests[test].addPath(&path);
SkPath strokedPath;
paint.getFillPath(path, &strokedPath);
SkRect refBound = strokedPath.getBounds();
SkIRect iref;
refBound.roundOut(&iref);
iref.inset(-outset, -outset);
SkBitmap refBitmap;
create(&refBitmap, iref, SkBitmap::kARGB_8888_Config);
SkCanvas refCanvas(refBitmap);
refCanvas.translate(SkIntToScalar(-iref.fLeft),
SkIntToScalar(-iref.fTop));
drawBG(&refCanvas);
refCanvas.drawPath(path, paint);
for (int view = 0; view < tests[test].viewLen; ++view) {
SkIRect itest = tests[test].views[view];
SkBitmap testBitmap;
create(&testBitmap, itest, SkBitmap::kARGB_8888_Config);
SkCanvas testCanvas(testBitmap);
testCanvas.translate(SkIntToScalar(-itest.fLeft),
SkIntToScalar(-itest.fTop));
drawBG(&testCanvas);
testCanvas.drawPath(path, paint);
REPORTER_ASSERT(reporter,
compare(refBitmap, iref, testBitmap, itest));
}
}
}
}
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("BlurMaskFilter", BlurTestClass, test_blur)
| {
"pile_set_name": "Github"
} |
//
// ExpireCache.h
//
// Library: Foundation
// Package: Cache
// Module: ExpireCache
//
// Definition of the ExpireCache class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Foundation_ExpireCache_INCLUDED
#define Foundation_ExpireCache_INCLUDED
#include "Poco/AbstractCache.h"
#include "Poco/ExpireStrategy.h"
namespace Poco {
template <
class TKey,
class TValue,
class TMutex = FastMutex,
class TEventMutex = FastMutex
>
class ExpireCache: public AbstractCache<TKey, TValue, ExpireStrategy<TKey, TValue>, TMutex, TEventMutex>
/// An ExpireCache caches entries for a fixed time period (per default 10 minutes).
/// Entries expire independently of the access pattern, i.e. after a constant time.
/// If you require your objects to expire after they were not accessed for a given time
/// period use a Poco::AccessExpireCache.
///
/// Be careful when using an ExpireCache. A cache is often used
/// like cache.has(x) followed by cache.get x). Note that it could happen
/// that the "has" call works, then the current execution thread gets descheduled, time passes,
/// the entry gets invalid, thus leading to an empty SharedPtr being returned
/// when "get" is invoked.
{
public:
ExpireCache(Timestamp::TimeDiff expire = 600000):
AbstractCache<TKey, TValue, ExpireStrategy<TKey, TValue>, TMutex, TEventMutex>(ExpireStrategy<TKey, TValue>(expire))
{
}
~ExpireCache()
{
}
private:
ExpireCache(const ExpireCache& aCache);
ExpireCache& operator = (const ExpireCache& aCache);
};
} // namespace Poco
#endif // Foundation_ExpireCache_INCLUDED
| {
"pile_set_name": "Github"
} |
# Copyright (c) 2020, Intel Corporation
#
# 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.
if(${Common_Encode_Supported} STREQUAL "yes")
set(TMP_SOURCES_
${TMP_SOURCES_}
${CMAKE_CURRENT_LIST_DIR}/decode_scalability_option.cpp
${CMAKE_CURRENT_LIST_DIR}/decode_scalability_singlepipe.cpp
)
set(TMP_HEADERS_
${TMP_HEADERS_}
${CMAKE_CURRENT_LIST_DIR}/decode_scalability_defs.h
${CMAKE_CURRENT_LIST_DIR}/decode_scalability_option.h
${CMAKE_CURRENT_LIST_DIR}/decode_scalability_singlepipe.h
)
endif()
media_add_curr_to_include_path()
| {
"pile_set_name": "Github"
} |
/*!
* Copyright 2018
*/
#include <xgboost/linear_updater.h>
#include <dmlc/registry.h>
#include "./param.h"
namespace dmlc {
DMLC_REGISTRY_ENABLE(::xgboost::LinearUpdaterReg);
} // namespace dmlc
namespace xgboost {
LinearUpdater* LinearUpdater::Create(const std::string& name, GenericParameter const* lparam) {
auto *e = ::dmlc::Registry< ::xgboost::LinearUpdaterReg>::Get()->Find(name);
if (e == nullptr) {
LOG(FATAL) << "Unknown linear updater " << name;
}
auto p_linear = (e->body)();
p_linear->learner_param_ = lparam;
return p_linear;
}
} // namespace xgboost
namespace xgboost {
namespace linear {
DMLC_REGISTER_PARAMETER(LinearTrainParam);
// List of files that will be force linked in static links.
DMLC_REGISTRY_LINK_TAG(updater_shotgun);
DMLC_REGISTRY_LINK_TAG(updater_coordinate);
#ifdef XGBOOST_USE_CUDA
DMLC_REGISTRY_LINK_TAG(updater_gpu_coordinate);
#endif // XGBOOST_USE_CUDA
} // namespace linear
} // namespace xgboost
| {
"pile_set_name": "Github"
} |
AX25 is Andes CPU IP to adopt RISC-V architecture.
Features
========
CPU Core
- 5-stage in-order execution pipeline
- Hardware Multiplier
- radix-2/radix-4/radix-16/radix-256/fast
- Hardware Divider
- Optional branch prediction
- Machine mode and optional user mode
- Optional performance monitoring
ISA
- RV64I base integer instructions
- RVC for 16-bit compressed instructions
- RVM for multiplication and division instructions
Memory subsystem
- I & D local memory
- Size: 4KB to 16MB
- Memory subsyetem soft-error protection
- Protection scheme: parity-checking or error-checking-and-correction (ECC)
- Automatic hardware error correction
Bus
- Interface Protocol
- Synchronous AHB (32-bit/64-bit data-width), or
- Synchronous AXI4 (64-bit data-width)
Power management
- Wait for interrupt (WFI) mode
Debug
- Configurable number of breakpoints: 2/4/8
- External Debug Module
- AHB slave port
- External JTAG debug transport module
Platform Level Interrupt Controller (PLIC)
- AHB slave port
- Configurable number of interrupts: 1-1023
- Configurable number of interrupt priorities: 3/7/15/63/127/255
- Configurable number of targets: 1-16
- Preempted interrupt priority stack
| {
"pile_set_name": "Github"
} |
//==- HexagonInstrFormatsV4.td - Hexagon Instruction Formats --*- tablegen -==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes the Hexagon V4 instruction classes in TableGen format.
//
//===----------------------------------------------------------------------===//
// Duplex Instruction Class Declaration
//===----------------------------------------------------------------------===//
class OpcodeDuplex {
field bits<32> Inst = ?; // Default to an invalid insn.
bits<4> IClass = 0; // ICLASS
bits<13> ISubHi = 0; // Low sub-insn
bits<13> ISubLo = 0; // High sub-insn
let Inst{31-29} = IClass{3-1};
let Inst{13} = IClass{0};
let Inst{15-14} = 0;
let Inst{28-16} = ISubHi;
let Inst{12-0} = ISubLo;
}
class InstDuplex<bits<4> iClass, list<dag> pattern = [],
string cstr = "">
: Instruction, OpcodeDuplex {
let Namespace = "Hexagon";
IType Type = TypeDUPLEX; // uses slot 0,1
let isCodeGenOnly = 1;
let hasSideEffects = 0;
dag OutOperandList = (outs);
dag InOperandList = (ins);
let IClass = iClass;
let Constraints = cstr;
let Itinerary = DUPLEX;
let Size = 4;
// SoftFail is a field the disassembler can use to provide a way for
// instructions to not match without killing the whole decode process. It is
// mainly used for ARM, but Tablegen expects this field to exist or it fails
// to build the decode table.
field bits<32> SoftFail = 0;
// *** Must match MCTargetDesc/HexagonBaseInfo.h ***
let TSFlags{5-0} = Type.Value;
// Predicated instructions.
bits<1> isPredicated = 0;
let TSFlags{6} = isPredicated;
bits<1> isPredicatedFalse = 0;
let TSFlags{7} = isPredicatedFalse;
bits<1> isPredicatedNew = 0;
let TSFlags{8} = isPredicatedNew;
// New-value insn helper fields.
bits<1> isNewValue = 0;
let TSFlags{9} = isNewValue; // New-value consumer insn.
bits<1> hasNewValue = 0;
let TSFlags{10} = hasNewValue; // New-value producer insn.
bits<3> opNewValue = 0;
let TSFlags{13-11} = opNewValue; // New-value produced operand.
bits<1> isNVStorable = 0;
let TSFlags{14} = isNVStorable; // Store that can become new-value store.
bits<1> isNVStore = 0;
let TSFlags{15} = isNVStore; // New-value store insn.
// Immediate extender helper fields.
bits<1> isExtendable = 0;
let TSFlags{16} = isExtendable; // Insn may be extended.
bits<1> isExtended = 0;
let TSFlags{17} = isExtended; // Insn must be extended.
bits<3> opExtendable = 0;
let TSFlags{20-18} = opExtendable; // Which operand may be extended.
bits<1> isExtentSigned = 0;
let TSFlags{21} = isExtentSigned; // Signed or unsigned range.
bits<5> opExtentBits = 0;
let TSFlags{26-22} = opExtentBits; //Number of bits of range before extending.
bits<2> opExtentAlign = 0;
let TSFlags{28-27} = opExtentAlign; // Alignment exponent before extending.
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Unknown default region, use the first alphabetically.
*/
return require __DIR__.'/chr_US.php';
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/memblock.h>
static u64 patterns[] __initdata = {
/* The first entry has to be 0 to leave memtest with zeroed memory */
0,
0xffffffffffffffffULL,
0x5555555555555555ULL,
0xaaaaaaaaaaaaaaaaULL,
0x1111111111111111ULL,
0x2222222222222222ULL,
0x4444444444444444ULL,
0x8888888888888888ULL,
0x3333333333333333ULL,
0x6666666666666666ULL,
0x9999999999999999ULL,
0xccccccccccccccccULL,
0x7777777777777777ULL,
0xbbbbbbbbbbbbbbbbULL,
0xddddddddddddddddULL,
0xeeeeeeeeeeeeeeeeULL,
0x7a6c7258554e494cULL, /* yeah ;-) */
};
static void __init reserve_bad_mem(u64 pattern, phys_addr_t start_bad, phys_addr_t end_bad)
{
pr_info(" %016llx bad mem addr %pa - %pa reserved\n",
cpu_to_be64(pattern), &start_bad, &end_bad);
memblock_reserve(start_bad, end_bad - start_bad);
}
static void __init memtest(u64 pattern, phys_addr_t start_phys, phys_addr_t size)
{
u64 *p, *start, *end;
phys_addr_t start_bad, last_bad;
phys_addr_t start_phys_aligned;
const size_t incr = sizeof(pattern);
start_phys_aligned = ALIGN(start_phys, incr);
start = __va(start_phys_aligned);
end = start + (size - (start_phys_aligned - start_phys)) / incr;
start_bad = 0;
last_bad = 0;
for (p = start; p < end; p++)
*p = pattern;
for (p = start; p < end; p++, start_phys_aligned += incr) {
if (*p == pattern)
continue;
if (start_phys_aligned == last_bad + incr) {
last_bad += incr;
continue;
}
if (start_bad)
reserve_bad_mem(pattern, start_bad, last_bad + incr);
start_bad = last_bad = start_phys_aligned;
}
if (start_bad)
reserve_bad_mem(pattern, start_bad, last_bad + incr);
}
static void __init do_one_pass(u64 pattern, phys_addr_t start, phys_addr_t end)
{
u64 i;
phys_addr_t this_start, this_end;
for_each_free_mem_range(i, NUMA_NO_NODE, MEMBLOCK_NONE, &this_start,
&this_end, NULL) {
this_start = clamp(this_start, start, end);
this_end = clamp(this_end, start, end);
if (this_start < this_end) {
pr_info(" %pa - %pa pattern %016llx\n",
&this_start, &this_end, cpu_to_be64(pattern));
memtest(pattern, this_start, this_end - this_start);
}
}
}
/* default is disabled */
static unsigned int memtest_pattern __initdata;
static int __init parse_memtest(char *arg)
{
int ret = 0;
if (arg)
ret = kstrtouint(arg, 0, &memtest_pattern);
else
memtest_pattern = ARRAY_SIZE(patterns);
return ret;
}
early_param("memtest", parse_memtest);
void __init early_memtest(phys_addr_t start, phys_addr_t end)
{
unsigned int i;
unsigned int idx = 0;
if (!memtest_pattern)
return;
pr_info("early_memtest: # of tests: %u\n", memtest_pattern);
for (i = memtest_pattern-1; i < UINT_MAX; --i) {
idx = i % ARRAY_SIZE(patterns);
do_one_pass(patterns[idx], start, end);
}
}
| {
"pile_set_name": "Github"
} |
/* (c) 2002-2003 by Marcin Wiacek and Michal Cihar */
#include <gammu-error.h>
#include <gammu-statemachine.h>
#include "common.h"
typedef enum {
H_Call = 1,
H_SMS,
H_Memory,
H_Filesystem,
H_Logo,
H_Ringtone,
H_Calendar,
H_ToDo,
H_Note,
H_DateTime,
H_Category,
H_Tests,
#ifdef GSM_ENABLE_BACKUP
H_Backup,
#endif
#if defined(GSM_ENABLE_NOKIA_DCT3) || defined(GSM_ENABLE_NOKIA_DCT4)
H_Nokia,
#endif
#ifdef GSM_ENABLE_AT
H_Siemens,
#endif
H_Network,
H_WAP,
H_MMS,
H_FM,
H_Info,
H_Settings,
#ifdef DEBUG
H_Decode,
#endif
H_Gammu,
H_Obsolete,
H_Other
} HelpCategory;
typedef struct {
HelpCategory category;
const char *option;
const char *description;
} HelpCategoryDescriptions;
typedef struct {
const char *parameter;
int min_arg;
int max_arg;
void (*Function) (int argc, char *argv[]);
HelpCategory help_cat[10];
const char *help;
} GSM_Parameters;
/* How should editor hadle tabs in this file? Add editor commands here.
* vim: noexpandtab sw=8 ts=8 sts=8:
*/
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Mirakel is an Android App for managing your ToDo-Lists
*
* Copyright (c) 2013-2015 Anatolij Zelenin, Georg Semmler.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package de.azapps.mirakel.settings.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import org.sufficientlysecure.donations.DonationsFragment;
import de.azapps.mirakel.helper.AnalyticsWrapperBase;
import de.azapps.mirakel.settings.custom_views.Settings;
import de.azapps.mirakel.settings.model_settings.generic_list.IDetailFragment;
public class DonationFragmentWrapper extends DonationsFragment implements
IDetailFragment<Settings> {
@NonNull
@Override
public Settings getItem() {
return Settings.DONATE;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (((AppCompatActivity)getActivity()).getSupportActionBar() != null) {
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getItem().getName());
}
}
@Override
public void onResume() {
super.onResume();
AnalyticsWrapperBase.setScreen(this);
}
@NonNull
public static Fragment newInstance() {
return new DonationFragmentWrapper();
}
}
| {
"pile_set_name": "Github"
} |
/*
* Shared Atheros AR9170 Header
*
* RX/TX meta descriptor format
*
* Copyright 2008, Johannes Berg <[email protected]>
* Copyright 2009-2011 Christian Lamparter <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, see
* http://www.gnu.org/licenses/.
*
* This file incorporates work covered by the following copyright and
* permission notice:
* Copyright (c) 2007-2008 Atheros Communications, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef __CARL9170_SHARED_WLAN_H
#define __CARL9170_SHARED_WLAN_H
#include "fwcmd.h"
#define AR9170_RX_PHY_RATE_CCK_1M 0x0a
#define AR9170_RX_PHY_RATE_CCK_2M 0x14
#define AR9170_RX_PHY_RATE_CCK_5M 0x37
#define AR9170_RX_PHY_RATE_CCK_11M 0x6e
#define AR9170_ENC_ALG_NONE 0x0
#define AR9170_ENC_ALG_WEP64 0x1
#define AR9170_ENC_ALG_TKIP 0x2
#define AR9170_ENC_ALG_AESCCMP 0x4
#define AR9170_ENC_ALG_WEP128 0x5
#define AR9170_ENC_ALG_WEP256 0x6
#define AR9170_ENC_ALG_CENC 0x7
#define AR9170_RX_ENC_SOFTWARE 0x8
#define AR9170_RX_STATUS_MODULATION 0x03
#define AR9170_RX_STATUS_MODULATION_S 0
#define AR9170_RX_STATUS_MODULATION_CCK 0x00
#define AR9170_RX_STATUS_MODULATION_OFDM 0x01
#define AR9170_RX_STATUS_MODULATION_HT 0x02
#define AR9170_RX_STATUS_MODULATION_DUPOFDM 0x03
/* depends on modulation */
#define AR9170_RX_STATUS_SHORT_PREAMBLE 0x08
#define AR9170_RX_STATUS_GREENFIELD 0x08
#define AR9170_RX_STATUS_MPDU 0x30
#define AR9170_RX_STATUS_MPDU_S 4
#define AR9170_RX_STATUS_MPDU_SINGLE 0x00
#define AR9170_RX_STATUS_MPDU_FIRST 0x20
#define AR9170_RX_STATUS_MPDU_MIDDLE 0x30
#define AR9170_RX_STATUS_MPDU_LAST 0x10
#define AR9170_RX_STATUS_CONT_AGGR 0x40
#define AR9170_RX_STATUS_TOTAL_ERROR 0x80
#define AR9170_RX_ERROR_RXTO 0x01
#define AR9170_RX_ERROR_OVERRUN 0x02
#define AR9170_RX_ERROR_DECRYPT 0x04
#define AR9170_RX_ERROR_FCS 0x08
#define AR9170_RX_ERROR_WRONG_RA 0x10
#define AR9170_RX_ERROR_PLCP 0x20
#define AR9170_RX_ERROR_MMIC 0x40
/* these are either-or */
#define AR9170_TX_MAC_PROT_RTS 0x0001
#define AR9170_TX_MAC_PROT_CTS 0x0002
#define AR9170_TX_MAC_PROT 0x0003
#define AR9170_TX_MAC_NO_ACK 0x0004
/* if unset, MAC will only do SIFS space before frame */
#define AR9170_TX_MAC_BACKOFF 0x0008
#define AR9170_TX_MAC_BURST 0x0010
#define AR9170_TX_MAC_AGGR 0x0020
/* encryption is a two-bit field */
#define AR9170_TX_MAC_ENCR_NONE 0x0000
#define AR9170_TX_MAC_ENCR_RC4 0x0040
#define AR9170_TX_MAC_ENCR_CENC 0x0080
#define AR9170_TX_MAC_ENCR_AES 0x00c0
#define AR9170_TX_MAC_MMIC 0x0100
#define AR9170_TX_MAC_HW_DURATION 0x0200
#define AR9170_TX_MAC_QOS_S 10
#define AR9170_TX_MAC_QOS 0x0c00
#define AR9170_TX_MAC_DISABLE_TXOP 0x1000
#define AR9170_TX_MAC_TXOP_RIFS 0x2000
#define AR9170_TX_MAC_IMM_BA 0x4000
/* either-or */
#define AR9170_TX_PHY_MOD_CCK 0x00000000
#define AR9170_TX_PHY_MOD_OFDM 0x00000001
#define AR9170_TX_PHY_MOD_HT 0x00000002
/* depends on modulation */
#define AR9170_TX_PHY_SHORT_PREAMBLE 0x00000004
#define AR9170_TX_PHY_GREENFIELD 0x00000004
#define AR9170_TX_PHY_BW_S 3
#define AR9170_TX_PHY_BW (3 << AR9170_TX_PHY_BW_SHIFT)
#define AR9170_TX_PHY_BW_20MHZ 0
#define AR9170_TX_PHY_BW_40MHZ 2
#define AR9170_TX_PHY_BW_40MHZ_DUP 3
#define AR9170_TX_PHY_TX_HEAVY_CLIP_S 6
#define AR9170_TX_PHY_TX_HEAVY_CLIP (7 << \
AR9170_TX_PHY_TX_HEAVY_CLIP_S)
#define AR9170_TX_PHY_TX_PWR_S 9
#define AR9170_TX_PHY_TX_PWR (0x3f << \
AR9170_TX_PHY_TX_PWR_S)
#define AR9170_TX_PHY_TXCHAIN_S 15
#define AR9170_TX_PHY_TXCHAIN (7 << \
AR9170_TX_PHY_TXCHAIN_S)
#define AR9170_TX_PHY_TXCHAIN_1 1
/* use for cck, ofdm 6/9/12/18/24 and HT if capable */
#define AR9170_TX_PHY_TXCHAIN_2 5
#define AR9170_TX_PHY_MCS_S 18
#define AR9170_TX_PHY_MCS (0x7f << \
AR9170_TX_PHY_MCS_S)
#define AR9170_TX_PHY_RATE_CCK_1M 0x0
#define AR9170_TX_PHY_RATE_CCK_2M 0x1
#define AR9170_TX_PHY_RATE_CCK_5M 0x2
#define AR9170_TX_PHY_RATE_CCK_11M 0x3
/* same as AR9170_RX_PHY_RATE */
#define AR9170_TXRX_PHY_RATE_OFDM_6M 0xb
#define AR9170_TXRX_PHY_RATE_OFDM_9M 0xf
#define AR9170_TXRX_PHY_RATE_OFDM_12M 0xa
#define AR9170_TXRX_PHY_RATE_OFDM_18M 0xe
#define AR9170_TXRX_PHY_RATE_OFDM_24M 0x9
#define AR9170_TXRX_PHY_RATE_OFDM_36M 0xd
#define AR9170_TXRX_PHY_RATE_OFDM_48M 0x8
#define AR9170_TXRX_PHY_RATE_OFDM_54M 0xc
#define AR9170_TXRX_PHY_RATE_HT_MCS0 0x0
#define AR9170_TXRX_PHY_RATE_HT_MCS1 0x1
#define AR9170_TXRX_PHY_RATE_HT_MCS2 0x2
#define AR9170_TXRX_PHY_RATE_HT_MCS3 0x3
#define AR9170_TXRX_PHY_RATE_HT_MCS4 0x4
#define AR9170_TXRX_PHY_RATE_HT_MCS5 0x5
#define AR9170_TXRX_PHY_RATE_HT_MCS6 0x6
#define AR9170_TXRX_PHY_RATE_HT_MCS7 0x7
#define AR9170_TXRX_PHY_RATE_HT_MCS8 0x8
#define AR9170_TXRX_PHY_RATE_HT_MCS9 0x9
#define AR9170_TXRX_PHY_RATE_HT_MCS10 0xa
#define AR9170_TXRX_PHY_RATE_HT_MCS11 0xb
#define AR9170_TXRX_PHY_RATE_HT_MCS12 0xc
#define AR9170_TXRX_PHY_RATE_HT_MCS13 0xd
#define AR9170_TXRX_PHY_RATE_HT_MCS14 0xe
#define AR9170_TXRX_PHY_RATE_HT_MCS15 0xf
#define AR9170_TX_PHY_SHORT_GI 0x80000000
#ifdef __CARL9170FW__
struct ar9170_tx_hw_mac_control {
union {
struct {
/*
* Beware of compiler bugs in all gcc pre 4.4!
*/
u8 erp_prot:2;
u8 no_ack:1;
u8 backoff:1;
u8 burst:1;
u8 ampdu:1;
u8 enc_mode:2;
u8 hw_mmic:1;
u8 hw_duration:1;
u8 qos_queue:2;
u8 disable_txop:1;
u8 txop_rifs:1;
u8 ba_end:1;
u8 probe:1;
} __packed;
__le16 set;
} __packed;
} __packed;
struct ar9170_tx_hw_phy_control {
union {
struct {
/*
* Beware of compiler bugs in all gcc pre 4.4!
*/
u8 modulation:2;
u8 preamble:1;
u8 bandwidth:2;
u8:1;
u8 heavy_clip:3;
u8 tx_power:6;
u8 chains:3;
u8 mcs:7;
u8:6;
u8 short_gi:1;
} __packed;
__le32 set;
} __packed;
} __packed;
struct ar9170_tx_rate_info {
u8 tries:3;
u8 erp_prot:2;
u8 ampdu:1;
u8 free:2; /* free for use (e.g.:RIFS/TXOP/AMPDU) */
} __packed;
struct carl9170_tx_superdesc {
__le16 len;
u8 rix;
u8 cnt;
u8 cookie;
u8 ampdu_density:3;
u8 ampdu_factor:2;
u8 ampdu_commit_density:1;
u8 ampdu_commit_factor:1;
u8 ampdu_unused_bit:1;
u8 queue:2;
u8 assign_seq:1;
u8 vif_id:3;
u8 fill_in_tsf:1;
u8 cab:1;
u8 padding2;
struct ar9170_tx_rate_info ri[CARL9170_TX_MAX_RATES];
struct ar9170_tx_hw_phy_control rr[CARL9170_TX_MAX_RETRY_RATES];
} __packed;
struct ar9170_tx_hwdesc {
__le16 length;
struct ar9170_tx_hw_mac_control mac;
struct ar9170_tx_hw_phy_control phy;
} __packed;
struct ar9170_tx_frame {
struct ar9170_tx_hwdesc hdr;
union {
struct ieee80211_hdr i3e;
u8 payload[0];
} data;
} __packed;
struct carl9170_tx_superframe {
struct carl9170_tx_superdesc s;
struct ar9170_tx_frame f;
} __packed __aligned(4);
#endif /* __CARL9170FW__ */
struct _ar9170_tx_hwdesc {
__le16 length;
__le16 mac_control;
__le32 phy_control;
} __packed;
#define CARL9170_TX_SUPER_AMPDU_DENSITY_S 0
#define CARL9170_TX_SUPER_AMPDU_DENSITY 0x7
#define CARL9170_TX_SUPER_AMPDU_FACTOR 0x18
#define CARL9170_TX_SUPER_AMPDU_FACTOR_S 3
#define CARL9170_TX_SUPER_AMPDU_COMMIT_DENSITY 0x20
#define CARL9170_TX_SUPER_AMPDU_COMMIT_DENSITY_S 5
#define CARL9170_TX_SUPER_AMPDU_COMMIT_FACTOR 0x40
#define CARL9170_TX_SUPER_AMPDU_COMMIT_FACTOR_S 6
#define CARL9170_TX_SUPER_MISC_QUEUE 0x3
#define CARL9170_TX_SUPER_MISC_QUEUE_S 0
#define CARL9170_TX_SUPER_MISC_ASSIGN_SEQ 0x4
#define CARL9170_TX_SUPER_MISC_VIF_ID 0x38
#define CARL9170_TX_SUPER_MISC_VIF_ID_S 3
#define CARL9170_TX_SUPER_MISC_FILL_IN_TSF 0x40
#define CARL9170_TX_SUPER_MISC_CAB 0x80
#define CARL9170_TX_SUPER_RI_TRIES 0x7
#define CARL9170_TX_SUPER_RI_TRIES_S 0
#define CARL9170_TX_SUPER_RI_ERP_PROT 0x18
#define CARL9170_TX_SUPER_RI_ERP_PROT_S 3
#define CARL9170_TX_SUPER_RI_AMPDU 0x20
#define CARL9170_TX_SUPER_RI_AMPDU_S 5
struct _carl9170_tx_superdesc {
__le16 len;
u8 rix;
u8 cnt;
u8 cookie;
u8 ampdu_settings;
u8 misc;
u8 padding;
u8 ri[CARL9170_TX_MAX_RATES];
__le32 rr[CARL9170_TX_MAX_RETRY_RATES];
} __packed;
struct _carl9170_tx_superframe {
struct _carl9170_tx_superdesc s;
struct _ar9170_tx_hwdesc f;
u8 frame_data[0];
} __packed __aligned(4);
#define CARL9170_TX_SUPERDESC_LEN 24
#define AR9170_TX_HWDESC_LEN 8
#define CARL9170_TX_SUPERFRAME_LEN (CARL9170_TX_SUPERDESC_LEN + \
AR9170_TX_HWDESC_LEN)
struct ar9170_rx_head {
u8 plcp[12];
} __packed;
#define AR9170_RX_HEAD_LEN 12
struct ar9170_rx_phystatus {
union {
struct {
u8 rssi_ant0, rssi_ant1, rssi_ant2,
rssi_ant0x, rssi_ant1x, rssi_ant2x,
rssi_combined;
} __packed;
u8 rssi[7];
} __packed;
u8 evm_stream0[6], evm_stream1[6];
u8 phy_err;
} __packed;
#define AR9170_RX_PHYSTATUS_LEN 20
struct ar9170_rx_macstatus {
u8 SAidx, DAidx;
u8 error;
u8 status;
} __packed;
#define AR9170_RX_MACSTATUS_LEN 4
struct ar9170_rx_frame_single {
struct ar9170_rx_head phy_head;
struct ieee80211_hdr i3e;
struct ar9170_rx_phystatus phy_tail;
struct ar9170_rx_macstatus macstatus;
} __packed;
struct ar9170_rx_frame_head {
struct ar9170_rx_head phy_head;
struct ieee80211_hdr i3e;
struct ar9170_rx_macstatus macstatus;
} __packed;
struct ar9170_rx_frame_middle {
struct ieee80211_hdr i3e;
struct ar9170_rx_macstatus macstatus;
} __packed;
struct ar9170_rx_frame_tail {
struct ieee80211_hdr i3e;
struct ar9170_rx_phystatus phy_tail;
struct ar9170_rx_macstatus macstatus;
} __packed;
struct ar9170_rx_frame {
union {
struct ar9170_rx_frame_single single;
struct ar9170_rx_frame_head head;
struct ar9170_rx_frame_middle middle;
struct ar9170_rx_frame_tail tail;
} __packed;
} __packed;
static inline u8 ar9170_get_decrypt_type(struct ar9170_rx_macstatus *t)
{
return (t->SAidx & 0xc0) >> 4 |
(t->DAidx & 0xc0) >> 6;
}
/*
* This is an workaround for several undocumented bugs.
* Don't mess with the QoS/AC <-> HW Queue map, if you don't
* know what you are doing.
*
* Known problems [hardware]:
* * The MAC does not aggregate frames on anything other
* than the first HW queue.
* * when an AMPDU is placed [in the first hw queue] and
* additional frames are already queued on a different
* hw queue, the MAC will ALWAYS freeze.
*
* In a nutshell: The hardware can either do QoS or
* Aggregation but not both at the same time. As a
* result, this makes the device pretty much useless
* for any serious 802.11n setup.
*/
enum ar9170_txq {
AR9170_TXQ_BK = 0, /* TXQ0 */
AR9170_TXQ_BE, /* TXQ1 */
AR9170_TXQ_VI, /* TXQ2 */
AR9170_TXQ_VO, /* TXQ3 */
__AR9170_NUM_TXQ,
};
#define AR9170_TXQ_DEPTH 32
#endif /* __CARL9170_SHARED_WLAN_H */
| {
"pile_set_name": "Github"
} |
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [email protected]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
| {
"pile_set_name": "Github"
} |
#!/bin/bash
#
# Jobscript for launching dcmip2012 test2-1 on the NERSC Cori machine
#
# usage: sbatch jobscript-...
#SBATCH -J d21-preqx # job name
#SBATCH -o out_dcmip2-1.o%j # output and error file name (%j expands to jobID)
#SBATCH -n 192 # total number of mpi tasks requested
#SBATCH -p debug # queue (partition) -- normal, development, etc.
#SBATCH -t 00:10:00 # run time (hh:mm:ss)
#SBATCH -A acme # charge hours to account 1
#SBATCH -C haswell # use Haswell nodes
date
EXEC=../../../test_execs/preqx-nlev60-interp/preqx-nlev60-interp # set name of executable
cp ./namelist-default.nl input.nl
srun -n 192 $EXEC < input.nl # launch simulation
ncl plot_lon_vs_z.ncl
date
| {
"pile_set_name": "Github"
} |
var pluginPath = [[NSBundle mainBundle] bundlePath] + "/Export for Origami.sketchplugin";
var pluginCode = [NSString stringWithContentsOfFile:pluginPath
encoding:NSUTF8StringEncoding
error:nil];
// Feed in script directly due to sandboxing
log([[[COScript app:"Sketch"] delegate] runPluginScript:pluginCode ]); | {
"pile_set_name": "Github"
} |
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
| {
"pile_set_name": "Github"
} |
Efektīvs reklāmu bloķētājs: nepārslogo procesoru un atmiņu, un var ielādēt un pielietot tūkstošiem filtru vairāk nekā citi populāri bloķētāji.
Ilustrēts apskats par tā efektivitāti: https://github.com/uBlockAdmin/uBlock/wiki/uBlock-vs.-ABP :-Efficiency-compared
Izmantošana: nospiediet lielo pogu uznirstošajā logā, lai izslēgtu/ieslēgtu uBlock pašreizējā web vietnē. Šī poga attiecas tikai uz pašreizējo tīmekļa vietni.
***
Elastīgs, tas ir vairāk nekā "reklāmu bloķētājs": tas var arī lasīt un izveidot filtrus no sistēmas hostu failiem.
Pēc noklusējuma, ielādē un izpilda šos filtru sarakstus:
- EasyList
- Peter Lowe’s Ad server list
- EasyPrivacy
- Malware domains
Ja vēlaties, ir pieejami daudz vairāk sarakstu, no kuriem jūs varat izvēlēties:
- Fanboy’s Enhanced Tracking List
- Dan Pollock’s hosts file
- hpHosts’s Ad and tracking servers
- MVPS HOSTS
- Spam404
- Un daudzi citi
Protams, jo vairāk papildus filtri tiks lietoti, jo lielāks atmiņas patēriņš. Tomēr pat pēc tam, kad pievienoti Fanboy divi papildu saraksti, hpHosts reklāmas un sekošanas serveriem, uBlock patērē mazāku atmiņas daudzumu, nekā citi populāri bloķētāji.
Arī jāapzinās, ka izvēloties dažus no šiem papildus sarakstiem, tas var izraisīt lielāku iespējamību, ka tīmekļa vietne tiks nepareizi parādīta — īpaši sarakstos, kurus parasti izmanto kā hosts failu.
***
Bez filtru sarakstiem, šis paplašinājums nav nekas. Tātad, ja vēlēsieties sniegt atbalstu, padomājiet par cilvēkiem, kas strādā, lai uzturētu filtru sarakstus, ko lietojat, tie ir pieejami lietošanai visiem par brīvu.
***
Bezmaksas.
Pirmkods ar publisko licenci (GPLv3)
Lietotājiem no lietotājiem.
Autori @ Github: https://github.com/uBlockAdmin/uBlock/graphs/contributors
Autori @ Crowdin: https://crowdin.net/project/ublock
***
Šī ir ļoti agrīna versija, paturiet to prātā, kad jūs to lietojat.
Projekta izmaiņu žurnāls:
https://github.com/uBlockAdmin/uBlock/releases
| {
"pile_set_name": "Github"
} |
class MessagesController < ApplicationController
before_action :set_message, only: %i[destroy update]
before_action :authenticate_user!, only: %i[create]
include MessagesHelper
def create
@message = Message.new(message_params)
@message.user_id = session_current_user_id
@temp_message_id = (0...20).map { ("a".."z").to_a[rand(8)] }.join
authorize @message
# sending temp message only to sender
pusher_message_created(true, @message, @temp_message_id)
if @message.save
pusher_message_created(false, @message, @temp_message_id)
notify_mentioned_users(@mentioned_users_id)
render json: { status: "success", message: { temp_id: @temp_message_id, id: @message.id } }, status: :created
else
render json: {
status: "error",
message: {
chat_channel_id: @message.chat_channel_id,
message: @message.errors.full_messages,
type: "error"
}
}, status: :unauthorized
end
end
def destroy
authorize @message
if @message.valid?
begin
Pusher.trigger(@message.chat_channel.pusher_channels, "message-deleted", @message.to_json)
rescue Pusher::Error => e
Honeybadger.notify(e)
end
end
if @message.destroy
render json: { status: "success", message: "Message was deleted" }
else
render json: {
status: "error",
message: {
chat_channel_id: @message.chat_channel_id,
message: @message.errors.full_messages,
type: "error"
}
}, status: :unauthorized
end
end
def update
authorize @message
if @message.update(permitted_attributes(@message).merge(edited_at: Time.zone.now))
if @message.valid?
begin
message_json = create_pusher_payload(@message, "")
Pusher.trigger(@message.chat_channel.pusher_channels, "message-edited", message_json)
rescue Pusher::Error => e
Honeybadger.notify(e)
end
end
render json: { status: "success", message: "Message was edited" }
else
render json: {
status: "error",
message: {
chat_channel_id: @message.chat_channel_id,
message: @message.errors.full_messages,
type: "error"
}
}, status: :unauthorized
end
end
private
def message_params
@mentioned_users_id = params[:message][:mentioned_users_id]
params.require(:message).permit(:message_markdown, :user_id, :chat_channel_id)
end
def set_message
@message = Message.find(params[:id])
end
def user_not_authorized
respond_to do |format|
format.json do
render json: {
status: "error",
message: {
chat_channel_id: message_params[:chat_channel_id],
message: "You can not do that because you are suspended",
type: "error"
}
}, status: :unauthorized
end
end
end
def notify_mentioned_users(user_ids)
# If @all is mentioned then we get an array of all of the channel's users IDs from the channel
# https://github.com/forem/forem/blob/9bdef4d4ae0b41612001a62c2409121b654bf71f/app/javascript/chat/chat.jsx#L1562
return unless user_ids
message_json = create_pusher_payload(@message, @temp_message_id)
user_ids.each do |id|
Pusher.trigger(ChatChannel.pm_notifications_channel(id), "mentioned", message_json)
end
end
end
| {
"pile_set_name": "Github"
} |
apiVersion: kafka.banzaicloud.io/v1beta1
kind: KafkaCluster
metadata:
finalizers:
- finalizer.kafkaclusters.kafka.banzaicloud.io
- topics.kafkaclusters.kafka.banzaicloud.io
- users.kafkaclusters.kafka.banzaicloud.io
generation: 4
labels:
argocd.argoproj.io/instance: kafka-cluster
controller-tools.k8s.io: "1.0"
name: kafkacluster
namespace: kafka
name: kafkacluster
namespace: kafka
resourceVersion: "31935335"
selfLink: /apis/kafka.banzaicloud.io/v1beta1/namespaces/2269-kafka/kafkaclusters/kafkacluster
uid: c6affef0-651d-44c7-8bff-638961517c8d
spec: {}
status:
alertCount: 0
brokersState:
"0":
configurationState: ConfigInSync
gracefulActionState:
cruiseControlState: GracefulUpscaleSucceeded
errorMessage: CruiseControl not yet ready
rackAwarenessState: |
broker.rack=us-east-1,us-east-1c
"1":
configurationState: ConfigInSync
gracefulActionState:
cruiseControlState: GracefulUpscaleSucceeded
errorMessage: CruiseControl not yet ready
rackAwarenessState: |
broker.rack=us-east-1,us-east-1b
"2":
configurationState: ConfigInSync
gracefulActionState:
cruiseControlState: GracefulUpscaleSucceeded
errorMessage: CruiseControl not yet ready
rackAwarenessState: |
broker.rack=us-east-1,us-east-1a
cruiseControlTopicStatus: ClusterRollingUpgrading
rollingUpgradeStatus:
errorCount: 0
lastSuccess: ""
state: ClusterRunning | {
"pile_set_name": "Github"
} |
//
// NSFileHandle+Additions.m
// gitty
//
// Created by brandon on 10/15/12.
//
//
#import "NSFileHandle+Additions.h"
@implementation NSFileHandle (Additions)
- (NSString *) readLine
{
NSData * newLineData = [@"\n" dataUsingEncoding:NSASCIIStringEncoding];
NSMutableData * currentData = [[[NSMutableData alloc] init] autorelease];
NSUInteger chunkSize = 1;
BOOL shouldReadMore = YES;
if ([self fileDescriptor] == -1)
return nil;
@autoreleasepool
{
@try
{
while (shouldReadMore)
{
NSData * chunk = [self readDataOfLength:chunkSize];
if (!chunk || [chunk length] == 0)
break;
NSRange newLineRange = [chunk rangeOfData:newLineData];
if (newLineRange.location != NSNotFound)
{
//include the length so we can include the delimiter in the string
chunk = [chunk subdataWithRange:NSMakeRange(0, newLineRange.location + [newLineData length])];
shouldReadMore = NO;
}
[currentData appendData:chunk];
}
}
@catch (NSException *exception)
{
currentData = nil;
}
}
if (!currentData || [currentData length] == 0)
return nil;
NSString * line = [[[NSString alloc] initWithData:currentData encoding:NSASCIIStringEncoding] autorelease];
return line;
}
@end
| {
"pile_set_name": "Github"
} |
class UmpleToRuby {
attribute_GetDefaultedCodeInjection <<!<</*attribute_GetDefaultedCodeInjection*/>>
def <<=gen.translate("getDefaultMethod",av)>>
<<# if (customGetDefaultPrefixCode != null) { append(realSb, "\n{0}",GeneratorHelper.doIndent(customGetDefaultPrefixCode, " ")); } #>>
<<=gen.translate("parameterOne",av)>> = <<= gen.translate("parameterValue",av) >>
<<# if (customGetDefaultPostfixCode != null) { append(realSb, "\n{0}",GeneratorHelper.doIndent(customGetDefaultPostfixCode, " ")); } #>>
<<=gen.translate("parameterOne",av)>>
end
!>>
}
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright (c) 2012 VMware, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* VMware, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.config.ui.editors.integration.graph.model;
import java.util.Arrays;
import java.util.List;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement;
import org.springframework.ide.eclipse.config.core.schemas.IntegrationSchemaConstants;
import org.springframework.ide.eclipse.config.graph.model.AbstractConfigGraphDiagram;
import org.springframework.ide.eclipse.config.graph.model.Activity;
/**
* @author Leo Dos Santos
*/
@SuppressWarnings("restriction")
public class ControlBusModelElement extends Activity {
public ControlBusModelElement() {
super();
}
public ControlBusModelElement(IDOMElement input, AbstractConfigGraphDiagram diagram) {
super(input, diagram);
}
@Override
public String getInputName() {
return IntegrationSchemaConstants.ELEM_CONTROL_BUS;
}
@Override
public List<String> getPrimaryIncomingAttributes() {
return Arrays.asList(IntegrationSchemaConstants.ATTR_INPUT_CHANNEL);
}
@Override
public List<String> getPrimaryOutgoingAttributes() {
return Arrays.asList(IntegrationSchemaConstants.ATTR_OUTPUT_CHANNEL);
}
}
| {
"pile_set_name": "Github"
} |
/**
* @file src/fileinfo/file_presentation/getters/iterative_getter/iterative_simple_getter/iterative_simple_getter.h
* @brief Definition of IterativeSimpleGetter class.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#ifndef FILEINFO_FILE_PRESENTATION_GETTERS_ITERATIVE_GETTER_ITERATIVE_SIMPLE_GETTER_ITERATIVE_SIMPLE_GETTER_H
#define FILEINFO_FILE_PRESENTATION_GETTERS_ITERATIVE_GETTER_ITERATIVE_SIMPLE_GETTER_ITERATIVE_SIMPLE_GETTER_H
#include "fileinfo/file_presentation/getters/iterative_getter/iterative_getter.h"
namespace retdec {
namespace fileinfo {
/**
* Abstract class for loading information about file.
*
* This class enable iterative queries to a set of items
* (e.g. queries to symbols from symbol tables).
*/
class IterativeSimpleGetter : public IterativeGetter
{
protected:
std::string elementHeader; ///< header for every presented structure
public:
IterativeSimpleGetter(FileInformation &fileInfo);
/// @name Getters
/// @{
void getElementHeader(std::string &elemHeader) const;
/// @}
/// @name Pure virtual methods
/// @{
virtual bool getFlags(std::size_t structIndex, std::size_t recIndex, std::string &flagsValue, std::vector<std::string> &desc) const = 0;
/// @}
};
} // namespace fileinfo
} // namespace retdec
#endif
| {
"pile_set_name": "Github"
} |
{
"name": "DWM rob",
"author": "",
"color": [
"#151515",
"#bf7979",
"#97b26b",
"#cdcda1",
"#4a5463",
"#9c3885",
"#88aadd",
"#ffffff",
"#505450",
"#f4a45f",
"#c5f779",
"#ffffaf",
"#7d8794",
"#e628ba",
"#99ccff",
"#dedede"
],
"foreground": "#ffffff",
"background": "#000000"
}
| {
"pile_set_name": "Github"
} |
require 'rubygems'
require 'tach'
key = 'Content-Length'
value = '100'
Tach.meter(1_000) do
tach('concat') do
temp = ''
temp << key << ': ' << value << "\r\n"
end
tach('interpolate') do
"#{key}: #{value}\r\n"
end
end
# +-------------+----------+
# | tach | total |
# +-------------+----------+
# | interpolate | 0.000404 |
# +-------------+----------+
# | concat | 0.000564 |
# +-------------+----------+
| {
"pile_set_name": "Github"
} |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2019 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#if SDL_VIDEO_DRIVER_WINDOWS
#include "SDL_assert.h"
#include "SDL_windowsshape.h"
#include "SDL_windowsvideo.h"
SDL_WindowShaper*
Win32_CreateShaper(SDL_Window * window) {
int resized_properly;
SDL_WindowShaper* result = (SDL_WindowShaper *)SDL_malloc(sizeof(SDL_WindowShaper));
result->window = window;
result->mode.mode = ShapeModeDefault;
result->mode.parameters.binarizationCutoff = 1;
result->userx = result->usery = 0;
result->driverdata = (SDL_ShapeData*)SDL_malloc(sizeof(SDL_ShapeData));
((SDL_ShapeData*)result->driverdata)->mask_tree = NULL;
/* Put some driver-data here. */
window->shaper = result;
resized_properly = Win32_ResizeWindowShape(window);
if (resized_properly != 0)
return NULL;
return result;
}
static void
CombineRectRegions(SDL_ShapeTree* node,void* closure) {
HRGN mask_region = *((HRGN*)closure),temp_region = NULL;
if(node->kind == OpaqueShape) {
/* Win32 API regions exclude their outline, so we widen the region by one pixel in each direction to include the real outline. */
temp_region = CreateRectRgn(node->data.shape.x,node->data.shape.y,node->data.shape.x + node->data.shape.w + 1,node->data.shape.y + node->data.shape.h + 1);
if(mask_region != NULL) {
CombineRgn(mask_region,mask_region,temp_region,RGN_OR);
DeleteObject(temp_region);
}
else
*((HRGN*)closure) = temp_region;
}
}
int
Win32_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode) {
SDL_ShapeData *data;
HRGN mask_region = NULL;
if( (shaper == NULL) ||
(shape == NULL) ||
((shape->format->Amask == 0) && (shape_mode->mode != ShapeModeColorKey)) ||
(shape->w != shaper->window->w) ||
(shape->h != shaper->window->h) ) {
return SDL_INVALID_SHAPE_ARGUMENT;
}
data = (SDL_ShapeData*)shaper->driverdata;
if(data->mask_tree != NULL)
SDL_FreeShapeTree(&data->mask_tree);
data->mask_tree = SDL_CalculateShapeTree(*shape_mode,shape);
SDL_TraverseShapeTree(data->mask_tree,&CombineRectRegions,&mask_region);
SDL_assert(mask_region != NULL);
SetWindowRgn(((SDL_WindowData *)(shaper->window->driverdata))->hwnd, mask_region, TRUE);
return 0;
}
int
Win32_ResizeWindowShape(SDL_Window *window) {
SDL_ShapeData* data;
if (window == NULL)
return -1;
data = (SDL_ShapeData *)window->shaper->driverdata;
if (data == NULL)
return -1;
if(data->mask_tree != NULL)
SDL_FreeShapeTree(&data->mask_tree);
if(window->shaper->hasshape == SDL_TRUE) {
window->shaper->userx = window->x;
window->shaper->usery = window->y;
SDL_SetWindowPosition(window,-1000,-1000);
}
return 0;
}
#endif /* SDL_VIDEO_DRIVER_WINDOWS */
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0 */
/*
* es8328.h -- ES8328 ALSA SoC Audio driver
*/
#ifndef _ES8328_H
#define _ES8328_H
#include <linux/regmap.h>
struct device;
extern const struct regmap_config es8328_regmap_config;
int es8328_probe(struct device *dev, struct regmap *regmap);
#define ES8328_DACLVOL 46
#define ES8328_DACRVOL 47
#define ES8328_DACCTL 28
#define ES8328_RATEMASK (0x1f << 0)
#define ES8328_CONTROL1 0x00
#define ES8328_CONTROL1_VMIDSEL_OFF (0 << 0)
#define ES8328_CONTROL1_VMIDSEL_50k (1 << 0)
#define ES8328_CONTROL1_VMIDSEL_500k (2 << 0)
#define ES8328_CONTROL1_VMIDSEL_5k (3 << 0)
#define ES8328_CONTROL1_VMIDSEL_MASK (3 << 0)
#define ES8328_CONTROL1_ENREF (1 << 2)
#define ES8328_CONTROL1_SEQEN (1 << 3)
#define ES8328_CONTROL1_SAMEFS (1 << 4)
#define ES8328_CONTROL1_DACMCLK_ADC (0 << 5)
#define ES8328_CONTROL1_DACMCLK_DAC (1 << 5)
#define ES8328_CONTROL1_LRCM (1 << 6)
#define ES8328_CONTROL1_SCP_RESET (1 << 7)
#define ES8328_CONTROL2 0x01
#define ES8328_CONTROL2_VREF_BUF_OFF (1 << 0)
#define ES8328_CONTROL2_VREF_LOWPOWER (1 << 1)
#define ES8328_CONTROL2_IBIASGEN_OFF (1 << 2)
#define ES8328_CONTROL2_ANALOG_OFF (1 << 3)
#define ES8328_CONTROL2_VREF_BUF_LOWPOWER (1 << 4)
#define ES8328_CONTROL2_VCM_MOD_LOWPOWER (1 << 5)
#define ES8328_CONTROL2_OVERCURRENT_ON (1 << 6)
#define ES8328_CONTROL2_THERMAL_SHUTDOWN_ON (1 << 7)
#define ES8328_CHIPPOWER 0x02
#define ES8328_CHIPPOWER_DACVREF_OFF 0
#define ES8328_CHIPPOWER_ADCVREF_OFF 1
#define ES8328_CHIPPOWER_DACDLL_OFF 2
#define ES8328_CHIPPOWER_ADCDLL_OFF 3
#define ES8328_CHIPPOWER_DACSTM_RESET 4
#define ES8328_CHIPPOWER_ADCSTM_RESET 5
#define ES8328_CHIPPOWER_DACDIG_OFF 6
#define ES8328_CHIPPOWER_ADCDIG_OFF 7
#define ES8328_ADCPOWER 0x03
#define ES8328_ADCPOWER_INT1_LOWPOWER 0
#define ES8328_ADCPOWER_FLASH_ADC_LOWPOWER 1
#define ES8328_ADCPOWER_ADC_BIAS_GEN_OFF 2
#define ES8328_ADCPOWER_MIC_BIAS_OFF 3
#define ES8328_ADCPOWER_ADCR_OFF 4
#define ES8328_ADCPOWER_ADCL_OFF 5
#define ES8328_ADCPOWER_AINR_OFF 6
#define ES8328_ADCPOWER_AINL_OFF 7
#define ES8328_DACPOWER 0x04
#define ES8328_DACPOWER_OUT3_ON 0
#define ES8328_DACPOWER_MONO_ON 1
#define ES8328_DACPOWER_ROUT2_ON 2
#define ES8328_DACPOWER_LOUT2_ON 3
#define ES8328_DACPOWER_ROUT1_ON 4
#define ES8328_DACPOWER_LOUT1_ON 5
#define ES8328_DACPOWER_RDAC_OFF 6
#define ES8328_DACPOWER_LDAC_OFF 7
#define ES8328_CHIPLOPOW1 0x05
#define ES8328_CHIPLOPOW2 0x06
#define ES8328_ANAVOLMANAG 0x07
#define ES8328_MASTERMODE 0x08
#define ES8328_MASTERMODE_BCLKDIV (0 << 0)
#define ES8328_MASTERMODE_BCLK_INV (1 << 5)
#define ES8328_MASTERMODE_MCLKDIV2 (1 << 6)
#define ES8328_MASTERMODE_MSC (1 << 7)
#define ES8328_ADCCONTROL1 0x09
#define ES8328_ADCCONTROL2 0x0a
#define ES8328_ADCCONTROL3 0x0b
#define ES8328_ADCCONTROL4 0x0c
#define ES8328_ADCCONTROL4_ADCFORMAT_MASK (3 << 0)
#define ES8328_ADCCONTROL4_ADCFORMAT_I2S (0 << 0)
#define ES8328_ADCCONTROL4_ADCFORMAT_LJUST (1 << 0)
#define ES8328_ADCCONTROL4_ADCFORMAT_RJUST (2 << 0)
#define ES8328_ADCCONTROL4_ADCFORMAT_PCM (3 << 0)
#define ES8328_ADCCONTROL4_ADCWL_SHIFT 2
#define ES8328_ADCCONTROL4_ADCWL_MASK (7 << 2)
#define ES8328_ADCCONTROL4_ADCLRP_I2S_POL_NORMAL (0 << 5)
#define ES8328_ADCCONTROL4_ADCLRP_I2S_POL_INV (1 << 5)
#define ES8328_ADCCONTROL4_ADCLRP_PCM_MSB_CLK2 (0 << 5)
#define ES8328_ADCCONTROL4_ADCLRP_PCM_MSB_CLK1 (1 << 5)
#define ES8328_ADCCONTROL5 0x0d
#define ES8328_ADCCONTROL5_RATEMASK (0x1f << 0)
#define ES8328_ADCCONTROL6 0x0e
#define ES8328_ADCCONTROL7 0x0f
#define ES8328_ADCCONTROL7_ADC_MUTE (1 << 2)
#define ES8328_ADCCONTROL7_ADC_LER (1 << 3)
#define ES8328_ADCCONTROL7_ADC_ZERO_CROSS (1 << 4)
#define ES8328_ADCCONTROL7_ADC_SOFT_RAMP (1 << 5)
#define ES8328_ADCCONTROL7_ADC_RAMP_RATE_4 (0 << 6)
#define ES8328_ADCCONTROL7_ADC_RAMP_RATE_8 (1 << 6)
#define ES8328_ADCCONTROL7_ADC_RAMP_RATE_16 (2 << 6)
#define ES8328_ADCCONTROL7_ADC_RAMP_RATE_32 (3 << 6)
#define ES8328_ADCCONTROL8 0x10
#define ES8328_ADCCONTROL9 0x11
#define ES8328_ADCCONTROL10 0x12
#define ES8328_ADCCONTROL11 0x13
#define ES8328_ADCCONTROL12 0x14
#define ES8328_ADCCONTROL13 0x15
#define ES8328_ADCCONTROL14 0x16
#define ES8328_DACCONTROL1 0x17
#define ES8328_DACCONTROL1_DACFORMAT_MASK (3 << 1)
#define ES8328_DACCONTROL1_DACFORMAT_I2S (0 << 1)
#define ES8328_DACCONTROL1_DACFORMAT_LJUST (1 << 1)
#define ES8328_DACCONTROL1_DACFORMAT_RJUST (2 << 1)
#define ES8328_DACCONTROL1_DACFORMAT_PCM (3 << 1)
#define ES8328_DACCONTROL1_DACWL_SHIFT 3
#define ES8328_DACCONTROL1_DACWL_MASK (7 << 3)
#define ES8328_DACCONTROL1_DACLRP_I2S_POL_NORMAL (0 << 6)
#define ES8328_DACCONTROL1_DACLRP_I2S_POL_INV (1 << 6)
#define ES8328_DACCONTROL1_DACLRP_PCM_MSB_CLK2 (0 << 6)
#define ES8328_DACCONTROL1_DACLRP_PCM_MSB_CLK1 (1 << 6)
#define ES8328_DACCONTROL1_LRSWAP (1 << 7)
#define ES8328_DACCONTROL2 0x18
#define ES8328_DACCONTROL2_RATEMASK (0x1f << 0)
#define ES8328_DACCONTROL2_DOUBLESPEED (1 << 5)
#define ES8328_DACCONTROL3 0x19
#define ES8328_DACCONTROL3_AUTOMUTE (1 << 2)
#define ES8328_DACCONTROL3_DACMUTE (1 << 2)
#define ES8328_DACCONTROL3_LEFTGAINVOL (1 << 3)
#define ES8328_DACCONTROL3_DACZEROCROSS (1 << 4)
#define ES8328_DACCONTROL3_DACSOFTRAMP (1 << 5)
#define ES8328_DACCONTROL3_DACRAMPRATE (3 << 6)
#define ES8328_LDACVOL 0x1a
#define ES8328_LDACVOL_MASK (0 << 0)
#define ES8328_LDACVOL_MAX (0xc0)
#define ES8328_RDACVOL 0x1b
#define ES8328_RDACVOL_MASK (0 << 0)
#define ES8328_RDACVOL_MAX (0xc0)
#define ES8328_DACVOL_MAX (0xc0)
#define ES8328_DACCONTROL4 0x1a
#define ES8328_DACCONTROL5 0x1b
#define ES8328_DACCONTROL6 0x1c
#define ES8328_DACCONTROL6_CLICKFREE (1 << 3)
#define ES8328_DACCONTROL6_DAC_INVR (1 << 4)
#define ES8328_DACCONTROL6_DAC_INVL (1 << 5)
#define ES8328_DACCONTROL6_DEEMPH_MASK (3 << 6)
#define ES8328_DACCONTROL6_DEEMPH_OFF (0 << 6)
#define ES8328_DACCONTROL6_DEEMPH_32k (1 << 6)
#define ES8328_DACCONTROL6_DEEMPH_44_1k (2 << 6)
#define ES8328_DACCONTROL6_DEEMPH_48k (3 << 6)
#define ES8328_DACCONTROL7 0x1d
#define ES8328_DACCONTROL7_VPP_SCALE_3p5 (0 << 0)
#define ES8328_DACCONTROL7_VPP_SCALE_4p0 (1 << 0)
#define ES8328_DACCONTROL7_VPP_SCALE_3p0 (2 << 0)
#define ES8328_DACCONTROL7_VPP_SCALE_2p5 (3 << 0)
#define ES8328_DACCONTROL7_SHELVING_STRENGTH (1 << 2) /* In eights */
#define ES8328_DACCONTROL7_MONO (1 << 5)
#define ES8328_DACCONTROL7_ZEROR (1 << 6)
#define ES8328_DACCONTROL7_ZEROL (1 << 7)
/* Shelving filter */
#define ES8328_DACCONTROL8 0x1e
#define ES8328_DACCONTROL9 0x1f
#define ES8328_DACCONTROL10 0x20
#define ES8328_DACCONTROL11 0x21
#define ES8328_DACCONTROL12 0x22
#define ES8328_DACCONTROL13 0x23
#define ES8328_DACCONTROL14 0x24
#define ES8328_DACCONTROL15 0x25
#define ES8328_DACCONTROL16 0x26
#define ES8328_DACCONTROL16_RMIXSEL_RIN1 (0 << 0)
#define ES8328_DACCONTROL16_RMIXSEL_RIN2 (1 << 0)
#define ES8328_DACCONTROL16_RMIXSEL_RIN3 (2 << 0)
#define ES8328_DACCONTROL16_RMIXSEL_RADC (3 << 0)
#define ES8328_DACCONTROL16_LMIXSEL_LIN1 (0 << 3)
#define ES8328_DACCONTROL16_LMIXSEL_LIN2 (1 << 3)
#define ES8328_DACCONTROL16_LMIXSEL_LIN3 (2 << 3)
#define ES8328_DACCONTROL16_LMIXSEL_LADC (3 << 3)
#define ES8328_DACCONTROL17 0x27
#define ES8328_DACCONTROL17_LI2LOVOL (7 << 3)
#define ES8328_DACCONTROL17_LI2LO (1 << 6)
#define ES8328_DACCONTROL17_LD2LO (1 << 7)
#define ES8328_DACCONTROL18 0x28
#define ES8328_DACCONTROL18_RI2LOVOL (7 << 3)
#define ES8328_DACCONTROL18_RI2LO (1 << 6)
#define ES8328_DACCONTROL18_RD2LO (1 << 7)
#define ES8328_DACCONTROL19 0x29
#define ES8328_DACCONTROL19_LI2ROVOL (7 << 3)
#define ES8328_DACCONTROL19_LI2RO (1 << 6)
#define ES8328_DACCONTROL19_LD2RO (1 << 7)
#define ES8328_DACCONTROL20 0x2a
#define ES8328_DACCONTROL20_RI2ROVOL (7 << 3)
#define ES8328_DACCONTROL20_RI2RO (1 << 6)
#define ES8328_DACCONTROL20_RD2RO (1 << 7)
#define ES8328_DACCONTROL21 0x2b
#define ES8328_DACCONTROL21_LI2MOVOL (7 << 3)
#define ES8328_DACCONTROL21_LI2MO (1 << 6)
#define ES8328_DACCONTROL21_LD2MO (1 << 7)
#define ES8328_DACCONTROL22 0x2c
#define ES8328_DACCONTROL22_RI2MOVOL (7 << 3)
#define ES8328_DACCONTROL22_RI2MO (1 << 6)
#define ES8328_DACCONTROL22_RD2MO (1 << 7)
#define ES8328_DACCONTROL23 0x2d
#define ES8328_DACCONTROL23_MOUTINV (1 << 1)
#define ES8328_DACCONTROL23_HPSWPOL (1 << 2)
#define ES8328_DACCONTROL23_HPSWEN (1 << 3)
#define ES8328_DACCONTROL23_VROI_1p5k (0 << 4)
#define ES8328_DACCONTROL23_VROI_40k (1 << 4)
#define ES8328_DACCONTROL23_OUT3_VREF (0 << 5)
#define ES8328_DACCONTROL23_OUT3_ROUT1 (1 << 5)
#define ES8328_DACCONTROL23_OUT3_MONOOUT (2 << 5)
#define ES8328_DACCONTROL23_OUT3_RIGHT_MIXER (3 << 5)
#define ES8328_DACCONTROL23_ROUT2INV (1 << 7)
/* LOUT1 Amplifier */
#define ES8328_LOUT1VOL 0x2e
#define ES8328_LOUT1VOL_MASK (0 << 5)
#define ES8328_LOUT1VOL_MAX (0x24)
/* ROUT1 Amplifier */
#define ES8328_ROUT1VOL 0x2f
#define ES8328_ROUT1VOL_MASK (0 << 5)
#define ES8328_ROUT1VOL_MAX (0x24)
#define ES8328_OUT1VOL_MAX (0x24)
/* LOUT2 Amplifier */
#define ES8328_LOUT2VOL 0x30
#define ES8328_LOUT2VOL_MASK (0 << 5)
#define ES8328_LOUT2VOL_MAX (0x24)
/* ROUT2 Amplifier */
#define ES8328_ROUT2VOL 0x31
#define ES8328_ROUT2VOL_MASK (0 << 5)
#define ES8328_ROUT2VOL_MAX (0x24)
#define ES8328_OUT2VOL_MAX (0x24)
/* Mono Out Amplifier */
#define ES8328_MONOOUTVOL 0x32
#define ES8328_MONOOUTVOL_MASK (0 << 5)
#define ES8328_MONOOUTVOL_MAX (0x24)
#define ES8328_DACCONTROL29 0x33
#define ES8328_DACCONTROL30 0x34
#define ES8328_SYSCLK 0
#define ES8328_REG_MAX 0x35
#define ES8328_1536FS 1536
#define ES8328_1024FS 1024
#define ES8328_768FS 768
#define ES8328_512FS 512
#define ES8328_384FS 384
#define ES8328_256FS 256
#define ES8328_128FS 128
#endif
| {
"pile_set_name": "Github"
} |
function testInterpreterReentry2() {
var a = false;
var b = {};
var c = false;
var d = {};
this.__defineGetter__('e', function(){});
for (let f in this) print(f);
[1 for each (g in this) for each (h in [])]
return 1;
}
assertEq(testInterpreterReentry2(), 1);
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "net/third_party/quiche/src/quic/core/frames/quic_goaway_frame.h"
namespace quic {
QuicGoAwayFrame::QuicGoAwayFrame(QuicControlFrameId control_frame_id,
QuicErrorCode error_code,
QuicStreamId last_good_stream_id,
const std::string& reason)
: control_frame_id(control_frame_id),
error_code(error_code),
last_good_stream_id(last_good_stream_id),
reason_phrase(reason) {}
std::ostream& operator<<(std::ostream& os,
const QuicGoAwayFrame& goaway_frame) {
os << "{ control_frame_id: " << goaway_frame.control_frame_id
<< ", error_code: " << goaway_frame.error_code
<< ", last_good_stream_id: " << goaway_frame.last_good_stream_id
<< ", reason_phrase: '" << goaway_frame.reason_phrase << "' }\n";
return os;
}
} // namespace quic
| {
"pile_set_name": "Github"
} |
/**
@author Dustin Neß (dness.de)
*/
func Definition(proplist def)
{
def.MeshTransformation = Trans_Scale(60);
}
public func Construction()
{
SetProperty("MeshTransformation", Trans_Mul(Trans_Rotate(RandomX(-35, 35),0, 10), GetID().MeshTransformation));
}
| {
"pile_set_name": "Github"
} |
lines columns q-benchmark-3.7.9_mean q-benchmark-3.7.9_stddev
1 1 0.08099310398101807 0.001417385651688644
10 1 0.0822291374206543 0.0014809900020001858
100 1 0.08169686794281006 0.002108157069167563
1000 1 0.08690853118896484 0.0012595326919263487
10000 1 0.12215542793273926 0.0020152625320395434
100000 1 0.4825761795043945 0.0050418000028856335
1000000 1 4.084399747848511 0.027731958079814215
lines columns q-benchmark-3.7.9_mean q-benchmark-3.7.9_stddev
1 5 0.0817826271057129 0.002665533758836163
10 5 0.08261749744415284 0.0019205430658525572
100 5 0.08472237586975098 0.002571239449841039
1000 5 0.08973510265350342 0.002323797583077552
10000 5 0.13746986389160157 0.001964971666036654
100000 5 0.60649254322052 0.007131635266871318
1000000 5 5.2585612535476685 0.05661789407928516
lines columns q-benchmark-3.7.9_mean q-benchmark-3.7.9_stddev
1 10 0.08112843036651611 0.002251300165899426
10 10 0.08175232410430908 0.0014557171018568637
100 10 0.08572309017181397 0.0019643550214810675
1000 10 0.09268453121185302 0.001816414236580489
10000 10 0.15538835525512695 0.0024978076091814994
100000 10 0.7879442930221557 0.009412516078916211
1000000 10 7.146207928657532 0.06659760176757985
lines columns q-benchmark-3.7.9_mean q-benchmark-3.7.9_stddev
1 20 0.08142082691192627 0.001304584466639188
10 20 0.08197519779205323 0.0014842098503865223
100 20 0.08949971199035645 0.0009937446141285785
1000 20 0.09955930709838867 0.0013978961740806384
10000 20 0.1966566801071167 0.0028489273218240147
100000 20 1.1518636226654053 0.006410720031542237
1000000 20 10.776052689552307 0.04739925571001746
lines columns q-benchmark-3.7.9_mean q-benchmark-3.7.9_stddev
1 50 0.08237688541412354 0.0016494314799953837
10 50 0.08519520759582519 0.002610550182895596
100 50 0.10423583984375 0.0018808335751867933
1000 50 0.12195603847503662 0.0023611894043373983
10000 50 0.3163540124893188 0.002761333651520998
100000 50 2.237372374534607 0.009955353920396077
1000000 50 21.59097549915314 0.081188190530421
lines columns q-benchmark-3.7.9_mean q-benchmark-3.7.9_stddev
1 100 0.08336784839630126 0.0013840724401561887
10 100 0.0864112138748169 0.0017946939354350697
100 100 0.12199611663818359 0.0013003743156634682
1000 100 0.15871686935424806 0.0035993681064501234
10000 100 0.5243751525878906 0.004370273273595629
100000 100 4.175828623771667 0.016127303710583043
1000000 100 40.82292411327362 0.12328165162380703
| {
"pile_set_name": "Github"
} |
//
// Copyright (c) 2000-2002
// Joerg Walter, Mathias Koch
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// The authors gratefully acknowledge the support of
// GeNeSys mbH & Co. KG in producing this work.
//
#include <iostream>
#include <boost/numeric/interval.hpp>
#include <boost/numeric/interval/io.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include "test7.hpp"
// this testcase requires fix of task #2473
int main () {
test_vector ();
test_matrix_vector ();
test_matrix ();
return 0;
}
| {
"pile_set_name": "Github"
} |
#ifndef _WINPERF_H
#define _WINPERF_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4820)
#endif
#define PERF_DATA_VERSION 1
#define PERF_DATA_REVISION 1
#define PERF_NO_INSTANCES -1
#define PERF_SIZE_DWORD 0
#define PERF_SIZE_LARGE 256
#define PERF_SIZE_ZERO 512
#define PERF_SIZE_VARIABLE_LEN 768
#define PERF_TYPE_NUMBER 0
#define PERF_TYPE_COUNTER 1024
#define PERF_TYPE_TEXT 2048
#define PERF_TYPE_ZERO 0xC00
#define PERF_NUMBER_HEX 0
#define PERF_NUMBER_DECIMAL 0x10000
#define PERF_NUMBER_DEC_1000 0x20000
#define PERF_COUNTER_VALUE 0
#define PERF_COUNTER_RATE 0x10000
#define PERF_COUNTER_FRACTION 0x20000
#define PERF_COUNTER_BASE 0x30000
#define PERF_COUNTER_ELAPSED 0x40000
#define PERF_COUNTER_QUEUELEN 0x50000
#define PERF_COUNTER_HISTOGRAM 0x60000
#define PERF_TEXT_UNICODE 0
#define PERF_TEXT_ASCII 0x10000
#define PERF_TIMER_TICK 0
#define PERF_TIMER_100NS 0x100000
#define PERF_OBJECT_TIMER 0x200000
#define PERF_DELTA_COUNTER 0x400000
#define PERF_DELTA_BASE 0x800000
#define PERF_INVERSE_COUNTER 0x1000000
#define PERF_MULTI_COUNTER 0x2000000
#define PERF_DISPLAY_NO_SUFFIX 0
#define PERF_DISPLAY_PER_SEC 0x10000000
#define PERF_DISPLAY_PERCENT 0x20000000
#define PERF_DISPLAY_SECONDS 0x30000000
#define PERF_DISPLAY_NOSHOW 0x40000000
#define PERF_COUNTER_HISTOGRAM_TYPE 0x80000000
#define PERF_NO_UNIQUE_ID (-1)
#define PERF_DETAIL_NOVICE 100
#define PERF_DETAIL_ADVANCED 200
#define PERF_DETAIL_EXPERT 300
#define PERF_DETAIL_WIZARD 400
#define PERF_COUNTER_COUNTER (PERF_SIZE_DWORD|PERF_TYPE_COUNTER|PERF_COUNTER_RATE|PERF_TIMER_TICK|PERF_DELTA_COUNTER|PERF_DISPLAY_PER_SEC)
#define PERF_COUNTER_TIMER (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_COUNTER_RATE|PERF_TIMER_TICK|PERF_DELTA_COUNTER|PERF_DISPLAY_PERCENT)
#define PERF_COUNTER_QUEUELEN_TYPE (PERF_SIZE_DWORD|PERF_TYPE_COUNTER|PERF_COUNTER_QUEUELEN|PERF_TIMER_TICK|PERF_DELTA_COUNTER|PERF_DISPLAY_NO_SUFFIX)
#define PERF_COUNTER_BULK_COUNT (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_COUNTER_RATE|PERF_TIMER_TICK|PERF_DELTA_COUNTER|PERF_DISPLAY_PER_SEC)
#define PERF_COUNTER_TEXT (PERF_SIZE_VARIABLE_LEN|PERF_TYPE_TEXT|PERF_TEXT_UNICODE|PERF_DISPLAY_NO_SUFFIX)
#define PERF_COUNTER_RAWCOUNT (PERF_SIZE_DWORD|PERF_TYPE_NUMBER|PERF_NUMBER_DECIMAL|PERF_DISPLAY_NO_SUFFIX)
#define PERF_COUNTER_LARGE_RAWCOUNT (PERF_SIZE_LARGE|PERF_TYPE_NUMBER|PERF_NUMBER_DECIMAL|PERF_DISPLAY_NO_SUFFIX)
#define PERF_COUNTER_RAWCOUNT_HEX (PERF_SIZE_DWORD|PERF_TYPE_NUMBER|PERF_NUMBER_HEX|PERF_DISPLAY_NO_SUFFIX)
#define PERF_COUNTER_LARGE_RAWCOUNT_HEX (PERF_SIZE_LARGE|PERF_TYPE_NUMBER|PERF_NUMBER_HEX|PERF_DISPLAY_NO_SUFFIX)
#define PERF_SAMPLE_FRACTION (PERF_SIZE_DWORD|PERF_TYPE_COUNTER|PERF_COUNTER_FRACTION|PERF_DELTA_COUNTER|PERF_DELTA_BASE|PERF_DISPLAY_PERCENT)
#define PERF_SAMPLE_COUNTER (PERF_SIZE_DWORD|PERF_TYPE_COUNTER|PERF_COUNTER_RATE|PERF_TIMER_TICK|PERF_DELTA_COUNTER|PERF_DISPLAY_NO_SUFFIX)
#define PERF_COUNTER_NODATA (PERF_SIZE_ZERO|PERF_DISPLAY_NOSHOW)
#define PERF_COUNTER_TIMER_INV (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_COUNTER_RATE|PERF_TIMER_TICK|PERF_DELTA_COUNTER|PERF_INVERSE_COUNTER|PERF_DISPLAY_PERCENT)
#define PERF_SAMPLE_BASE (PERF_SIZE_DWORD|PERF_TYPE_COUNTER|PERF_COUNTER_BASE|PERF_DISPLAY_NOSHOW|1)
#define PERF_AVERAGE_TIMER (PERF_SIZE_DWORD|PERF_TYPE_COUNTER|PERF_COUNTER_FRACTION|PERF_DISPLAY_SECONDS)
#define PERF_AVERAGE_BASE (PERF_SIZE_DWORD|PERF_TYPE_COUNTER|PERF_COUNTER_BASE|PERF_DISPLAY_NOSHOW|2)
#define PERF_AVERAGE_BULK (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_COUNTER_FRACTION|PERF_DISPLAY_NOSHOW)
#define PERF_100NSEC_TIMER (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_COUNTER_RATE|PERF_TIMER_100NS|PERF_DELTA_COUNTER|PERF_DISPLAY_PERCENT)
#define PERF_100NSEC_TIMER_INV (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_COUNTER_RATE|PERF_TIMER_100NS|PERF_DELTA_COUNTER|PERF_INVERSE_COUNTER|PERF_DISPLAY_PERCENT)
#define PERF_COUNTER_MULTI_TIMER (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_COUNTER_RATE|PERF_DELTA_COUNTER|PERF_TIMER_TICK|PERF_MULTI_COUNTER|PERF_DISPLAY_PERCENT)
#define PERF_COUNTER_MULTI_TIMER_INV (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_COUNTER_RATE|PERF_DELTA_COUNTER|PERF_MULTI_COUNTER|PERF_TIMER_TICK|PERF_INVERSE_COUNTER|PERF_DISPLAY_PERCENT)
#define PERF_COUNTER_MULTI_BASE (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_COUNTER_BASE|PERF_MULTI_COUNTER|PERF_DISPLAY_NOSHOW)
#define PERF_100NSEC_MULTI_TIMER (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_DELTA_COUNTER|PERF_COUNTER_RATE|PERF_TIMER_100NS|PERF_MULTI_COUNTER|PERF_DISPLAY_PERCENT)
#define PERF_100NSEC_MULTI_TIMER_INV (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_DELTA_COUNTER|PERF_COUNTER_RATE|PERF_TIMER_100NS|PERF_MULTI_COUNTER|PERF_INVERSE_COUNTER|PERF_DISPLAY_PERCENT)
#define PERF_RAW_FRACTION (PERF_SIZE_DWORD|PERF_TYPE_COUNTER|PERF_COUNTER_FRACTION|PERF_DISPLAY_PERCENT)
#define PERF_RAW_BASE (PERF_SIZE_DWORD|PERF_TYPE_COUNTER|PERF_COUNTER_BASE|PERF_DISPLAY_NOSHOW|3)
#define PERF_ELAPSED_TIME (PERF_SIZE_LARGE|PERF_TYPE_COUNTER|PERF_COUNTER_ELAPSED|PERF_OBJECT_TIMER|PERF_DISPLAY_SECONDS)
typedef struct _PERF_DATA_BLOCK {
WCHAR Signature[4];
DWORD LittleEndian;
DWORD Version;
DWORD Revision;
DWORD TotalByteLength;
DWORD HeaderLength;
DWORD NumObjectTypes;
LONG DefaultObject;
SYSTEMTIME SystemTime;
LARGE_INTEGER PerfTime;
LARGE_INTEGER PerfFreq;
LARGE_INTEGER PerfTime100nSec;
DWORD SystemNameLength;
DWORD SystemNameOffset;
} PERF_DATA_BLOCK, *PPERF_DATA_BLOCK;
typedef struct _PERF_OBJECT_TYPE {
DWORD TotalByteLength;
DWORD DefinitionLength;
DWORD HeaderLength;
DWORD ObjectNameTitleIndex;
LPWSTR ObjectNameTitle;
DWORD ObjectHelpTitleIndex;
LPWSTR ObjectHelpTitle;
DWORD DetailLevel;
DWORD NumCounters;
LONG DefaultCounter;
LONG NumInstances;
DWORD CodePage;
LARGE_INTEGER PerfTime;
LARGE_INTEGER PerfFreq;
} PERF_OBJECT_TYPE, *PPERF_OBJECT_TYPE;
typedef struct _PERF_COUNTER_DEFINITION {
DWORD ByteLength;
DWORD CounterNameTitleIndex;
LPWSTR CounterNameTitle;
DWORD CounterHelpTitleIndex;
LPWSTR CounterHelpTitle;
LONG DefaultScale;
DWORD DetailLevel;
DWORD CounterType;
DWORD CounterSize;
DWORD CounterOffset;
} PERF_COUNTER_DEFINITION,*PPERF_COUNTER_DEFINITION;
typedef struct _PERF_INSTANCE_DEFINITION {
DWORD ByteLength;
DWORD ParentObjectTitleIndex;
DWORD ParentObjectInstance;
LONG UniqueID;
DWORD NameOffset;
DWORD NameLength;
} PERF_INSTANCE_DEFINITION,*PPERF_INSTANCE_DEFINITION;
typedef struct _PERF_COUNTER_BLOCK {
DWORD ByteLength;
} PERF_COUNTER_BLOCK, *PPERF_COUNTER_BLOCK;
typedef DWORD(CALLBACK PM_OPEN_PROC)(LPWSTR);
typedef DWORD(CALLBACK PM_COLLECT_PROC)(LPWSTR,PVOID*,PDWORD,PDWORD);
typedef DWORD(CALLBACK PM_CLOSE_PROC)(void);
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.10">
<Form uuid="bf03bed9-89da-4afa-b0c5-bd6606f8f9c1">
<Properties>
<Name>Форма</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Форма</v8:content>
</v8:item>
</Synonym>
<Comment/>
<FormType>Managed</FormType>
<IncludeHelpInContents>false</IncludeHelpInContents>
<UsePurposes>
<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>
<v8:Value xsi:type="app:ApplicationUsePurpose">MobilePlatformApplication</v8:Value>
</UsePurposes>
<ExtendedPresentation/>
</Properties>
</Form>
</MetaDataObject> | {
"pile_set_name": "Github"
} |
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2015, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
/** @file texture.h
* @brief Defines texture helper structures for the library
*
* Used for file formats which embed their textures into the model file.
* Supported are both normal textures, which are stored as uncompressed
* pixels, and "compressed" textures, which are stored in a file format
* such as PNG or TGA.
*/
#ifndef AI_TEXTURE_H_INC
#define AI_TEXTURE_H_INC
#include "types.h"
#ifdef __cplusplus
extern "C" {
#endif
// --------------------------------------------------------------------------------
/** @def AI_MAKE_EMBEDDED_TEXNAME
* Used to build the reserved path name used by the material system to
* reference textures that are embedded into their corresponding
* model files. The parameter specifies the index of the texture
* (zero-based, in the aiScene::mTextures array)
*/
#if (!defined AI_MAKE_EMBEDDED_TEXNAME)
# define AI_MAKE_EMBEDDED_TEXNAME(_n_) "*" # _n_
#endif
#include "./Compiler/pushpack1.h"
// --------------------------------------------------------------------------------
/** @brief Helper structure to represent a texel in a ARGB8888 format
*
* Used by aiTexture.
*/
struct aiTexel
{
unsigned char b,g,r,a;
#ifdef __cplusplus
//! Comparison operator
bool operator== (const aiTexel& other) const
{
return b == other.b && r == other.r &&
g == other.g && a == other.a;
}
//! Inverse comparison operator
bool operator!= (const aiTexel& other) const
{
return b != other.b || r != other.r ||
g != other.g || a != other.a;
}
//! Conversion to a floating-point 4d color
operator aiColor4D() const
{
return aiColor4D(r/255.f,g/255.f,b/255.f,a/255.f);
}
#endif // __cplusplus
} PACK_STRUCT;
#include "./Compiler/poppack1.h"
// --------------------------------------------------------------------------------
/** Helper structure to describe an embedded texture
*
* Normally textures are contained in external files but some file formats embed
* them directly in the model file. There are two types of embedded textures:
* 1. Uncompressed textures. The color data is given in an uncompressed format.
* 2. Compressed textures stored in a file format like png or jpg. The raw file
* bytes are given so the application must utilize an image decoder (e.g. DevIL) to
* get access to the actual color data.
*/
struct aiTexture
{
/** Width of the texture, in pixels
*
* If mHeight is zero the texture is compressed in a format
* like JPEG. In this case mWidth specifies the size of the
* memory area pcData is pointing to, in bytes.
*/
unsigned int mWidth;
/** Height of the texture, in pixels
*
* If this value is zero, pcData points to an compressed texture
* in any format (e.g. JPEG).
*/
unsigned int mHeight;
/** A hint from the loader to make it easier for applications
* to determine the type of embedded compressed textures.
*
* If mHeight != 0 this member is undefined. Otherwise it
* is set set to '\\0\\0\\0\\0' if the loader has no additional
* information about the texture file format used OR the
* file extension of the format without a trailing dot. If there
* are multiple file extensions for a format, the shortest
* extension is chosen (JPEG maps to 'jpg', not to 'jpeg').
* E.g. 'dds\\0', 'pcx\\0', 'jpg\\0'. All characters are lower-case.
* The fourth character will always be '\\0'.
*/
char achFormatHint[4];
/** Data of the texture.
*
* Points to an array of mWidth * mHeight aiTexel's.
* The format of the texture data is always ARGB8888 to
* make the implementation for user of the library as easy
* as possible. If mHeight = 0 this is a pointer to a memory
* buffer of size mWidth containing the compressed texture
* data. Good luck, have fun!
*/
C_STRUCT aiTexel* pcData;
#ifdef __cplusplus
//! For compressed textures (mHeight == 0): compare the
//! format hint against a given string.
//! @param s Input string. 3 characters are maximally processed.
//! Example values: "jpg", "png"
//! @return true if the given string matches the format hint
bool CheckFormat(const char* s) const
{
return (0 == ::strncmp(achFormatHint,s,3));
}
// Construction
aiTexture ()
: mWidth (0)
, mHeight (0)
, pcData (NULL)
{
achFormatHint[0] = achFormatHint[1] = 0;
achFormatHint[2] = achFormatHint[3] = 0;
}
// Destruction
~aiTexture ()
{
delete[] pcData;
}
#endif
};
#ifdef __cplusplus
}
#endif
#endif // AI_TEXTURE_H_INC
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" ?>
<screenplay xmlns="urn:screenplay">
<path id="check">
<moveTo x="20" y="50" />
<quadTo x1="40" y1="70" x2="40" y2="77" />
<quadTo x1="45" y1="55" x2="75" y2="30" />
</path>
<roundRect id="frame"
left="3" top="3" right="97" bottom="97"
rx="17" ry="17" />
<event kind="onLoad">
<paint antiAlias="true" />
<!-- draw the background -->
<paint stroke="true" strokeWidth="4">
<color color="0x66000000"/>
</paint>
<matrix translate="[0,2]"/>
<add use="frame" />
<paint>
<color color="black"/>
</paint>
<matrix translate="[0,-2]"/>
<add use="frame" />
<paint stroke="false">
<linearGradient points="[0,frame.top,0,frame.bottom]" tileMode="clamp"
offsets="[0,0.65,1]">
<color color="#F2F2F2" />
<color color="#AFAFAF" />
<color color="#C7C7C7" />
</linearGradient>
</paint>
<add use="frame" />
<!-- draw the checkmark background -->
<paint stroke="true" strokeWidth="9">
<shader/>
<blur radius="1" blurStyle="normal"/>
<color color="0x88777777"/>
</paint>
<matrix translate="[0,-2]" />
<add use="check" />
<paint>
<color color="0x88BBBBBB"/>
</paint>
<matrix translate="[0,4]" />
<add use="check" />
<!-- draw the checkmark -->
<paint>
<maskFilter/>
<color color="#66CC00"/>
</paint>
<matrix translate="[0,-2]" />
<add use="check" />
</event>
</screenplay>
| {
"pile_set_name": "Github"
} |
name: hrtimer_start
ID: 93
format:
field:unsigned short common_type; offset:0; size:2; signed:0;
field:unsigned char common_flags; offset:2; size:1; signed:0;
field:unsigned char common_preempt_count; offset:3; size:1; signed:0;
field:int common_pid; offset:4; size:4; signed:1;
field:void * hrtimer; offset:8; size:8; signed:0;
field:void * function; offset:16; size:8; signed:0;
field:s64 expires; offset:24; size:8; signed:1;
field:s64 softexpires; offset:32; size:8; signed:1;
print fmt: "hrtimer=%p function=%pf expires=%llu softexpires=%llu", REC->hrtimer, REC->function, (unsigned long long)(((ktime_t) { .tv64 = REC->expires }).tv64), (unsigned long long)(((ktime_t) { .tv64 = REC->softexpires }).tv64)
| {
"pile_set_name": "Github"
} |
//
// STMAssembleMaker.h
// HomePageTest
//
// Created by DaiMing on 16/5/31.
// Copyright © 2016年 Starming. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "STMPartView.h"
@class STMAssembleView;
typedef NS_ENUM(NSUInteger, STMAssembleAlignment) {
STMAssembleAlignmentCenter,
STMAssembleAlignmentLeft,
STMAssembleAlignmentRight,
STMAssembleAlignmentTop,
STMAssembleAlignmentBottom
};
typedef NS_ENUM(NSUInteger, STMAssembleArrange) {
STMAssembleArrangeHorizontal,
STMAssembleArrangeVertical
};
typedef void(^ParsingFormatStringCompleteBlock)(STMAssembleView *asView);
@interface STMAssembleMaker : NSObject
//属性
@property (nonatomic, strong) NSMutableArray *subViews; //存放所有子视图
@property (nonatomic) CGFloat padding; //间隔距离
@property (nonatomic) STMAssembleAlignment alignment; //对齐
@property (nonatomic) STMAssembleArrange arrange; //水平还是垂直排列
@property (nonatomic) NSUInteger extendWith; //由第几个PartView来撑开AssembleView的大小
@property (nonatomic, copy) ParsingFormatStringCompleteBlock parsingCompletion;
//方法
- (STMAssembleMaker *(^)(STMAssembleView *))addAssembleView;
- (STMAssembleMaker *(^)(STMPartView *))addPartView;
- (STMAssembleMaker *(^)(UIView *))addView;
- (STMAssembleMaker *(^)(CGFloat))paddingEqualTo;
- (STMAssembleMaker *(^)(STMAssembleAlignment))alignmentEqualTo;
- (STMAssembleMaker *(^)(STMAssembleArrange))arrangeEqualTo;
- (STMAssembleMaker *(^)(NSUInteger))extendWithEqualTo;
@end
| {
"pile_set_name": "Github"
} |
cmake_minimum_required(VERSION 3.5)
project(AudioTK)
SET(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/CMake)
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
set(ATK_VERSION 3.2.0)
set(ATK_CURRENTLY_BUILDING ON)
option(ENABLE_TESTS "Enable tests generation" ON)
option(ENABLE_PROFILE_INFO "Enable profile info" OFF)
option(ENABLE_PROFILING "Enable the internal time counter" OFF)
option(ENABLE_SHARED_LIBRARIES "Enable shared libraries generation" ON)
option(ENABLE_STATIC_LIBRARIES "Enable static libraries generation" OFF)
option(ENABLE_PYTHON "Enable Python support" ON)
option(ENABLE_THREADS "Enable thread pool support" OFF)
option(ENABLE_SIMD "Enable SIMD support" OFF)
option(ENABLE_GPL "Enable GPL library support like FFTW and LIBSNDFILE" OFF)
option(ENABLE_CODECOVERAGE "Generate code coverage data" OFF)
option(ENABLE_ADDRESS_SANITIZER "Activate address sanitizer support" OFF)
option(BUILD_DOC "Build Doxygen documentation" OFF)
option(DISABLE_EIGEN_WARNINGS "Removes lots of Eigen warnings" OFF)
option(DISABLE_PYTHON_TESTS "Don't test Python modules" OFF) #Use this for CI
message(STATUS " Build SIMD: ${ENABLE_SIMD}")
message(STATUS " Build shared libraries: ${ENABLE_SHARED_LIBRARIES}")
message(STATUS " Build static libraries: ${ENABLE_STATIC_LIBRARIES}")
message(STATUS " Build tests: ${ENABLE_TESTS}")
enable_testing()
if(ENABLE_PYTHON)
add_subdirectory(${CMAKE_SOURCE_DIR}/3rdParty/pybind11)
LIST(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/3rdParty/pybind11/tools)
FIND_PACKAGE(PythonLibsNew REQUIRED)
endif(ENABLE_PYTHON)
include_directories(SYSTEM ${CMAKE_SOURCE_DIR}/3rdParty/eigen)
include_directories(SYSTEM ${CMAKE_SOURCE_DIR}/3rdParty/gsl/include)
if(ENABLE_SIMD)
SET(USE_SIMD 0)
else(ENABLE_SIMD)
SET(USE_SIMD 0)
endif(ENABLE_SIMD)
if(ENABLE_TESTS)
if(NOT ENABLE_SHARED_LIBRARIES)
message (ERROR " Tests depend on shared libraries to run")
endif(NOT ENABLE_SHARED_LIBRARIES)
endif(ENABLE_TESTS)
if(ENABLE_PYTHON)
if(NOT ENABLE_SHARED_LIBRARIES)
message (ERROR " Python support depends on shared libraries to run")
endif(NOT ENABLE_SHARED_LIBRARIES)
endif(ENABLE_PYTHON)
if(ENABLE_CODECOVERAGE)
SET(CMAKE_BUILD_TYPE "Coverage" CACHE STRING "" FORCE)
include(CodeCoverage)
setup_target_for_coverage(codecoverage "make test" coverage)
SET(ENABLE_INSTANTIATION 0)
else(ENABLE_CODECOVERAGE)
SET(ENABLE_INSTANTIATION 1)
endif(ENABLE_CODECOVERAGE)
IF(NOT DEFINED PYTHON_INSTALL_FOLDER)
set(PYTHON_INSTALL_FOLDER "${CMAKE_INSTALL_PREFIX}/lib/")
ENDIF(NOT DEFINED PYTHON_INSTALL_FOLDER)
if(ENABLE_PROFILING)
set(ENABLE_INTERNAL_PROFILING 1)
else(ENABLE_PROFILING)
set(ENABLE_INTERNAL_PROFILING 0)
endif(ENABLE_PROFILING)
if(ENABLE_THREADS)
find_package(TBB REQUIRED)
set(USE_THREADPOOL 1)
if(ENABLE_THREADS)
include_directories(${TBB_INCLUDE_DIR})
endif(ENABLE_THREADS)
else(ENABLE_THREADS)
set(USE_THREADPOOL 0)
endif(ENABLE_THREADS)
find_package(Git REQUIRED)
if(ENABLE_GPL)
find_package(libsndfile)
if(LIBSNDFILE_FOUND)
set(USE_LIBSNDFILE 1)
else(LIBSNDFILE_FOUND)
set(USE_LIBSNDFILE 0)
endif(LIBSNDFILE_FOUND)
endif(ENABLE_GPL)
find_package(IPP)
find_package(Boost REQUIRED)
SET(USE_FFTW 0)
SET(USE_IPP 0)
if(HAVE_IPP)
include_directories(${IPP_INCLUDE_DIRS})
SET(FFT_INCLUDES ${IPP_INCLUDE_DIRS})
SET(FFT_LIBRARIES ${IPP_LIBRARIES})
SET(FFTLIBRARIES ${IPP_LIBRARIES})
SET(USE_IPP 1)
else(HAVE_IPP)
if(ENABLE_GPL)
FIND_PACKAGE(FFTW REQUIRED)
SET(USE_FFTW 1)
include_directories(${FFTW_INCLUDES})
SET(FFT_INCLUDES ${FFTW_INCLUDES})
SET(FFT_LIBRARIES ${FFTW_LIBRARIES})
SET(FFTLIBRARIES ${FFTW_LIBRARIES})
else(ENABLE_GPL)
MESSAGE(FATAL_ERROR "No FFT support")
endif(ENABLE_GPL)
endif(HAVE_IPP)
if(ENABLE_TESTS)
find_package(Boost REQUIRED unit_test_framework system)
endif(ENABLE_TESTS)
include(Utilities)
# configure a header file to pass some of the CMake settings
# to the source code
configure_file (
"ATK/config.h.in"
"ATK/config.h" @ONLY
)
configure_file (
"atk-config.cmake.in"
"atk-config.cmake" @ONLY
)
INSTALL(FILES ${PROJECT_BINARY_DIR}/atk-config.cmake
DESTINATION ${CMAKE_INSTALL_PREFIX}
)
include_directories(${CMAKE_BINARY_DIR})
include_directories(SYSTEM ${Boost_INCLUDE_DIR})
add_subdirectory(ATK)
if(ENABLE_TESTS)
find_package(Boost REQUIRED unit_test_framework system)
ADD_DEFINITIONS("-DBOOST_ALL_NO_LIB")
add_subdirectory(tests)
add_subdirectory(profiling)
endif(ENABLE_TESTS)
if(ENABLE_PYTHON)
add_subdirectory(Python/ATK)
endif(ENABLE_PYTHON)
add_subdirectory(modules)
FILE(GLOB CMAKE_OTHER_SRC CMake/*.cmake *.in ATK/*.in *.yml *.md *.properties *.py scripts/*.sh)
SOURCE_GROUP_BY_FOLDER(CMAKE_OTHER)
add_custom_target(CMake SOURCES ${CMAKE_OTHER_SRC})
IF (BUILD_DOC)
FIND_PACKAGE(Doxygen REQUIRED)
SET(DOXYGEN_INPUT Doxyfile)
SET(DOXYGEN_OUTPUT Doxygen)
ADD_CUSTOM_COMMAND(
OUTPUT ${DOXYGEN_OUTPUT}
COMMAND ${CMAKE_COMMAND} -E echo_append "Building API Documentation..."
COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_INPUT}
COMMAND ${CMAKE_COMMAND} -E echo "Done."
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
DEPENDS ${DOXYGEN_INPUT}
)
ADD_CUSTOM_TARGET(apidoc ALL DEPENDS ${DOXYGEN_OUTPUT})
ADD_CUSTOM_TARGET(apidoc_forced
COMMAND ${CMAKE_COMMAND} -E echo_append "Building API Documentation..."
COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_INPUT}
COMMAND ${CMAKE_COMMAND} -E echo "Done."
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
ENDIF (BUILD_DOC)
IF(CMAKE_BUILD_TYPE MATCHES Debug)
message("Debug build.")
ELSEIF(CMAKE_BUILD_TYPE MATCHES Release)
message("Release build.")
ENDIF()
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<simple.com.demo.widgets.MultiImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#a5a5a5"
android:layout_marginTop="10dp"
/>
| {
"pile_set_name": "Github"
} |
{% extends "base.html" %}
{% block title %}
Edit "{{ course.title }}"
{% endblock %}
{% block content %}
<h1>Edit "{{ course.title }}"</h1>
<div class="module">
<h2>Course modules</h2>
<form action="" method="post">
{{ formset.as_p }}
{{ formset.management_form }}
{% csrf_token %}
<input type="submit" class="button" value="Save modules">
</form>
</div>
{% endblock %}
| {
"pile_set_name": "Github"
} |
/**
* Sinon.JS 1.12.2, 2015/09/10
*
* @author Christian Johansen ([email protected])
* @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
*
* (The BSD License)
*
* Copyright (c) 2010-2014, Christian Johansen, [email protected]
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Christian Johansen nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Helps IE run the fake timers. By defining global functions, IE allows
* them to be overwritten at a later point. If these are not defined like
* this, overwriting them will result in anything from an exception to browser
* crash.
*
* If you don't require fake timers to work in IE, don't include this file.
*
* @author Christian Johansen ([email protected])
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
function setTimeout() {}
function clearTimeout() {}
function setImmediate() {}
function clearImmediate() {}
function setInterval() {}
function clearInterval() {}
function Date() {}
// Reassign the original functions. Now their writable attribute
// should be true. Hackish, I know, but it works.
setTimeout = sinon.timers.setTimeout;
clearTimeout = sinon.timers.clearTimeout;
setImmediate = sinon.timers.setImmediate;
clearImmediate = sinon.timers.clearImmediate;
setInterval = sinon.timers.setInterval;
clearInterval = sinon.timers.clearInterval;
Date = sinon.timers.Date;
/**
* Helps IE run the fake XMLHttpRequest. By defining global functions, IE allows
* them to be overwritten at a later point. If these are not defined like
* this, overwriting them will result in anything from an exception to browser
* crash.
*
* If you don't require fake XHR to work in IE, don't include this file.
*
* @author Christian Johansen ([email protected])
* @license BSD
*
* Copyright (c) 2010-2013 Christian Johansen
*/
function XMLHttpRequest() {}
// Reassign the original function. Now its writable attribute
// should be true. Hackish, I know, but it works.
XMLHttpRequest = sinon.xhr.XMLHttpRequest || undefined;
/**
* Helps IE run the fake XDomainRequest. By defining global functions, IE allows
* them to be overwritten at a later point. If these are not defined like
* this, overwriting them will result in anything from an exception to browser
* crash.
*
* If you don't require fake XDR to work in IE, don't include this file.
*/
function XDomainRequest() {}
// Reassign the original function. Now its writable attribute
// should be true. Hackish, I know, but it works.
XDomainRequest = sinon.xdr.XDomainRequest || undefined;
| {
"pile_set_name": "Github"
} |
//---------------------------------------------------------------------
// <copyright file="ZipException.cs" company="Microsoft Corporation">
// Copyright (c) 1999, Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Part of the Deployment Tools Foundation project.
// </summary>
//---------------------------------------------------------------------
namespace Microsoft.PackageManagement.Archivers.Internal.Compression.Zip
{
using System;
/// <summary>
/// Exception class for zip operations.
/// </summary>
public class ZipException : ArchiveException
{
/// <summary>
/// Creates a new ZipException with a specified error message and a reference to the
/// inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception. If the
/// innerException parameter is not a null reference (Nothing in Visual Basic), the current exception
/// is raised in a catch block that handles the inner exception.</param>
public ZipException(string message, Exception innerException)
: base(message, innerException) { }
/// <summary>
/// Creates a new ZipException with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public ZipException(string message)
: this(message, null) { }
/// <summary>
/// Creates a new ZipException.
/// </summary>
public ZipException()
: this(null, null) { }
}
}
| {
"pile_set_name": "Github"
} |
/* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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 cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <CNIOBoringSSL_bio.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#include <CNIOBoringSSL_asn1.h>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_thread.h>
#include "../internal.h"
BIO *BIO_new(const BIO_METHOD *method) {
BIO *ret = OPENSSL_malloc(sizeof(BIO));
if (ret == NULL) {
OPENSSL_PUT_ERROR(BIO, ERR_R_MALLOC_FAILURE);
return NULL;
}
OPENSSL_memset(ret, 0, sizeof(BIO));
ret->method = method;
ret->shutdown = 1;
ret->references = 1;
if (method->create != NULL && !method->create(ret)) {
OPENSSL_free(ret);
return NULL;
}
return ret;
}
int BIO_free(BIO *bio) {
BIO *next_bio;
for (; bio != NULL; bio = next_bio) {
if (!CRYPTO_refcount_dec_and_test_zero(&bio->references)) {
return 0;
}
next_bio = BIO_pop(bio);
if (bio->method != NULL && bio->method->destroy != NULL) {
bio->method->destroy(bio);
}
OPENSSL_free(bio);
}
return 1;
}
int BIO_up_ref(BIO *bio) {
CRYPTO_refcount_inc(&bio->references);
return 1;
}
void BIO_vfree(BIO *bio) {
BIO_free(bio);
}
void BIO_free_all(BIO *bio) {
BIO_free(bio);
}
int BIO_read(BIO *bio, void *buf, int len) {
if (bio == NULL || bio->method == NULL || bio->method->bread == NULL) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
}
if (!bio->init) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNINITIALIZED);
return -2;
}
if (len <= 0) {
return 0;
}
int ret = bio->method->bread(bio, buf, len);
if (ret > 0) {
bio->num_read += ret;
}
return ret;
}
int BIO_gets(BIO *bio, char *buf, int len) {
if (bio == NULL || bio->method == NULL || bio->method->bgets == NULL) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
}
if (!bio->init) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNINITIALIZED);
return -2;
}
if (len <= 0) {
return 0;
}
int ret = bio->method->bgets(bio, buf, len);
if (ret > 0) {
bio->num_read += ret;
}
return ret;
}
int BIO_write(BIO *bio, const void *in, int inl) {
if (bio == NULL || bio->method == NULL || bio->method->bwrite == NULL) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
}
if (!bio->init) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNINITIALIZED);
return -2;
}
if (inl <= 0) {
return 0;
}
int ret = bio->method->bwrite(bio, in, inl);
if (ret > 0) {
bio->num_write += ret;
}
return ret;
}
int BIO_write_all(BIO *bio, const void *data, size_t len) {
const uint8_t *data_u8 = data;
while (len > 0) {
int ret = BIO_write(bio, data_u8, len > INT_MAX ? INT_MAX : (int)len);
if (ret <= 0) {
return 0;
}
data_u8 += ret;
len -= ret;
}
return 1;
}
int BIO_puts(BIO *bio, const char *in) {
return BIO_write(bio, in, strlen(in));
}
int BIO_flush(BIO *bio) {
return BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, NULL);
}
long BIO_ctrl(BIO *bio, int cmd, long larg, void *parg) {
if (bio == NULL) {
return 0;
}
if (bio->method == NULL || bio->method->ctrl == NULL) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD);
return -2;
}
return bio->method->ctrl(bio, cmd, larg, parg);
}
char *BIO_ptr_ctrl(BIO *b, int cmd, long larg) {
char *p = NULL;
if (BIO_ctrl(b, cmd, larg, (void *)&p) <= 0) {
return NULL;
}
return p;
}
long BIO_int_ctrl(BIO *b, int cmd, long larg, int iarg) {
int i = iarg;
return BIO_ctrl(b, cmd, larg, (void *)&i);
}
int BIO_reset(BIO *bio) {
return BIO_ctrl(bio, BIO_CTRL_RESET, 0, NULL);
}
int BIO_eof(BIO *bio) {
return BIO_ctrl(bio, BIO_CTRL_EOF, 0, NULL);
}
void BIO_set_flags(BIO *bio, int flags) {
bio->flags |= flags;
}
int BIO_test_flags(const BIO *bio, int flags) {
return bio->flags & flags;
}
int BIO_should_read(const BIO *bio) {
return BIO_test_flags(bio, BIO_FLAGS_READ);
}
int BIO_should_write(const BIO *bio) {
return BIO_test_flags(bio, BIO_FLAGS_WRITE);
}
int BIO_should_retry(const BIO *bio) {
return BIO_test_flags(bio, BIO_FLAGS_SHOULD_RETRY);
}
int BIO_should_io_special(const BIO *bio) {
return BIO_test_flags(bio, BIO_FLAGS_IO_SPECIAL);
}
int BIO_get_retry_reason(const BIO *bio) { return bio->retry_reason; }
void BIO_clear_flags(BIO *bio, int flags) {
bio->flags &= ~flags;
}
void BIO_set_retry_read(BIO *bio) {
bio->flags |= BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY;
}
void BIO_set_retry_write(BIO *bio) {
bio->flags |= BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY;
}
static const int kRetryFlags = BIO_FLAGS_RWS | BIO_FLAGS_SHOULD_RETRY;
int BIO_get_retry_flags(BIO *bio) {
return bio->flags & kRetryFlags;
}
void BIO_clear_retry_flags(BIO *bio) {
bio->flags &= ~kRetryFlags;
bio->retry_reason = 0;
}
int BIO_method_type(const BIO *bio) { return bio->method->type; }
void BIO_copy_next_retry(BIO *bio) {
BIO_clear_retry_flags(bio);
BIO_set_flags(bio, BIO_get_retry_flags(bio->next_bio));
bio->retry_reason = bio->next_bio->retry_reason;
}
long BIO_callback_ctrl(BIO *bio, int cmd, bio_info_cb fp) {
if (bio == NULL) {
return 0;
}
if (bio->method == NULL || bio->method->callback_ctrl == NULL) {
OPENSSL_PUT_ERROR(BIO, BIO_R_UNSUPPORTED_METHOD);
return 0;
}
return bio->method->callback_ctrl(bio, cmd, fp);
}
size_t BIO_pending(const BIO *bio) {
const long r = BIO_ctrl((BIO *) bio, BIO_CTRL_PENDING, 0, NULL);
assert(r >= 0);
if (r < 0) {
return 0;
}
return r;
}
size_t BIO_ctrl_pending(const BIO *bio) {
return BIO_pending(bio);
}
size_t BIO_wpending(const BIO *bio) {
const long r = BIO_ctrl((BIO *) bio, BIO_CTRL_WPENDING, 0, NULL);
assert(r >= 0);
if (r < 0) {
return 0;
}
return r;
}
int BIO_set_close(BIO *bio, int close_flag) {
return BIO_ctrl(bio, BIO_CTRL_SET_CLOSE, close_flag, NULL);
}
OPENSSL_EXPORT size_t BIO_number_read(const BIO *bio) {
return bio->num_read;
}
OPENSSL_EXPORT size_t BIO_number_written(const BIO *bio) {
return bio->num_write;
}
BIO *BIO_push(BIO *bio, BIO *appended_bio) {
BIO *last_bio;
if (bio == NULL) {
return bio;
}
last_bio = bio;
while (last_bio->next_bio != NULL) {
last_bio = last_bio->next_bio;
}
last_bio->next_bio = appended_bio;
return bio;
}
BIO *BIO_pop(BIO *bio) {
BIO *ret;
if (bio == NULL) {
return NULL;
}
ret = bio->next_bio;
bio->next_bio = NULL;
return ret;
}
BIO *BIO_next(BIO *bio) {
if (!bio) {
return NULL;
}
return bio->next_bio;
}
BIO *BIO_find_type(BIO *bio, int type) {
int method_type, mask;
if (!bio) {
return NULL;
}
mask = type & 0xff;
do {
if (bio->method != NULL) {
method_type = bio->method->type;
if (!mask) {
if (method_type & type) {
return bio;
}
} else if (method_type == type) {
return bio;
}
}
bio = bio->next_bio;
} while (bio != NULL);
return NULL;
}
int BIO_indent(BIO *bio, unsigned indent, unsigned max_indent) {
if (indent > max_indent) {
indent = max_indent;
}
while (indent--) {
if (BIO_puts(bio, " ") != 1) {
return 0;
}
}
return 1;
}
static int print_bio(const char *str, size_t len, void *bio) {
return BIO_write((BIO *)bio, str, len);
}
void ERR_print_errors(BIO *bio) {
ERR_print_errors_cb(print_bio, bio);
}
// bio_read_all reads everything from |bio| and prepends |prefix| to it. On
// success, |*out| is set to an allocated buffer (which should be freed with
// |OPENSSL_free|), |*out_len| is set to its length and one is returned. The
// buffer will contain |prefix| followed by the contents of |bio|. On failure,
// zero is returned.
//
// The function will fail if the size of the output would equal or exceed
// |max_len|.
static int bio_read_all(BIO *bio, uint8_t **out, size_t *out_len,
const uint8_t *prefix, size_t prefix_len,
size_t max_len) {
static const size_t kChunkSize = 4096;
size_t len = prefix_len + kChunkSize;
if (len > max_len) {
len = max_len;
}
if (len < prefix_len) {
return 0;
}
*out = OPENSSL_malloc(len);
if (*out == NULL) {
return 0;
}
OPENSSL_memcpy(*out, prefix, prefix_len);
size_t done = prefix_len;
for (;;) {
if (done == len) {
OPENSSL_free(*out);
return 0;
}
const size_t todo = len - done;
assert(todo < INT_MAX);
const int n = BIO_read(bio, *out + done, todo);
if (n == 0) {
*out_len = done;
return 1;
} else if (n == -1) {
OPENSSL_free(*out);
return 0;
}
done += n;
if (len < max_len && len - done < kChunkSize / 2) {
len += kChunkSize;
if (len < kChunkSize || len > max_len) {
len = max_len;
}
uint8_t *new_buf = OPENSSL_realloc(*out, len);
if (new_buf == NULL) {
OPENSSL_free(*out);
return 0;
}
*out = new_buf;
}
}
}
// bio_read_full reads |len| bytes |bio| and writes them into |out|. It
// tolerates partial reads from |bio| and returns one on success or zero if a
// read fails before |len| bytes are read. On failure, it additionally sets
// |*out_eof_on_first_read| to whether the error was due to |bio| returning zero
// on the first read. |out_eof_on_first_read| may be NULL to discard the value.
static int bio_read_full(BIO *bio, uint8_t *out, int *out_eof_on_first_read,
size_t len) {
int first_read = 1;
while (len > 0) {
int todo = len <= INT_MAX ? (int)len : INT_MAX;
int ret = BIO_read(bio, out, todo);
if (ret <= 0) {
if (out_eof_on_first_read != NULL) {
*out_eof_on_first_read = first_read && ret == 0;
}
return 0;
}
out += ret;
len -= (size_t)ret;
first_read = 0;
}
return 1;
}
// For compatibility with existing |d2i_*_bio| callers, |BIO_read_asn1| uses
// |ERR_LIB_ASN1| errors.
OPENSSL_DECLARE_ERROR_REASON(ASN1, ASN1_R_DECODE_ERROR)
OPENSSL_DECLARE_ERROR_REASON(ASN1, ASN1_R_HEADER_TOO_LONG)
OPENSSL_DECLARE_ERROR_REASON(ASN1, ASN1_R_NOT_ENOUGH_DATA)
OPENSSL_DECLARE_ERROR_REASON(ASN1, ASN1_R_TOO_LONG)
int BIO_read_asn1(BIO *bio, uint8_t **out, size_t *out_len, size_t max_len) {
uint8_t header[6];
static const size_t kInitialHeaderLen = 2;
int eof_on_first_read;
if (!bio_read_full(bio, header, &eof_on_first_read, kInitialHeaderLen)) {
if (eof_on_first_read) {
// Historically, OpenSSL returned |ASN1_R_HEADER_TOO_LONG| when
// |d2i_*_bio| could not read anything. CPython conditions on this to
// determine if |bio| was empty.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_HEADER_TOO_LONG);
} else {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA);
}
return 0;
}
const uint8_t tag = header[0];
const uint8_t length_byte = header[1];
if ((tag & 0x1f) == 0x1f) {
// Long form tags are not supported.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
size_t len, header_len;
if ((length_byte & 0x80) == 0) {
// Short form length.
len = length_byte;
header_len = kInitialHeaderLen;
} else {
const size_t num_bytes = length_byte & 0x7f;
if ((tag & 0x20 /* constructed */) != 0 && num_bytes == 0) {
// indefinite length.
if (!bio_read_all(bio, out, out_len, header, kInitialHeaderLen,
max_len)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA);
return 0;
}
return 1;
}
if (num_bytes == 0 || num_bytes > 4) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
if (!bio_read_full(bio, header + kInitialHeaderLen, NULL, num_bytes)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA);
return 0;
}
header_len = kInitialHeaderLen + num_bytes;
uint32_t len32 = 0;
for (unsigned i = 0; i < num_bytes; i++) {
len32 <<= 8;
len32 |= header[kInitialHeaderLen + i];
}
if (len32 < 128) {
// Length should have used short-form encoding.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
if ((len32 >> ((num_bytes-1)*8)) == 0) {
// Length should have been at least one byte shorter.
OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
return 0;
}
len = len32;
}
if (len + header_len < len ||
len + header_len > max_len ||
len > INT_MAX) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_TOO_LONG);
return 0;
}
len += header_len;
*out_len = len;
*out = OPENSSL_malloc(len);
if (*out == NULL) {
OPENSSL_PUT_ERROR(ASN1, ERR_R_MALLOC_FAILURE);
return 0;
}
OPENSSL_memcpy(*out, header, header_len);
if (!bio_read_full(bio, (*out) + header_len, NULL, len - header_len)) {
OPENSSL_PUT_ERROR(ASN1, ASN1_R_NOT_ENOUGH_DATA);
OPENSSL_free(*out);
return 0;
}
return 1;
}
void BIO_set_retry_special(BIO *bio) {
bio->flags |= BIO_FLAGS_READ | BIO_FLAGS_IO_SPECIAL;
}
int BIO_set_write_buffer_size(BIO *bio, int buffer_size) { return 0; }
static struct CRYPTO_STATIC_MUTEX g_index_lock = CRYPTO_STATIC_MUTEX_INIT;
static int g_index = BIO_TYPE_START;
int BIO_get_new_index(void) {
CRYPTO_STATIC_MUTEX_lock_write(&g_index_lock);
// If |g_index| exceeds 255, it will collide with the flags bits.
int ret = g_index > 255 ? -1 : g_index++;
CRYPTO_STATIC_MUTEX_unlock_write(&g_index_lock);
return ret;
}
BIO_METHOD *BIO_meth_new(int type, const char *name) {
BIO_METHOD *method = OPENSSL_malloc(sizeof(BIO_METHOD));
if (method == NULL) {
return NULL;
}
OPENSSL_memset(method, 0, sizeof(BIO_METHOD));
method->type = type;
method->name = name;
return method;
}
void BIO_meth_free(BIO_METHOD *method) {
OPENSSL_free(method);
}
int BIO_meth_set_create(BIO_METHOD *method,
int (*create)(BIO *)) {
method->create = create;
return 1;
}
int BIO_meth_set_destroy(BIO_METHOD *method,
int (*destroy)(BIO *)) {
method->destroy = destroy;
return 1;
}
int BIO_meth_set_write(BIO_METHOD *method,
int (*write)(BIO *, const char *, int)) {
method->bwrite = write;
return 1;
}
int BIO_meth_set_read(BIO_METHOD *method,
int (*read)(BIO *, char *, int)) {
method->bread = read;
return 1;
}
int BIO_meth_set_gets(BIO_METHOD *method,
int (*gets)(BIO *, char *, int)) {
method->bgets = gets;
return 1;
}
int BIO_meth_set_ctrl(BIO_METHOD *method,
long (*ctrl)(BIO *, int, long, void *)) {
method->ctrl = ctrl;
return 1;
}
void BIO_set_data(BIO *bio, void *ptr) { bio->ptr = ptr; }
void *BIO_get_data(BIO *bio) { return bio->ptr; }
void BIO_set_init(BIO *bio, int init) { bio->init = init; }
int BIO_get_init(BIO *bio) { return bio->init; }
void BIO_set_shutdown(BIO *bio, int shutdown) { bio->shutdown = shutdown; }
int BIO_get_shutdown(BIO *bio) { return bio->shutdown; }
int BIO_meth_set_puts(BIO_METHOD *method, int (*puts)(BIO *, const char *)) {
// Ignore the parameter. We implement |BIO_puts| using |BIO_write|.
return 1;
}
| {
"pile_set_name": "Github"
} |
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
* Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*************************************************************************/
#ifndef OPENCV_FLANN_INDEX_TESTING_H_
#define OPENCV_FLANN_INDEX_TESTING_H_
#include <cstring>
#include <cassert>
#include <cmath>
#include "matrix.h"
#include "nn_index.h"
#include "result_set.h"
#include "logger.h"
#include "timer.h"
namespace cvflann
{
inline int countCorrectMatches(int* neighbors, int* groundTruth, int n)
{
int count = 0;
for (int i=0; i<n; ++i) {
for (int k=0; k<n; ++k) {
if (neighbors[i]==groundTruth[k]) {
count++;
break;
}
}
}
return count;
}
template <typename Distance>
typename Distance::ResultType computeDistanceRaport(const Matrix<typename Distance::ElementType>& inputData, typename Distance::ElementType* target,
int* neighbors, int* groundTruth, int veclen, int n, const Distance& distance)
{
typedef typename Distance::ResultType DistanceType;
DistanceType ret = 0;
for (int i=0; i<n; ++i) {
DistanceType den = distance(inputData[groundTruth[i]], target, veclen);
DistanceType num = distance(inputData[neighbors[i]], target, veclen);
if ((den==0)&&(num==0)) {
ret += 1;
}
else {
ret += num/den;
}
}
return ret;
}
template <typename Distance>
float search_with_ground_truth(NNIndex<Distance>& index, const Matrix<typename Distance::ElementType>& inputData,
const Matrix<typename Distance::ElementType>& testData, const Matrix<int>& matches, int nn, int checks,
float& time, typename Distance::ResultType& dist, const Distance& distance, int skipMatches)
{
typedef typename Distance::ResultType DistanceType;
if (matches.cols<size_t(nn)) {
Logger::info("matches.cols=%d, nn=%d\n",matches.cols,nn);
throw FLANNException("Ground truth is not computed for as many neighbors as requested");
}
KNNResultSet<DistanceType> resultSet(nn+skipMatches);
SearchParams searchParams(checks);
std::vector<int> indices(nn+skipMatches);
std::vector<DistanceType> dists(nn+skipMatches);
int* neighbors = &indices[skipMatches];
int correct = 0;
DistanceType distR = 0;
StartStopTimer t;
int repeats = 0;
while (t.value<0.2) {
repeats++;
t.start();
correct = 0;
distR = 0;
for (size_t i = 0; i < testData.rows; i++) {
resultSet.init(&indices[0], &dists[0]);
index.findNeighbors(resultSet, testData[i], searchParams);
correct += countCorrectMatches(neighbors,matches[i], nn);
distR += computeDistanceRaport<Distance>(inputData, testData[i], neighbors, matches[i], (int)testData.cols, nn, distance);
}
t.stop();
}
time = float(t.value/repeats);
float precicion = (float)correct/(nn*testData.rows);
dist = distR/(testData.rows*nn);
Logger::info("%8d %10.4g %10.5g %10.5g %10.5g\n",
checks, precicion, time, 1000.0 * time / testData.rows, dist);
return precicion;
}
template <typename Distance>
float test_index_checks(NNIndex<Distance>& index, const Matrix<typename Distance::ElementType>& inputData,
const Matrix<typename Distance::ElementType>& testData, const Matrix<int>& matches,
int checks, float& precision, const Distance& distance, int nn = 1, int skipMatches = 0)
{
typedef typename Distance::ResultType DistanceType;
Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n");
Logger::info("---------------------------------------------------------\n");
float time = 0;
DistanceType dist = 0;
precision = search_with_ground_truth(index, inputData, testData, matches, nn, checks, time, dist, distance, skipMatches);
return time;
}
template <typename Distance>
float test_index_precision(NNIndex<Distance>& index, const Matrix<typename Distance::ElementType>& inputData,
const Matrix<typename Distance::ElementType>& testData, const Matrix<int>& matches,
float precision, int& checks, const Distance& distance, int nn = 1, int skipMatches = 0)
{
typedef typename Distance::ResultType DistanceType;
const float SEARCH_EPS = 0.001f;
Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n");
Logger::info("---------------------------------------------------------\n");
int c2 = 1;
float p2;
int c1 = 1;
//float p1;
float time;
DistanceType dist;
p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches);
if (p2>precision) {
Logger::info("Got as close as I can\n");
checks = c2;
return time;
}
while (p2<precision) {
c1 = c2;
//p1 = p2;
c2 *=2;
p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches);
}
int cx;
float realPrecision;
if (fabs(p2-precision)>SEARCH_EPS) {
Logger::info("Start linear estimation\n");
// after we got to values in the vecinity of the desired precision
// use linear approximation get a better estimation
cx = (c1+c2)/2;
realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches);
while (fabs(realPrecision-precision)>SEARCH_EPS) {
if (realPrecision<precision) {
c1 = cx;
}
else {
c2 = cx;
}
cx = (c1+c2)/2;
if (cx==c1) {
Logger::info("Got as close as I can\n");
break;
}
realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches);
}
c2 = cx;
p2 = realPrecision;
}
else {
Logger::info("No need for linear estimation\n");
cx = c2;
realPrecision = p2;
}
checks = cx;
return time;
}
template <typename Distance>
void test_index_precisions(NNIndex<Distance>& index, const Matrix<typename Distance::ElementType>& inputData,
const Matrix<typename Distance::ElementType>& testData, const Matrix<int>& matches,
float* precisions, int precisions_length, const Distance& distance, int nn = 1, int skipMatches = 0, float maxTime = 0)
{
typedef typename Distance::ResultType DistanceType;
const float SEARCH_EPS = 0.001;
// make sure precisions array is sorted
std::sort(precisions, precisions+precisions_length);
int pindex = 0;
float precision = precisions[pindex];
Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n");
Logger::info("---------------------------------------------------------\n");
int c2 = 1;
float p2;
int c1 = 1;
float p1;
float time;
DistanceType dist;
p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches);
// if precision for 1 run down the tree is already
// better then some of the requested precisions, then
// skip those
while (precisions[pindex]<p2 && pindex<precisions_length) {
pindex++;
}
if (pindex==precisions_length) {
Logger::info("Got as close as I can\n");
return;
}
for (int i=pindex; i<precisions_length; ++i) {
precision = precisions[i];
while (p2<precision) {
c1 = c2;
p1 = p2;
c2 *=2;
p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches);
if ((maxTime> 0)&&(time > maxTime)&&(p2<precision)) return;
}
int cx;
float realPrecision;
if (fabs(p2-precision)>SEARCH_EPS) {
Logger::info("Start linear estimation\n");
// after we got to values in the vecinity of the desired precision
// use linear approximation get a better estimation
cx = (c1+c2)/2;
realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches);
while (fabs(realPrecision-precision)>SEARCH_EPS) {
if (realPrecision<precision) {
c1 = cx;
}
else {
c2 = cx;
}
cx = (c1+c2)/2;
if (cx==c1) {
Logger::info("Got as close as I can\n");
break;
}
realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches);
}
c2 = cx;
p2 = realPrecision;
}
else {
Logger::info("No need for linear estimation\n");
cx = c2;
realPrecision = p2;
}
}
}
}
#endif //OPENCV_FLANN_INDEX_TESTING_H_
| {
"pile_set_name": "Github"
} |
/****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2005-2006 Fen Systems Ltd.
* Copyright 2006-2012 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#ifndef EFX_SELFTEST_H
#define EFX_SELFTEST_H
#include "net_driver.h"
/*
* Self tests
*/
struct efx_loopback_self_tests {
int tx_sent[EFX_TXQ_TYPES];
int tx_done[EFX_TXQ_TYPES];
int rx_good;
int rx_bad;
};
#define EFX_MAX_PHY_TESTS 20
/* Efx self test results
* For fields which are not counters, 1 indicates success and -1
* indicates failure; 0 indicates test could not be run.
*/
struct efx_self_tests {
/* online tests */
int phy_alive;
int nvram;
int interrupt;
int eventq_dma[EFX_MAX_CHANNELS];
int eventq_int[EFX_MAX_CHANNELS];
/* offline tests */
int memory;
int registers;
int phy_ext[EFX_MAX_PHY_TESTS];
struct efx_loopback_self_tests loopback[LOOPBACK_TEST_MAX + 1];
};
void efx_loopback_rx_packet(struct efx_nic *efx, const char *buf_ptr,
int pkt_len);
int efx_selftest(struct efx_nic *efx, struct efx_self_tests *tests,
unsigned flags);
void efx_selftest_async_start(struct efx_nic *efx);
void efx_selftest_async_cancel(struct efx_nic *efx);
void efx_selftest_async_work(struct work_struct *data);
#endif /* EFX_SELFTEST_H */
| {
"pile_set_name": "Github"
} |
0.0000005706416187587390041479624688455628 {omega[1]}
0.0000019133732731057715456866629595352879 {omega[2]}
0.0000053148568483405528785575373370490652 {omega[3]}
0.0000136025605957942838394422690533557257 {omega[4]}
0.0000323409098063415540837923127591001932 {omega[5]}
0.0000723600120301315709993875691639388104 {omega[6]}
0.0001540350804343130127133621544216132704 {omega[7]}
0.0003145533052232731284577848499157959328 {omega[8]}
0.0006200497020551953230117959601705446282 {omega[9]}
0.0011855162537368045241599644385767364785 {omega[10]}
0.0022069478662736208310269270162912169653 {omega[11]}
0.0040125097850616049998706579612223199760 {omega[12]}
0.0071429334158332422530461711020904891356 {omega[13]}
0.0124763532504684430960158561009498701111 {omega[14]}
0.0214200693210761487794859371860956009925 {omega[15]}
0.0362022426290005512868682042981749447108 {omega[16]}
0.0603118072107131979889076654754997974806 {omega[17]}
0.0991575490037124810871666837075455447348 {omega[18]}
0.1610532321069100576823793224967573678441 {omega[19]}
0.2587016001330438780064172737960248582567 {omega[20]}
0.4115020557426163164160305696359642979587 {omega[21]}
0.6494476549208797880926441470350596318895 {omega[22]}
1.0208924028541680157451329580275967146008 {omega[23]}
1.6125224809282724514449339214827716659784 {omega[24]}
2.6206564269384833901731235439314104951336 {omega[25]}
4.7816869373872780703792206846713952472783 {omega[26]}
0.0000002133144855182277243161717615151138 {alpha[1]}
0.0000013598455236373701158655421666142230 {alpha[2]}
0.0000047124550492559390314715995172478724 {alpha[3]}
0.0000135892313875476908971370887678530373 {alpha[4]}
0.0000353448292062735552666836864031153775 {alpha[5]}
0.0000852624094776091537220424333395115551 {alpha[6]}
0.0001937696123827856227612199347602565946 {alpha[7]}
0.0004193019539011284660279576315834032529 {alpha[8]}
0.0008706751521397799173938834046797274890 {alpha[9]}
0.0017451825269790492686261572981981649022 {alpha[10]}
0.0033922651238883996249367299303384415410 {alpha[11]}
0.0064181505252207956398419284177458976615 {alpha[12]}
0.0118552427827219890361744639682706203843 {alpha[13]}
0.0214325989784812014480366295851587743471 {alpha[14]}
0.0380024523115869211318271301408566742452 {alpha[15]}
0.0662051645142035866326620657806856229399 {alpha[16]}
0.1134951556790142145918405015836416538377 {alpha[17]}
0.1917091947380367131969136282321208852863 {alpha[18]}
0.3194458205559336816143235077136708355283 {alpha[19]}
0.5256606865849020383579977278021289066601 {alpha[20]}
0.8551196101465752695460625920631514418346 {alpha[21]}
1.3768549287486877857498643318301390081615 {alpha[22]}
2.1981347341403645611907641255200474006415 {alpha[23]}
3.4910495322750164169222503174339067300025 {alpha[24]}
5.5582136011756041742322420606825517097604 {alpha[25]}
9.0863318203460010352018327850487366958987 {alpha[26]}
| {
"pile_set_name": "Github"
} |
opt.tau <- function(kappa.init=NULL, i=NULL, kappa=NULL, mode, fixedprior=NULL) {
if(mode=="Jeffreys") {
return(jeffreys(kappa.init))
}
if(mode=="Pooled") {
return(pooledvar(kappa,i))
}
if(mode=="Fixed") {
paramgroup <- which(kappa$covar$type==kappa$covar$type[i])
return(fixedprior[paramgroup])
}
}
##
#This method implements a simple pooled MAP estimate by type
##
pooledvar <- function(kappa, i) {
paramgroup <- which(kappa$covar$type==kappa$covar$type[i])
tau <- mean(as.numeric(unlist(kappa$params[paramgroup]))^2)
prec <- 1/tau
prec <- ifelse(prec > 1e5,1e5,prec)
return(prec)
}
###
# Function to estimate jeffreys variance.
###
jeffreys <- function(x) {
if(sum(abs(x))==0) {
return(1)
} else {
x <- x^2
prec <- 1/x
prec[prec>1e5] <- 1e5
return(prec)
}
} | {
"pile_set_name": "Github"
} |
/*
Copyright 2020 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by injection-gen. DO NOT EDIT.
package legacytargetable
import (
context "context"
duck "knative.dev/pkg/apis/duck"
v1alpha1 "knative.dev/pkg/apis/duck/v1alpha1"
controller "knative.dev/pkg/controller"
injection "knative.dev/pkg/injection"
dynamicclient "knative.dev/pkg/injection/clients/dynamicclient"
logging "knative.dev/pkg/logging"
)
func init() {
injection.Default.RegisterDuck(WithDuck)
}
// Key is used for associating the Informer inside the context.Context.
type Key struct{}
func WithDuck(ctx context.Context) context.Context {
dc := dynamicclient.Get(ctx)
dif := &duck.CachedInformerFactory{
Delegate: &duck.TypedInformerFactory{
Client: dc,
Type: (&v1alpha1.LegacyTargetable{}).GetFullType(),
ResyncPeriod: controller.GetResyncPeriod(ctx),
StopChannel: ctx.Done(),
},
}
return context.WithValue(ctx, Key{}, dif)
}
// Get extracts the typed informer from the context.
func Get(ctx context.Context) duck.InformerFactory {
untyped := ctx.Value(Key{})
if untyped == nil {
logging.FromContext(ctx).Panic(
"Unable to fetch knative.dev/pkg/apis/duck.InformerFactory from context.")
}
return untyped.(duck.InformerFactory)
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#ifndef JDWP_UTIL_H
#define JDWP_UTIL_H
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#ifdef DEBUG
/* Just to make sure these interfaces are not used here. */
#undef free
#define free do_not_use_this_interface_free
#undef malloc
#define malloc do_not_use_this_interface_malloc
#undef calloc
#define calloc do_not_use_this_interface_calloc
#undef realloc
#define realloc do_not_use_this_interface_realloc
#undef strdup
#define strdup do_not_use_this_interface_strdup
#endif
#include "log_messages.h"
#include "vm_interface.h"
#include "JDWP.h"
#include "util_md.h"
#include "error_messages.h"
#include "debugInit.h"
/* Definition of a CommonRef tracked by the backend for the frontend */
typedef struct RefNode {
jlong seqNum; /* ID of reference, also key for hash table */
jobject ref; /* could be strong or weak */
struct RefNode *next; /* next RefNode* in bucket chain */
jint count; /* count of references */
unsigned isStrong : 1; /* 1 means this is a string reference */
} RefNode;
/* Value of a NULL ID */
#define NULL_OBJECT_ID ((jlong)0)
/*
* Globals used throughout the back end
*/
typedef jint FrameNumber;
typedef struct {
jvmtiEnv *jvmti;
JavaVM *jvm;
volatile jboolean vmDead; /* Once VM is dead it stays that way - don't put in init */
jboolean assertOn;
jboolean assertFatal;
jboolean doerrorexit;
jboolean modifiedUtf8;
jboolean quiet;
/* Debug flags (bit mask) */
int debugflags;
/* Possible debug flags */
#define USE_ITERATE_THROUGH_HEAP 0X001
char * options;
jclass classClass;
jclass threadClass;
jclass threadGroupClass;
jclass classLoaderClass;
jclass stringClass;
jclass systemClass;
jmethodID threadConstructor;
jmethodID threadSetDaemon;
jmethodID threadResume;
jmethodID systemGetProperty;
jmethodID setProperty;
jthreadGroup systemThreadGroup;
jobject agent_properties;
jint cachedJvmtiVersion;
jvmtiCapabilities cachedJvmtiCapabilities;
jboolean haveCachedJvmtiCapabilities;
jvmtiEventCallbacks callbacks;
/* Various property values we should grab on initialization */
char* property_java_version; /* UTF8 java.version */
char* property_java_vm_name; /* UTF8 java.vm.name */
char* property_java_vm_info; /* UTF8 java.vm.info */
char* property_java_class_path; /* UTF8 java.class.path */
char* property_sun_boot_library_path; /* UTF8 sun.boot.library.path */
char* property_path_separator; /* UTF8 path.separator */
char* property_user_dir; /* UTF8 user.dir */
unsigned log_flags;
/* Common References static data */
jrawMonitorID refLock;
jlong nextSeqNum;
RefNode **objectsByID;
int objectsByIDsize;
int objectsByIDcount;
/* Indication that the agent has been loaded */
jboolean isLoaded;
} BackendGlobalData;
extern BackendGlobalData * gdata;
/*
* Event Index for handlers
*/
typedef enum {
EI_min = 1,
EI_SINGLE_STEP = 1,
EI_BREAKPOINT = 2,
EI_FRAME_POP = 3,
EI_EXCEPTION = 4,
EI_THREAD_START = 5,
EI_THREAD_END = 6,
EI_CLASS_PREPARE = 7,
EI_GC_FINISH = 8,
EI_CLASS_LOAD = 9,
EI_FIELD_ACCESS = 10,
EI_FIELD_MODIFICATION = 11,
EI_EXCEPTION_CATCH = 12,
EI_METHOD_ENTRY = 13,
EI_METHOD_EXIT = 14,
EI_MONITOR_CONTENDED_ENTER = 15,
EI_MONITOR_CONTENDED_ENTERED = 16,
EI_MONITOR_WAIT = 17,
EI_MONITOR_WAITED = 18,
EI_VM_INIT = 19,
EI_VM_DEATH = 20,
EI_max = 20
} EventIndex;
/* Agent errors that might be in a jvmtiError for JDWP or internal.
* (Done this way so that compiler allows it's use as a jvmtiError)
*/
#define _AGENT_ERROR(x) ((jvmtiError)(JVMTI_ERROR_MAX+64+x))
#define AGENT_ERROR_INTERNAL _AGENT_ERROR(1)
#define AGENT_ERROR_VM_DEAD _AGENT_ERROR(2)
#define AGENT_ERROR_NO_JNI_ENV _AGENT_ERROR(3)
#define AGENT_ERROR_JNI_EXCEPTION _AGENT_ERROR(4)
#define AGENT_ERROR_JVMTI_INTERNAL _AGENT_ERROR(5)
#define AGENT_ERROR_JDWP_INTERNAL _AGENT_ERROR(6)
#define AGENT_ERROR_NOT_CURRENT_FRAME _AGENT_ERROR(7)
#define AGENT_ERROR_OUT_OF_MEMORY _AGENT_ERROR(8)
#define AGENT_ERROR_INVALID_TAG _AGENT_ERROR(9)
#define AGENT_ERROR_ALREADY_INVOKING _AGENT_ERROR(10)
#define AGENT_ERROR_INVALID_INDEX _AGENT_ERROR(11)
#define AGENT_ERROR_INVALID_LENGTH _AGENT_ERROR(12)
#define AGENT_ERROR_INVALID_STRING _AGENT_ERROR(13)
#define AGENT_ERROR_INVALID_CLASS_LOADER _AGENT_ERROR(14)
#define AGENT_ERROR_INVALID_ARRAY _AGENT_ERROR(15)
#define AGENT_ERROR_TRANSPORT_LOAD _AGENT_ERROR(16)
#define AGENT_ERROR_TRANSPORT_INIT _AGENT_ERROR(17)
#define AGENT_ERROR_NATIVE_METHOD _AGENT_ERROR(18)
#define AGENT_ERROR_INVALID_COUNT _AGENT_ERROR(19)
#define AGENT_ERROR_INVALID_FRAMEID _AGENT_ERROR(20)
#define AGENT_ERROR_NULL_POINTER _AGENT_ERROR(21)
#define AGENT_ERROR_ILLEGAL_ARGUMENT _AGENT_ERROR(22)
#define AGENT_ERROR_INVALID_THREAD _AGENT_ERROR(23)
#define AGENT_ERROR_INVALID_EVENT_TYPE _AGENT_ERROR(24)
#define AGENT_ERROR_INVALID_OBJECT _AGENT_ERROR(25)
#define AGENT_ERROR_NO_MORE_FRAMES _AGENT_ERROR(26)
#define AGENT_ERROR_INVALID_MODULE _AGENT_ERROR(27)
/* Combined event information */
typedef struct {
EventIndex ei;
jthread thread;
jclass clazz;
jmethodID method;
jlocation location;
jobject object; /* possibly an exception or user object */
union {
/* ei = EI_FIELD_ACCESS */
struct {
jclass field_clazz;
jfieldID field;
} field_access;
/* ei = EI_FIELD_MODIFICATION */
struct {
jclass field_clazz;
jfieldID field;
char signature_type;
jvalue new_value;
} field_modification;
/* ei = EI_EXCEPTION */
struct {
jclass catch_clazz;
jmethodID catch_method;
jlocation catch_location;
} exception;
/* ei = EI_METHOD_EXIT */
struct {
jvalue return_value;
} method_exit;
/* For monitor wait events */
union {
/* ei = EI_MONITOR_WAIT */
jlong timeout;
/* ei = EI_MONITOR_WAITED */
jboolean timed_out;
} monitor;
} u;
} EventInfo;
/* Structure to hold dynamic array of objects */
typedef struct ObjectBatch {
jobject *objects;
jint count;
} ObjectBatch;
/*
* JNI signature constants, beyond those defined in JDWP_TAG(*)
*/
#define SIGNATURE_BEGIN_ARGS '('
#define SIGNATURE_END_ARGS ')'
#define SIGNATURE_END_CLASS ';'
/*
* Modifier flags for classes, fields, methods
*/
#define MOD_PUBLIC 0x0001 /* visible to everyone */
#define MOD_PRIVATE 0x0002 /* visible only to the defining class */
#define MOD_PROTECTED 0x0004 /* visible to subclasses */
#define MOD_STATIC 0x0008 /* instance variable is static */
#define MOD_FINAL 0x0010 /* no further subclassing, overriding */
#define MOD_SYNCHRONIZED 0x0020 /* wrap method call in monitor lock */
#define MOD_VOLATILE 0x0040 /* can cache in registers */
#define MOD_TRANSIENT 0x0080 /* not persistant */
#define MOD_NATIVE 0x0100 /* implemented in C */
#define MOD_INTERFACE 0x0200 /* class is an interface */
#define MOD_ABSTRACT 0x0400 /* no definition provided */
/*
* Additional modifiers not defined as such in the JVM spec
*/
#define MOD_SYNTHETIC 0xf0000000 /* not in source code */
/*
* util funcs
*/
void util_initialize(JNIEnv *env);
void util_reset(void);
struct PacketInputStream;
struct PacketOutputStream;
jint uniqueID(void);
jbyte referenceTypeTag(jclass clazz);
jbyte specificTypeKey(JNIEnv *env, jobject object);
jboolean isObjectTag(jbyte tag);
jvmtiError spawnNewThread(jvmtiStartFunction func, void *arg, char *name);
void convertSignatureToClassname(char *convert);
void writeCodeLocation(struct PacketOutputStream *out, jclass clazz,
jmethodID method, jlocation location);
jvmtiError classInstances(jclass klass, ObjectBatch *instances, int maxInstances);
jvmtiError classInstanceCounts(jint classCount, jclass *classes, jlong *counts);
jvmtiError objectReferrers(jobject obj, ObjectBatch *referrers, int maxObjects);
/*
* Command handling helpers shared among multiple command sets
*/
int filterDebugThreads(jthread *threads, int count);
void sharedGetFieldValues(struct PacketInputStream *in,
struct PacketOutputStream *out,
jboolean isStatic);
jboolean sharedInvoke(struct PacketInputStream *in,
struct PacketOutputStream *out);
jvmtiError fieldSignature(jclass, jfieldID, char **, char **, char **);
jvmtiError fieldModifiers(jclass, jfieldID, jint *);
jvmtiError methodSignature(jmethodID, char **, char **, char **);
jvmtiError methodReturnType(jmethodID, char *);
jvmtiError methodModifiers(jmethodID, jint *);
jvmtiError methodClass(jmethodID, jclass *);
jvmtiError methodLocation(jmethodID, jlocation*, jlocation*);
jvmtiError classLoader(jclass, jobject *);
/*
* Thin wrappers on top of JNI
*/
JNIEnv *getEnv(void);
jboolean isClass(jobject object);
jboolean isThread(jobject object);
jboolean isThreadGroup(jobject object);
jboolean isString(jobject object);
jboolean isClassLoader(jobject object);
jboolean isArray(jobject object);
/*
* Thin wrappers on top of JVMTI
*/
jvmtiError jvmtiGetCapabilities(jvmtiCapabilities *caps);
jint jvmtiMajorVersion(void);
jint jvmtiMinorVersion(void);
jint jvmtiMicroVersion(void);
jvmtiError getSourceDebugExtension(jclass clazz, char **extensionPtr);
jboolean canSuspendResumeThreadLists(void);
jrawMonitorID debugMonitorCreate(char *name);
void debugMonitorEnter(jrawMonitorID theLock);
void debugMonitorExit(jrawMonitorID theLock);
void debugMonitorWait(jrawMonitorID theLock);
void debugMonitorTimedWait(jrawMonitorID theLock, jlong millis);
void debugMonitorNotify(jrawMonitorID theLock);
void debugMonitorNotifyAll(jrawMonitorID theLock);
void debugMonitorDestroy(jrawMonitorID theLock);
jthread *allThreads(jint *count);
void threadGroupInfo(jthreadGroup, jvmtiThreadGroupInfo *info);
jclass findClass(JNIEnv *env, const char * name);
jmethodID getMethod(JNIEnv *env, jclass clazz, const char * name, const char *signature);
char *getModuleName(jclass);
char *getClassname(jclass);
jvmtiError classSignature(jclass, char**, char**);
jint classStatus(jclass);
void writeGenericSignature(struct PacketOutputStream *, char *);
jboolean isMethodNative(jmethodID);
jboolean isMethodObsolete(jmethodID);
jvmtiError isMethodSynthetic(jmethodID, jboolean*);
jvmtiError isFieldSynthetic(jclass, jfieldID, jboolean*);
jboolean isSameObject(JNIEnv *env, jobject o1, jobject o2);
jint objectHashCode(jobject);
jvmtiError allInterfaces(jclass clazz, jclass **ppinterfaces, jint *count);
jvmtiError allLoadedClasses(jclass **ppclasses, jint *count);
jvmtiError allClassLoaderClasses(jobject loader, jclass **ppclasses, jint *count);
jvmtiError allNestedClasses(jclass clazz, jclass **ppnested, jint *pcount);
void setAgentPropertyValue(JNIEnv *env, char *propertyName, char* propertyValue);
void *jvmtiAllocate(jint numBytes);
void jvmtiDeallocate(void *buffer);
void eventIndexInit(void);
jdwpEvent eventIndex2jdwp(EventIndex i);
jvmtiEvent eventIndex2jvmti(EventIndex i);
EventIndex jdwp2EventIndex(jdwpEvent eventType);
EventIndex jvmti2EventIndex(jvmtiEvent kind);
jvmtiError map2jvmtiError(jdwpError);
jdwpError map2jdwpError(jvmtiError);
jdwpThreadStatus map2jdwpThreadStatus(jint state);
jint map2jdwpSuspendStatus(jint state);
jint map2jdwpClassStatus(jint);
void log_debugee_location(const char *func,
jthread thread, jmethodID method, jlocation location);
/*
* Local Reference management. The two macros below are used
* throughout the back end whenever space for JNI local references
* is needed in the current frame.
*/
void createLocalRefSpace(JNIEnv *env, jint capacity);
#define WITH_LOCAL_REFS(env, number) \
createLocalRefSpace(env, number); \
{ /* BEGINNING OF WITH SCOPE */
#define END_WITH_LOCAL_REFS(env) \
JNI_FUNC_PTR(env,PopLocalFrame)(env, NULL); \
} /* END OF WITH SCOPE */
void saveGlobalRef(JNIEnv *env, jobject obj, jobject *pobj);
void tossGlobalRef(JNIEnv *env, jobject *pobj);
#endif
| {
"pile_set_name": "Github"
} |
package gov.uspto.patent.doc.xml.fragments;
import static org.junit.Assert.*;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.junit.Test;
import gov.uspto.patent.InvalidDataException;
import gov.uspto.patent.model.CountryCode;
import gov.uspto.patent.model.DocumentDate;
import gov.uspto.patent.model.DocumentId;
import gov.uspto.patent.model.DocumentIdType;
public class PriorityClaimsTest {
@Test
public void test() throws DocumentException, InvalidDataException {
String xml = "<xml><biblio><priority-claims>\r\n" +
"<priority-claim kind=\"regional\" sequence=\"01\">\r\n" +
"<country>EM</country>\r\n" +
"<doc-number>002705756-0001</doc-number>\r\n" +
"<date>20150522</date>\r\n" +
"</priority-claim>\r\n" +
"<priority-claim kind=\"regional\" sequence=\"02\">\r\n" +
"<country>EM</country>\r\n" +
"<doc-number>002705756-0002</doc-number>\r\n" +
"<date>20150522</date>\r\n" +
"</priority-claim>\r\n" +
"<priority-claim kind=\"regional\" sequence=\"03\">\r\n" +
"<country>EM</country>\r\n" +
"<doc-number>002705756-0003</doc-number>\r\n" +
"<date>20150522</date>\r\n" +
"</priority-claim>\r\n" +
"</priority-claims></biblio></xml>";
Document doc = DocumentHelper.parseText(xml);
List<DocumentId> docIds = new PriorityClaims(doc).read();
assertEquals("Expect 3 docIds", 3, docIds.size());
DocumentId id1 = new DocumentId(CountryCode.EM, "0027057560001");
id1.setType(DocumentIdType.REGIONAL_FILING);
id1.setDate(new DocumentDate("20150522"));
assertEquals(id1, docIds.get(0));
DocumentId id2 = new DocumentId(CountryCode.EM, "0027057560002");
id2.setType(DocumentIdType.REGIONAL_FILING);
id2.setDate(new DocumentDate("20150522"));
assertEquals(id2, docIds.get(1));
DocumentId id3 = new DocumentId(CountryCode.EM, "0027057560003");
id3.setType(DocumentIdType.REGIONAL_FILING);
id3.setDate(new DocumentDate("20150522"));
assertEquals(id3, docIds.get(2));
}
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package io.reactivex.observable.internal.operators;
import io.reactivex.common.annotations.Nullable;
import io.reactivex.common.functions.Predicate;
import io.reactivex.observable.*;
import io.reactivex.observable.internal.observers.BasicFuseableObserver;
public final class ObservableFilter<T> extends AbstractObservableWithUpstream<T, T> {
final Predicate<? super T> predicate;
public ObservableFilter(ObservableSource<T> source, Predicate<? super T> predicate) {
super(source);
this.predicate = predicate;
}
@Override
public void subscribeActual(Observer<? super T> s) {
source.subscribe(new FilterObserver<T>(s, predicate));
}
static final class FilterObserver<T> extends BasicFuseableObserver<T, T> {
final Predicate<? super T> filter;
FilterObserver(Observer<? super T> actual, Predicate<? super T> filter) {
super(actual);
this.filter = filter;
}
@Override
public void onNext(T t) {
if (sourceMode == NONE) {
boolean b;
try {
b = filter.test(t);
} catch (Throwable e) {
fail(e);
return;
}
if (b) {
actual.onNext(t);
}
} else {
actual.onNext(null);
}
}
@Override
public int requestFusion(int mode) {
return transitiveBoundaryFusion(mode);
}
@Nullable
@Override
public T poll() throws Exception {
for (;;) {
T v = qs.poll();
if (v == null || filter.test(v)) {
return v;
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
--- fpr/fpr.c.orig 1994-05-27 12:31:21 UTC
+++ fpr/fpr.c
@@ -45,6 +45,7 @@ static char sccsid[] = "@(#)fpr.c 8.1 (B
#endif /* not lint */
#include <stdio.h>
+#include <stdlib.h>
#define BLANK ' '
#define TAB '\t'
@@ -80,12 +81,13 @@ COLUMN *line;
int maxpos;
int maxcol;
-extern char *malloc();
-extern char *calloc();
-extern char *realloc();
-
-
+void init();
+void mygettext();
+void flush();
+void savech(int);
+void nospace();
+int
main()
{
register int ch;
@@ -124,7 +126,7 @@ main()
while ( ! ateof)
{
- gettext();
+ mygettext();
ch = getchar();
if (ch == EOF)
{
@@ -176,6 +178,7 @@ main()
+void
init()
{
register COLUMN *cp;
@@ -210,7 +213,8 @@ init()
-gettext()
+void
+mygettext()
{
register int i;
register char ateol;
@@ -283,8 +287,8 @@ gettext()
-savech(col)
-int col;
+void
+savech(int col)
{
register char ch;
register int oldmax;
@@ -340,6 +344,7 @@ int col;
+void
flush()
{
register int i;
@@ -403,6 +408,7 @@ flush()
+void
nospace()
{
fputs("Storage limit exceeded.\n", stderr);
| {
"pile_set_name": "Github"
} |
--TEST--
Test get_declared_interfaces() function : error conditions
--FILE--
<?php
/* Prototype : proto array get_declared_interfaces()
* Description: Returns an array of all declared interfaces.
* Source code: Zend/zend_builtin_functions.c
* Alias to functions:
*/
echo "*** Testing get_declared_interfaces() : error conditions ***\n";
// One argument
echo "\n-- Testing get_declared_interfaces() function with one argument --\n";
$extra_arg = 10;;
var_dump( get_declared_interfaces($extra_arg) );
echo "Done";
?>
--EXPECTF--
*** Testing get_declared_interfaces() : error conditions ***
-- Testing get_declared_interfaces() function with one argument --
Warning: get_declared_interfaces() expects exactly 0 parameters, 1 given in %s on line 13
NULL
Done
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/source/trace_posix.h"
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
namespace webrtc {
TracePosix::TracePosix()
: crit_sect_(*CriticalSectionWrapper::CreateCriticalSection()) {
struct timeval system_time_high_res;
gettimeofday(&system_time_high_res, 0);
prev_api_tick_count_ = prev_tick_count_ = system_time_high_res.tv_sec;
}
TracePosix::~TracePosix() {
delete &crit_sect_;
StopThread();
}
int32_t TracePosix::AddTime(char* trace_message, const TraceLevel level) const {
struct timeval system_time_high_res;
if (gettimeofday(&system_time_high_res, 0) == -1) {
return -1;
}
struct tm buffer;
const struct tm* system_time =
localtime_r(&system_time_high_res.tv_sec, &buffer);
const uint32_t ms_time = system_time_high_res.tv_usec / 1000;
uint32_t prev_tickCount = 0;
{
CriticalSectionScoped lock(&crit_sect_);
if (level == kTraceApiCall) {
prev_tickCount = prev_tick_count_;
prev_tick_count_ = ms_time;
} else {
prev_tickCount = prev_api_tick_count_;
prev_api_tick_count_ = ms_time;
}
}
uint32_t dw_delta_time = ms_time - prev_tickCount;
if (prev_tickCount == 0) {
dw_delta_time = 0;
}
if (dw_delta_time > 0x0fffffff) {
// Either wraparound or data race.
dw_delta_time = 0;
}
if (dw_delta_time > 99999) {
dw_delta_time = 99999;
}
sprintf(trace_message, "(%2u:%2u:%2u:%3u |%5lu) ", system_time->tm_hour,
system_time->tm_min, system_time->tm_sec, ms_time,
static_cast<unsigned long>(dw_delta_time));
// Messages are 22 characters.
return 22;
}
int32_t TracePosix::AddDateTimeInfo(char* trace_message) const {
time_t t;
time(&t);
char buffer[26]; // man ctime says buffer should have room for >=26 bytes.
sprintf(trace_message, "Local Date: %s", ctime_r(&t, buffer));
int32_t len = static_cast<int32_t>(strlen(trace_message));
if ('\n' == trace_message[len - 1]) {
trace_message[len - 1] = '\0';
--len;
}
// Messages is 12 characters.
return len + 1;
}
} // namespace webrtc
| {
"pile_set_name": "Github"
} |
<view>
<view class="title text-center">basic</view>
<view class="text-left">text-left</view>
<view class="text-center">text-center</view>
<view class="text-right">text-right</view>
<view class="title">title</view>
<view class="border-basic">border-basic</view>
<view class="padding">padding</view>
<view class="padding-half">padding-half</view>
<view class="space"></view>
</view> | {
"pile_set_name": "Github"
} |
/*
* Marvell Wireless LAN device driver: WMM
*
* Copyright (C) 2011-2014, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*/
#include "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "wmm.h"
#include "11n.h"
/* Maximum value FW can accept for driver delay in packet transmission */
#define DRV_PKT_DELAY_TO_FW_MAX 512
#define WMM_QUEUED_PACKET_LOWER_LIMIT 180
#define WMM_QUEUED_PACKET_UPPER_LIMIT 200
/* Offset for TOS field in the IP header */
#define IPTOS_OFFSET 5
static bool disable_tx_amsdu;
module_param(disable_tx_amsdu, bool, 0644);
/* WMM information IE */
static const u8 wmm_info_ie[] = { WLAN_EID_VENDOR_SPECIFIC, 0x07,
0x00, 0x50, 0xf2, 0x02,
0x00, 0x01, 0x00
};
static const u8 wmm_aci_to_qidx_map[] = { WMM_AC_BE,
WMM_AC_BK,
WMM_AC_VI,
WMM_AC_VO
};
static u8 tos_to_tid[] = {
/* TID DSCP_P2 DSCP_P1 DSCP_P0 WMM_AC */
0x01, /* 0 1 0 AC_BK */
0x02, /* 0 0 0 AC_BK */
0x00, /* 0 0 1 AC_BE */
0x03, /* 0 1 1 AC_BE */
0x04, /* 1 0 0 AC_VI */
0x05, /* 1 0 1 AC_VI */
0x06, /* 1 1 0 AC_VO */
0x07 /* 1 1 1 AC_VO */
};
static u8 ac_to_tid[4][2] = { {1, 2}, {0, 3}, {4, 5}, {6, 7} };
/*
* This function debug prints the priority parameters for a WMM AC.
*/
static void
mwifiex_wmm_ac_debug_print(const struct ieee_types_wmm_ac_parameters *ac_param)
{
const char *ac_str[] = { "BK", "BE", "VI", "VO" };
pr_debug("info: WMM AC_%s: ACI=%d, ACM=%d, Aifsn=%d, "
"EcwMin=%d, EcwMax=%d, TxopLimit=%d\n",
ac_str[wmm_aci_to_qidx_map[(ac_param->aci_aifsn_bitmap
& MWIFIEX_ACI) >> 5]],
(ac_param->aci_aifsn_bitmap & MWIFIEX_ACI) >> 5,
(ac_param->aci_aifsn_bitmap & MWIFIEX_ACM) >> 4,
ac_param->aci_aifsn_bitmap & MWIFIEX_AIFSN,
ac_param->ecw_bitmap & MWIFIEX_ECW_MIN,
(ac_param->ecw_bitmap & MWIFIEX_ECW_MAX) >> 4,
le16_to_cpu(ac_param->tx_op_limit));
}
/*
* This function allocates a route address list.
*
* The function also initializes the list with the provided RA.
*/
static struct mwifiex_ra_list_tbl *
mwifiex_wmm_allocate_ralist_node(struct mwifiex_adapter *adapter, const u8 *ra)
{
struct mwifiex_ra_list_tbl *ra_list;
ra_list = kzalloc(sizeof(struct mwifiex_ra_list_tbl), GFP_ATOMIC);
if (!ra_list)
return NULL;
INIT_LIST_HEAD(&ra_list->list);
skb_queue_head_init(&ra_list->skb_head);
memcpy(ra_list->ra, ra, ETH_ALEN);
ra_list->total_pkt_count = 0;
mwifiex_dbg(adapter, INFO, "info: allocated ra_list %p\n", ra_list);
return ra_list;
}
/* This function returns random no between 16 and 32 to be used as threshold
* for no of packets after which BA setup is initiated.
*/
static u8 mwifiex_get_random_ba_threshold(void)
{
u64 ns;
/* setup ba_packet_threshold here random number between
* [BA_SETUP_PACKET_OFFSET,
* BA_SETUP_PACKET_OFFSET+BA_SETUP_MAX_PACKET_THRESHOLD-1]
*/
ns = ktime_get_ns();
ns += (ns >> 32) + (ns >> 16);
return ((u8)ns % BA_SETUP_MAX_PACKET_THRESHOLD) + BA_SETUP_PACKET_OFFSET;
}
/*
* This function allocates and adds a RA list for all TIDs
* with the given RA.
*/
void mwifiex_ralist_add(struct mwifiex_private *priv, const u8 *ra)
{
int i;
struct mwifiex_ra_list_tbl *ra_list;
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_sta_node *node;
unsigned long flags;
for (i = 0; i < MAX_NUM_TID; ++i) {
ra_list = mwifiex_wmm_allocate_ralist_node(adapter, ra);
mwifiex_dbg(adapter, INFO,
"info: created ra_list %p\n", ra_list);
if (!ra_list)
break;
ra_list->is_11n_enabled = 0;
ra_list->tdls_link = false;
ra_list->ba_status = BA_SETUP_NONE;
ra_list->amsdu_in_ampdu = false;
if (!mwifiex_queuing_ra_based(priv)) {
if (mwifiex_is_tdls_link_setup
(mwifiex_get_tdls_link_status(priv, ra))) {
ra_list->tdls_link = true;
ra_list->is_11n_enabled =
mwifiex_tdls_peer_11n_enabled(priv, ra);
} else {
ra_list->is_11n_enabled = IS_11N_ENABLED(priv);
}
} else {
spin_lock_irqsave(&priv->sta_list_spinlock, flags);
node = mwifiex_get_sta_entry(priv, ra);
if (node)
ra_list->tx_paused = node->tx_pause;
ra_list->is_11n_enabled =
mwifiex_is_sta_11n_enabled(priv, node);
if (ra_list->is_11n_enabled)
ra_list->max_amsdu = node->max_amsdu;
spin_unlock_irqrestore(&priv->sta_list_spinlock, flags);
}
mwifiex_dbg(adapter, DATA, "data: ralist %p: is_11n_enabled=%d\n",
ra_list, ra_list->is_11n_enabled);
if (ra_list->is_11n_enabled) {
ra_list->ba_pkt_count = 0;
ra_list->ba_packet_thr =
mwifiex_get_random_ba_threshold();
}
list_add_tail(&ra_list->list,
&priv->wmm.tid_tbl_ptr[i].ra_list);
}
}
/*
* This function sets the WMM queue priorities to their default values.
*/
static void mwifiex_wmm_default_queue_priorities(struct mwifiex_private *priv)
{
/* Default queue priorities: VO->VI->BE->BK */
priv->wmm.queue_priority[0] = WMM_AC_VO;
priv->wmm.queue_priority[1] = WMM_AC_VI;
priv->wmm.queue_priority[2] = WMM_AC_BE;
priv->wmm.queue_priority[3] = WMM_AC_BK;
}
/*
* This function map ACs to TIDs.
*/
static void
mwifiex_wmm_queue_priorities_tid(struct mwifiex_private *priv)
{
struct mwifiex_wmm_desc *wmm = &priv->wmm;
u8 *queue_priority = wmm->queue_priority;
int i;
for (i = 0; i < 4; ++i) {
tos_to_tid[7 - (i * 2)] = ac_to_tid[queue_priority[i]][1];
tos_to_tid[6 - (i * 2)] = ac_to_tid[queue_priority[i]][0];
}
for (i = 0; i < MAX_NUM_TID; ++i)
priv->tos_to_tid_inv[tos_to_tid[i]] = (u8)i;
atomic_set(&wmm->highest_queued_prio, HIGH_PRIO_TID);
}
/*
* This function initializes WMM priority queues.
*/
void
mwifiex_wmm_setup_queue_priorities(struct mwifiex_private *priv,
struct ieee_types_wmm_parameter *wmm_ie)
{
u16 cw_min, avg_back_off, tmp[4];
u32 i, j, num_ac;
u8 ac_idx;
if (!wmm_ie || !priv->wmm_enabled) {
/* WMM is not enabled, just set the defaults and return */
mwifiex_wmm_default_queue_priorities(priv);
return;
}
mwifiex_dbg(priv->adapter, INFO,
"info: WMM Parameter IE: version=%d,\t"
"qos_info Parameter Set Count=%d, Reserved=%#x\n",
wmm_ie->vend_hdr.version, wmm_ie->qos_info_bitmap &
IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK,
wmm_ie->reserved);
for (num_ac = 0; num_ac < ARRAY_SIZE(wmm_ie->ac_params); num_ac++) {
u8 ecw = wmm_ie->ac_params[num_ac].ecw_bitmap;
u8 aci_aifsn = wmm_ie->ac_params[num_ac].aci_aifsn_bitmap;
cw_min = (1 << (ecw & MWIFIEX_ECW_MIN)) - 1;
avg_back_off = (cw_min >> 1) + (aci_aifsn & MWIFIEX_AIFSN);
ac_idx = wmm_aci_to_qidx_map[(aci_aifsn & MWIFIEX_ACI) >> 5];
priv->wmm.queue_priority[ac_idx] = ac_idx;
tmp[ac_idx] = avg_back_off;
mwifiex_dbg(priv->adapter, INFO,
"info: WMM: CWmax=%d CWmin=%d Avg Back-off=%d\n",
(1 << ((ecw & MWIFIEX_ECW_MAX) >> 4)) - 1,
cw_min, avg_back_off);
mwifiex_wmm_ac_debug_print(&wmm_ie->ac_params[num_ac]);
}
/* Bubble sort */
for (i = 0; i < num_ac; i++) {
for (j = 1; j < num_ac - i; j++) {
if (tmp[j - 1] > tmp[j]) {
swap(tmp[j - 1], tmp[j]);
swap(priv->wmm.queue_priority[j - 1],
priv->wmm.queue_priority[j]);
} else if (tmp[j - 1] == tmp[j]) {
if (priv->wmm.queue_priority[j - 1]
< priv->wmm.queue_priority[j])
swap(priv->wmm.queue_priority[j - 1],
priv->wmm.queue_priority[j]);
}
}
}
mwifiex_wmm_queue_priorities_tid(priv);
}
/*
* This function evaluates whether or not an AC is to be downgraded.
*
* In case the AC is not enabled, the highest AC is returned that is
* enabled and does not require admission control.
*/
static enum mwifiex_wmm_ac_e
mwifiex_wmm_eval_downgrade_ac(struct mwifiex_private *priv,
enum mwifiex_wmm_ac_e eval_ac)
{
int down_ac;
enum mwifiex_wmm_ac_e ret_ac;
struct mwifiex_wmm_ac_status *ac_status;
ac_status = &priv->wmm.ac_status[eval_ac];
if (!ac_status->disabled)
/* Okay to use this AC, its enabled */
return eval_ac;
/* Setup a default return value of the lowest priority */
ret_ac = WMM_AC_BK;
/*
* Find the highest AC that is enabled and does not require
* admission control. The spec disallows downgrading to an AC,
* which is enabled due to a completed admission control.
* Unadmitted traffic is not to be sent on an AC with admitted
* traffic.
*/
for (down_ac = WMM_AC_BK; down_ac < eval_ac; down_ac++) {
ac_status = &priv->wmm.ac_status[down_ac];
if (!ac_status->disabled && !ac_status->flow_required)
/* AC is enabled and does not require admission
control */
ret_ac = (enum mwifiex_wmm_ac_e) down_ac;
}
return ret_ac;
}
/*
* This function downgrades WMM priority queue.
*/
void
mwifiex_wmm_setup_ac_downgrade(struct mwifiex_private *priv)
{
int ac_val;
mwifiex_dbg(priv->adapter, INFO, "info: WMM: AC Priorities:\t"
"BK(0), BE(1), VI(2), VO(3)\n");
if (!priv->wmm_enabled) {
/* WMM is not enabled, default priorities */
for (ac_val = WMM_AC_BK; ac_val <= WMM_AC_VO; ac_val++)
priv->wmm.ac_down_graded_vals[ac_val] =
(enum mwifiex_wmm_ac_e) ac_val;
} else {
for (ac_val = WMM_AC_BK; ac_val <= WMM_AC_VO; ac_val++) {
priv->wmm.ac_down_graded_vals[ac_val]
= mwifiex_wmm_eval_downgrade_ac(priv,
(enum mwifiex_wmm_ac_e) ac_val);
mwifiex_dbg(priv->adapter, INFO,
"info: WMM: AC PRIO %d maps to %d\n",
ac_val,
priv->wmm.ac_down_graded_vals[ac_val]);
}
}
}
/*
* This function converts the IP TOS field to an WMM AC
* Queue assignment.
*/
static enum mwifiex_wmm_ac_e
mwifiex_wmm_convert_tos_to_ac(struct mwifiex_adapter *adapter, u32 tos)
{
/* Map of TOS UP values to WMM AC */
const enum mwifiex_wmm_ac_e tos_to_ac[] = { WMM_AC_BE,
WMM_AC_BK,
WMM_AC_BK,
WMM_AC_BE,
WMM_AC_VI,
WMM_AC_VI,
WMM_AC_VO,
WMM_AC_VO
};
if (tos >= ARRAY_SIZE(tos_to_ac))
return WMM_AC_BE;
return tos_to_ac[tos];
}
/*
* This function evaluates a given TID and downgrades it to a lower
* TID if the WMM Parameter IE received from the AP indicates that the
* AP is disabled (due to call admission control (ACM bit). Mapping
* of TID to AC is taken care of internally.
*/
u8 mwifiex_wmm_downgrade_tid(struct mwifiex_private *priv, u32 tid)
{
enum mwifiex_wmm_ac_e ac, ac_down;
u8 new_tid;
ac = mwifiex_wmm_convert_tos_to_ac(priv->adapter, tid);
ac_down = priv->wmm.ac_down_graded_vals[ac];
/* Send the index to tid array, picking from the array will be
* taken care by dequeuing function
*/
new_tid = ac_to_tid[ac_down][tid % 2];
return new_tid;
}
/*
* This function initializes the WMM state information and the
* WMM data path queues.
*/
void
mwifiex_wmm_init(struct mwifiex_adapter *adapter)
{
int i, j;
struct mwifiex_private *priv;
for (j = 0; j < adapter->priv_num; ++j) {
priv = adapter->priv[j];
if (!priv)
continue;
for (i = 0; i < MAX_NUM_TID; ++i) {
if (!disable_tx_amsdu &&
adapter->tx_buf_size > MWIFIEX_TX_DATA_BUF_SIZE_2K)
priv->aggr_prio_tbl[i].amsdu =
priv->tos_to_tid_inv[i];
else
priv->aggr_prio_tbl[i].amsdu =
BA_STREAM_NOT_ALLOWED;
priv->aggr_prio_tbl[i].ampdu_ap =
priv->tos_to_tid_inv[i];
priv->aggr_prio_tbl[i].ampdu_user =
priv->tos_to_tid_inv[i];
}
priv->aggr_prio_tbl[6].amsdu
= priv->aggr_prio_tbl[6].ampdu_ap
= priv->aggr_prio_tbl[6].ampdu_user
= BA_STREAM_NOT_ALLOWED;
priv->aggr_prio_tbl[7].amsdu = priv->aggr_prio_tbl[7].ampdu_ap
= priv->aggr_prio_tbl[7].ampdu_user
= BA_STREAM_NOT_ALLOWED;
mwifiex_set_ba_params(priv);
mwifiex_reset_11n_rx_seq_num(priv);
priv->wmm.drv_pkt_delay_max = MWIFIEX_WMM_DRV_DELAY_MAX;
atomic_set(&priv->wmm.tx_pkts_queued, 0);
atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID);
}
}
int mwifiex_bypass_txlist_empty(struct mwifiex_adapter *adapter)
{
struct mwifiex_private *priv;
int i;
for (i = 0; i < adapter->priv_num; i++) {
priv = adapter->priv[i];
if (!priv)
continue;
if (adapter->if_ops.is_port_ready &&
!adapter->if_ops.is_port_ready(priv))
continue;
if (!skb_queue_empty(&priv->bypass_txq))
return false;
}
return true;
}
/*
* This function checks if WMM Tx queue is empty.
*/
int
mwifiex_wmm_lists_empty(struct mwifiex_adapter *adapter)
{
int i;
struct mwifiex_private *priv;
for (i = 0; i < adapter->priv_num; ++i) {
priv = adapter->priv[i];
if (!priv)
continue;
if (!priv->port_open &&
(priv->bss_mode != NL80211_IFTYPE_ADHOC))
continue;
if (adapter->if_ops.is_port_ready &&
!adapter->if_ops.is_port_ready(priv))
continue;
if (atomic_read(&priv->wmm.tx_pkts_queued))
return false;
}
return true;
}
/*
* This function deletes all packets in an RA list node.
*
* The packet sent completion callback handler are called with
* status failure, after they are dequeued to ensure proper
* cleanup. The RA list node itself is freed at the end.
*/
static void
mwifiex_wmm_del_pkts_in_ralist_node(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ra_list)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct sk_buff *skb, *tmp;
skb_queue_walk_safe(&ra_list->skb_head, skb, tmp) {
skb_unlink(skb, &ra_list->skb_head);
mwifiex_write_data_complete(adapter, skb, 0, -1);
}
}
/*
* This function deletes all packets in an RA list.
*
* Each nodes in the RA list are freed individually first, and then
* the RA list itself is freed.
*/
static void
mwifiex_wmm_del_pkts_in_ralist(struct mwifiex_private *priv,
struct list_head *ra_list_head)
{
struct mwifiex_ra_list_tbl *ra_list;
list_for_each_entry(ra_list, ra_list_head, list)
mwifiex_wmm_del_pkts_in_ralist_node(priv, ra_list);
}
/*
* This function deletes all packets in all RA lists.
*/
static void mwifiex_wmm_cleanup_queues(struct mwifiex_private *priv)
{
int i;
for (i = 0; i < MAX_NUM_TID; i++)
mwifiex_wmm_del_pkts_in_ralist(priv, &priv->wmm.tid_tbl_ptr[i].
ra_list);
atomic_set(&priv->wmm.tx_pkts_queued, 0);
atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID);
}
/*
* This function deletes all route addresses from all RA lists.
*/
static void mwifiex_wmm_delete_all_ralist(struct mwifiex_private *priv)
{
struct mwifiex_ra_list_tbl *ra_list, *tmp_node;
int i;
for (i = 0; i < MAX_NUM_TID; ++i) {
mwifiex_dbg(priv->adapter, INFO,
"info: ra_list: freeing buf for tid %d\n", i);
list_for_each_entry_safe(ra_list, tmp_node,
&priv->wmm.tid_tbl_ptr[i].ra_list,
list) {
list_del(&ra_list->list);
kfree(ra_list);
}
INIT_LIST_HEAD(&priv->wmm.tid_tbl_ptr[i].ra_list);
}
}
static int mwifiex_free_ack_frame(int id, void *p, void *data)
{
pr_warn("Have pending ack frames!\n");
kfree_skb(p);
return 0;
}
/*
* This function cleans up the Tx and Rx queues.
*
* Cleanup includes -
* - All packets in RA lists
* - All entries in Rx reorder table
* - All entries in Tx BA stream table
* - MPA buffer (if required)
* - All RA lists
*/
void
mwifiex_clean_txrx(struct mwifiex_private *priv)
{
unsigned long flags;
struct sk_buff *skb, *tmp;
mwifiex_11n_cleanup_reorder_tbl(priv);
spin_lock_irqsave(&priv->wmm.ra_list_spinlock, flags);
mwifiex_wmm_cleanup_queues(priv);
mwifiex_11n_delete_all_tx_ba_stream_tbl(priv);
if (priv->adapter->if_ops.cleanup_mpa_buf)
priv->adapter->if_ops.cleanup_mpa_buf(priv->adapter);
mwifiex_wmm_delete_all_ralist(priv);
memcpy(tos_to_tid, ac_to_tid, sizeof(tos_to_tid));
if (priv->adapter->if_ops.clean_pcie_ring &&
!priv->adapter->surprise_removed)
priv->adapter->if_ops.clean_pcie_ring(priv->adapter);
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock, flags);
skb_queue_walk_safe(&priv->tdls_txq, skb, tmp) {
skb_unlink(skb, &priv->tdls_txq);
mwifiex_write_data_complete(priv->adapter, skb, 0, -1);
}
skb_queue_walk_safe(&priv->bypass_txq, skb, tmp) {
skb_unlink(skb, &priv->bypass_txq);
mwifiex_write_data_complete(priv->adapter, skb, 0, -1);
}
atomic_set(&priv->adapter->bypass_tx_pending, 0);
idr_for_each(&priv->ack_status_frames, mwifiex_free_ack_frame, NULL);
idr_destroy(&priv->ack_status_frames);
}
/*
* This function retrieves a particular RA list node, matching with the
* given TID and RA address.
*/
struct mwifiex_ra_list_tbl *
mwifiex_wmm_get_ralist_node(struct mwifiex_private *priv, u8 tid,
const u8 *ra_addr)
{
struct mwifiex_ra_list_tbl *ra_list;
list_for_each_entry(ra_list, &priv->wmm.tid_tbl_ptr[tid].ra_list,
list) {
if (!memcmp(ra_list->ra, ra_addr, ETH_ALEN))
return ra_list;
}
return NULL;
}
void mwifiex_update_ralist_tx_pause(struct mwifiex_private *priv, u8 *mac,
u8 tx_pause)
{
struct mwifiex_ra_list_tbl *ra_list;
u32 pkt_cnt = 0, tx_pkts_queued;
unsigned long flags;
int i;
spin_lock_irqsave(&priv->wmm.ra_list_spinlock, flags);
for (i = 0; i < MAX_NUM_TID; ++i) {
ra_list = mwifiex_wmm_get_ralist_node(priv, i, mac);
if (ra_list && ra_list->tx_paused != tx_pause) {
pkt_cnt += ra_list->total_pkt_count;
ra_list->tx_paused = tx_pause;
if (tx_pause)
priv->wmm.pkts_paused[i] +=
ra_list->total_pkt_count;
else
priv->wmm.pkts_paused[i] -=
ra_list->total_pkt_count;
}
}
if (pkt_cnt) {
tx_pkts_queued = atomic_read(&priv->wmm.tx_pkts_queued);
if (tx_pause)
tx_pkts_queued -= pkt_cnt;
else
tx_pkts_queued += pkt_cnt;
atomic_set(&priv->wmm.tx_pkts_queued, tx_pkts_queued);
atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID);
}
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock, flags);
}
/* This function updates non-tdls peer ralist tx_pause while
* tdls channel switching
*/
void mwifiex_update_ralist_tx_pause_in_tdls_cs(struct mwifiex_private *priv,
u8 *mac, u8 tx_pause)
{
struct mwifiex_ra_list_tbl *ra_list;
u32 pkt_cnt = 0, tx_pkts_queued;
unsigned long flags;
int i;
spin_lock_irqsave(&priv->wmm.ra_list_spinlock, flags);
for (i = 0; i < MAX_NUM_TID; ++i) {
list_for_each_entry(ra_list, &priv->wmm.tid_tbl_ptr[i].ra_list,
list) {
if (!memcmp(ra_list->ra, mac, ETH_ALEN))
continue;
if (ra_list->tx_paused != tx_pause) {
pkt_cnt += ra_list->total_pkt_count;
ra_list->tx_paused = tx_pause;
if (tx_pause)
priv->wmm.pkts_paused[i] +=
ra_list->total_pkt_count;
else
priv->wmm.pkts_paused[i] -=
ra_list->total_pkt_count;
}
}
}
if (pkt_cnt) {
tx_pkts_queued = atomic_read(&priv->wmm.tx_pkts_queued);
if (tx_pause)
tx_pkts_queued -= pkt_cnt;
else
tx_pkts_queued += pkt_cnt;
atomic_set(&priv->wmm.tx_pkts_queued, tx_pkts_queued);
atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID);
}
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock, flags);
}
/*
* This function retrieves an RA list node for a given TID and
* RA address pair.
*
* If no such node is found, a new node is added first and then
* retrieved.
*/
struct mwifiex_ra_list_tbl *
mwifiex_wmm_get_queue_raptr(struct mwifiex_private *priv, u8 tid,
const u8 *ra_addr)
{
struct mwifiex_ra_list_tbl *ra_list;
ra_list = mwifiex_wmm_get_ralist_node(priv, tid, ra_addr);
if (ra_list)
return ra_list;
mwifiex_ralist_add(priv, ra_addr);
return mwifiex_wmm_get_ralist_node(priv, tid, ra_addr);
}
/*
* This function deletes RA list nodes for given mac for all TIDs.
* Function also decrements TX pending count accordingly.
*/
void
mwifiex_wmm_del_peer_ra_list(struct mwifiex_private *priv, const u8 *ra_addr)
{
struct mwifiex_ra_list_tbl *ra_list;
unsigned long flags;
int i;
spin_lock_irqsave(&priv->wmm.ra_list_spinlock, flags);
for (i = 0; i < MAX_NUM_TID; ++i) {
ra_list = mwifiex_wmm_get_ralist_node(priv, i, ra_addr);
if (!ra_list)
continue;
mwifiex_wmm_del_pkts_in_ralist_node(priv, ra_list);
if (ra_list->tx_paused)
priv->wmm.pkts_paused[i] -= ra_list->total_pkt_count;
else
atomic_sub(ra_list->total_pkt_count,
&priv->wmm.tx_pkts_queued);
list_del(&ra_list->list);
kfree(ra_list);
}
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock, flags);
}
/*
* This function checks if a particular RA list node exists in a given TID
* table index.
*/
int
mwifiex_is_ralist_valid(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ra_list, int ptr_index)
{
struct mwifiex_ra_list_tbl *rlist;
list_for_each_entry(rlist, &priv->wmm.tid_tbl_ptr[ptr_index].ra_list,
list) {
if (rlist == ra_list)
return true;
}
return false;
}
/*
* This function adds a packet to bypass TX queue.
* This is special TX queue for packets which can be sent even when port_open
* is false.
*/
void
mwifiex_wmm_add_buf_bypass_txqueue(struct mwifiex_private *priv,
struct sk_buff *skb)
{
skb_queue_tail(&priv->bypass_txq, skb);
}
/*
* This function adds a packet to WMM queue.
*
* In disconnected state the packet is immediately dropped and the
* packet send completion callback is called with status failure.
*
* Otherwise, the correct RA list node is located and the packet
* is queued at the list tail.
*/
void
mwifiex_wmm_add_buf_txqueue(struct mwifiex_private *priv,
struct sk_buff *skb)
{
struct mwifiex_adapter *adapter = priv->adapter;
u32 tid;
struct mwifiex_ra_list_tbl *ra_list;
u8 ra[ETH_ALEN], tid_down;
unsigned long flags;
struct list_head list_head;
int tdls_status = TDLS_NOT_SETUP;
struct ethhdr *eth_hdr = (struct ethhdr *)skb->data;
struct mwifiex_txinfo *tx_info = MWIFIEX_SKB_TXCB(skb);
memcpy(ra, eth_hdr->h_dest, ETH_ALEN);
if (GET_BSS_ROLE(priv) == MWIFIEX_BSS_ROLE_STA &&
ISSUPP_TDLS_ENABLED(adapter->fw_cap_info)) {
if (ntohs(eth_hdr->h_proto) == ETH_P_TDLS)
mwifiex_dbg(adapter, DATA,
"TDLS setup packet for %pM.\t"
"Don't block\n", ra);
else if (memcmp(priv->cfg_bssid, ra, ETH_ALEN))
tdls_status = mwifiex_get_tdls_link_status(priv, ra);
}
if (!priv->media_connected && !mwifiex_is_skb_mgmt_frame(skb)) {
mwifiex_dbg(adapter, DATA, "data: drop packet in disconnect\n");
mwifiex_write_data_complete(adapter, skb, 0, -1);
return;
}
tid = skb->priority;
spin_lock_irqsave(&priv->wmm.ra_list_spinlock, flags);
tid_down = mwifiex_wmm_downgrade_tid(priv, tid);
/* In case of infra as we have already created the list during
association we just don't have to call get_queue_raptr, we will
have only 1 raptr for a tid in case of infra */
if (!mwifiex_queuing_ra_based(priv) &&
!mwifiex_is_skb_mgmt_frame(skb)) {
switch (tdls_status) {
case TDLS_SETUP_COMPLETE:
case TDLS_CHAN_SWITCHING:
case TDLS_IN_BASE_CHAN:
case TDLS_IN_OFF_CHAN:
ra_list = mwifiex_wmm_get_queue_raptr(priv, tid_down,
ra);
tx_info->flags |= MWIFIEX_BUF_FLAG_TDLS_PKT;
break;
case TDLS_SETUP_INPROGRESS:
skb_queue_tail(&priv->tdls_txq, skb);
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock,
flags);
return;
default:
list_head = priv->wmm.tid_tbl_ptr[tid_down].ra_list;
if (!list_empty(&list_head))
ra_list = list_first_entry(
&list_head, struct mwifiex_ra_list_tbl,
list);
else
ra_list = NULL;
break;
}
} else {
memcpy(ra, skb->data, ETH_ALEN);
if (ra[0] & 0x01 || mwifiex_is_skb_mgmt_frame(skb))
eth_broadcast_addr(ra);
ra_list = mwifiex_wmm_get_queue_raptr(priv, tid_down, ra);
}
if (!ra_list) {
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock, flags);
mwifiex_write_data_complete(adapter, skb, 0, -1);
return;
}
skb_queue_tail(&ra_list->skb_head, skb);
ra_list->ba_pkt_count++;
ra_list->total_pkt_count++;
if (atomic_read(&priv->wmm.highest_queued_prio) <
priv->tos_to_tid_inv[tid_down])
atomic_set(&priv->wmm.highest_queued_prio,
priv->tos_to_tid_inv[tid_down]);
if (ra_list->tx_paused)
priv->wmm.pkts_paused[tid_down]++;
else
atomic_inc(&priv->wmm.tx_pkts_queued);
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock, flags);
}
/*
* This function processes the get WMM status command response from firmware.
*
* The response may contain multiple TLVs -
* - AC Queue status TLVs
* - Current WMM Parameter IE TLV
* - Admission Control action frame TLVs
*
* This function parses the TLVs and then calls further specific functions
* to process any changes in the queue prioritize or state.
*/
int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv,
const struct host_cmd_ds_command *resp)
{
u8 *curr = (u8 *) &resp->params.get_wmm_status;
uint16_t resp_len = le16_to_cpu(resp->size), tlv_len;
int mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK;
bool valid = true;
struct mwifiex_ie_types_data *tlv_hdr;
struct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus;
struct ieee_types_wmm_parameter *wmm_param_ie = NULL;
struct mwifiex_wmm_ac_status *ac_status;
mwifiex_dbg(priv->adapter, INFO,
"info: WMM: WMM_GET_STATUS cmdresp received: %d\n",
resp_len);
while ((resp_len >= sizeof(tlv_hdr->header)) && valid) {
tlv_hdr = (struct mwifiex_ie_types_data *) curr;
tlv_len = le16_to_cpu(tlv_hdr->header.len);
if (resp_len < tlv_len + sizeof(tlv_hdr->header))
break;
switch (le16_to_cpu(tlv_hdr->header.type)) {
case TLV_TYPE_WMMQSTATUS:
tlv_wmm_qstatus =
(struct mwifiex_ie_types_wmm_queue_status *)
tlv_hdr;
mwifiex_dbg(priv->adapter, CMD,
"info: CMD_RESP: WMM_GET_STATUS:\t"
"QSTATUS TLV: %d, %d, %d\n",
tlv_wmm_qstatus->queue_index,
tlv_wmm_qstatus->flow_required,
tlv_wmm_qstatus->disabled);
ac_status = &priv->wmm.ac_status[tlv_wmm_qstatus->
queue_index];
ac_status->disabled = tlv_wmm_qstatus->disabled;
ac_status->flow_required =
tlv_wmm_qstatus->flow_required;
ac_status->flow_created = tlv_wmm_qstatus->flow_created;
break;
case WLAN_EID_VENDOR_SPECIFIC:
/*
* Point the regular IEEE IE 2 bytes into the Marvell IE
* and setup the IEEE IE type and length byte fields
*/
wmm_param_ie =
(struct ieee_types_wmm_parameter *) (curr +
2);
wmm_param_ie->vend_hdr.len = (u8) tlv_len;
wmm_param_ie->vend_hdr.element_id =
WLAN_EID_VENDOR_SPECIFIC;
mwifiex_dbg(priv->adapter, CMD,
"info: CMD_RESP: WMM_GET_STATUS:\t"
"WMM Parameter Set Count: %d\n",
wmm_param_ie->qos_info_bitmap & mask);
memcpy((u8 *) &priv->curr_bss_params.bss_descriptor.
wmm_ie, wmm_param_ie,
wmm_param_ie->vend_hdr.len + 2);
break;
default:
valid = false;
break;
}
curr += (tlv_len + sizeof(tlv_hdr->header));
resp_len -= (tlv_len + sizeof(tlv_hdr->header));
}
mwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie);
mwifiex_wmm_setup_ac_downgrade(priv);
return 0;
}
/*
* Callback handler from the command module to allow insertion of a WMM TLV.
*
* If the BSS we are associating to supports WMM, this function adds the
* required WMM Information IE to the association request command buffer in
* the form of a Marvell extended IEEE IE.
*/
u32
mwifiex_wmm_process_association_req(struct mwifiex_private *priv,
u8 **assoc_buf,
struct ieee_types_wmm_parameter *wmm_ie,
struct ieee80211_ht_cap *ht_cap)
{
struct mwifiex_ie_types_wmm_param_set *wmm_tlv;
u32 ret_len = 0;
/* Null checks */
if (!assoc_buf)
return 0;
if (!(*assoc_buf))
return 0;
if (!wmm_ie)
return 0;
mwifiex_dbg(priv->adapter, INFO,
"info: WMM: process assoc req: bss->wmm_ie=%#x\n",
wmm_ie->vend_hdr.element_id);
if ((priv->wmm_required ||
(ht_cap && (priv->adapter->config_bands & BAND_GN ||
priv->adapter->config_bands & BAND_AN))) &&
wmm_ie->vend_hdr.element_id == WLAN_EID_VENDOR_SPECIFIC) {
wmm_tlv = (struct mwifiex_ie_types_wmm_param_set *) *assoc_buf;
wmm_tlv->header.type = cpu_to_le16((u16) wmm_info_ie[0]);
wmm_tlv->header.len = cpu_to_le16((u16) wmm_info_ie[1]);
memcpy(wmm_tlv->wmm_ie, &wmm_info_ie[2],
le16_to_cpu(wmm_tlv->header.len));
if (wmm_ie->qos_info_bitmap & IEEE80211_WMM_IE_AP_QOSINFO_UAPSD)
memcpy((u8 *) (wmm_tlv->wmm_ie
+ le16_to_cpu(wmm_tlv->header.len)
- sizeof(priv->wmm_qosinfo)),
&priv->wmm_qosinfo, sizeof(priv->wmm_qosinfo));
ret_len = sizeof(wmm_tlv->header)
+ le16_to_cpu(wmm_tlv->header.len);
*assoc_buf += ret_len;
}
return ret_len;
}
/*
* This function computes the time delay in the driver queues for a
* given packet.
*
* When the packet is received at the OS/Driver interface, the current
* time is set in the packet structure. The difference between the present
* time and that received time is computed in this function and limited
* based on pre-compiled limits in the driver.
*/
u8
mwifiex_wmm_compute_drv_pkt_delay(struct mwifiex_private *priv,
const struct sk_buff *skb)
{
u32 queue_delay = ktime_to_ms(net_timedelta(skb->tstamp));
u8 ret_val;
/*
* Queue delay is passed as a uint8 in units of 2ms (ms shifted
* by 1). Min value (other than 0) is therefore 2ms, max is 510ms.
*
* Pass max value if queue_delay is beyond the uint8 range
*/
ret_val = (u8) (min(queue_delay, priv->wmm.drv_pkt_delay_max) >> 1);
mwifiex_dbg(priv->adapter, DATA, "data: WMM: Pkt Delay: %d ms,\t"
"%d ms sent to FW\n", queue_delay, ret_val);
return ret_val;
}
/*
* This function retrieves the highest priority RA list table pointer.
*/
static struct mwifiex_ra_list_tbl *
mwifiex_wmm_get_highest_priolist_ptr(struct mwifiex_adapter *adapter,
struct mwifiex_private **priv, int *tid)
{
struct mwifiex_private *priv_tmp;
struct mwifiex_ra_list_tbl *ptr;
struct mwifiex_tid_tbl *tid_ptr;
atomic_t *hqp;
unsigned long flags_ra;
int i, j;
/* check the BSS with highest priority first */
for (j = adapter->priv_num - 1; j >= 0; --j) {
/* iterate over BSS with the equal priority */
list_for_each_entry(adapter->bss_prio_tbl[j].bss_prio_cur,
&adapter->bss_prio_tbl[j].bss_prio_head,
list) {
try_again:
priv_tmp = adapter->bss_prio_tbl[j].bss_prio_cur->priv;
if (((priv_tmp->bss_mode != NL80211_IFTYPE_ADHOC) &&
!priv_tmp->port_open) ||
(atomic_read(&priv_tmp->wmm.tx_pkts_queued) == 0))
continue;
if (adapter->if_ops.is_port_ready &&
!adapter->if_ops.is_port_ready(priv_tmp))
continue;
/* iterate over the WMM queues of the BSS */
hqp = &priv_tmp->wmm.highest_queued_prio;
for (i = atomic_read(hqp); i >= LOW_PRIO_TID; --i) {
spin_lock_irqsave(&priv_tmp->wmm.
ra_list_spinlock, flags_ra);
tid_ptr = &(priv_tmp)->wmm.
tid_tbl_ptr[tos_to_tid[i]];
/* iterate over receiver addresses */
list_for_each_entry(ptr, &tid_ptr->ra_list,
list) {
if (!ptr->tx_paused &&
!skb_queue_empty(&ptr->skb_head))
/* holds both locks */
goto found;
}
spin_unlock_irqrestore(&priv_tmp->wmm.
ra_list_spinlock,
flags_ra);
}
if (atomic_read(&priv_tmp->wmm.tx_pkts_queued) != 0) {
atomic_set(&priv_tmp->wmm.highest_queued_prio,
HIGH_PRIO_TID);
/* Iterate current private once more, since
* there still exist packets in data queue
*/
goto try_again;
} else
atomic_set(&priv_tmp->wmm.highest_queued_prio,
NO_PKT_PRIO_TID);
}
}
return NULL;
found:
/* holds ra_list_spinlock */
if (atomic_read(hqp) > i)
atomic_set(hqp, i);
spin_unlock_irqrestore(&priv_tmp->wmm.ra_list_spinlock, flags_ra);
*priv = priv_tmp;
*tid = tos_to_tid[i];
return ptr;
}
/* This functions rotates ra and bss lists so packets are picked round robin.
*
* After a packet is successfully transmitted, rotate the ra list, so the ra
* next to the one transmitted, will come first in the list. This way we pick
* the ra' in a round robin fashion. Same applies to bss nodes of equal
* priority.
*
* Function also increments wmm.packets_out counter.
*/
void mwifiex_rotate_priolists(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ra,
int tid)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_bss_prio_tbl *tbl = adapter->bss_prio_tbl;
struct mwifiex_tid_tbl *tid_ptr = &priv->wmm.tid_tbl_ptr[tid];
unsigned long flags;
spin_lock_irqsave(&tbl[priv->bss_priority].bss_prio_lock, flags);
/*
* dirty trick: we remove 'head' temporarily and reinsert it after
* curr bss node. imagine list to stay fixed while head is moved
*/
list_move(&tbl[priv->bss_priority].bss_prio_head,
&tbl[priv->bss_priority].bss_prio_cur->list);
spin_unlock_irqrestore(&tbl[priv->bss_priority].bss_prio_lock, flags);
spin_lock_irqsave(&priv->wmm.ra_list_spinlock, flags);
if (mwifiex_is_ralist_valid(priv, ra, tid)) {
priv->wmm.packets_out[tid]++;
/* same as above */
list_move(&tid_ptr->ra_list, &ra->list);
}
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock, flags);
}
/*
* This function checks if 11n aggregation is possible.
*/
static int
mwifiex_is_11n_aggragation_possible(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ptr,
int max_buf_size)
{
int count = 0, total_size = 0;
struct sk_buff *skb, *tmp;
int max_amsdu_size;
if (priv->bss_role == MWIFIEX_BSS_ROLE_UAP && priv->ap_11n_enabled &&
ptr->is_11n_enabled)
max_amsdu_size = min_t(int, ptr->max_amsdu, max_buf_size);
else
max_amsdu_size = max_buf_size;
skb_queue_walk_safe(&ptr->skb_head, skb, tmp) {
total_size += skb->len;
if (total_size >= max_amsdu_size)
break;
if (++count >= MIN_NUM_AMSDU)
return true;
}
return false;
}
/*
* This function sends a single packet to firmware for transmission.
*/
static void
mwifiex_send_single_packet(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ptr, int ptr_index,
unsigned long ra_list_flags)
__releases(&priv->wmm.ra_list_spinlock)
{
struct sk_buff *skb, *skb_next;
struct mwifiex_tx_param tx_param;
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_txinfo *tx_info;
if (skb_queue_empty(&ptr->skb_head)) {
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock,
ra_list_flags);
mwifiex_dbg(adapter, DATA, "data: nothing to send\n");
return;
}
skb = skb_dequeue(&ptr->skb_head);
tx_info = MWIFIEX_SKB_TXCB(skb);
mwifiex_dbg(adapter, DATA,
"data: dequeuing the packet %p %p\n", ptr, skb);
ptr->total_pkt_count--;
if (!skb_queue_empty(&ptr->skb_head))
skb_next = skb_peek(&ptr->skb_head);
else
skb_next = NULL;
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock, ra_list_flags);
tx_param.next_pkt_len = ((skb_next) ? skb_next->len +
sizeof(struct txpd) : 0);
if (mwifiex_process_tx(priv, skb, &tx_param) == -EBUSY) {
/* Queue the packet back at the head */
spin_lock_irqsave(&priv->wmm.ra_list_spinlock, ra_list_flags);
if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) {
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock,
ra_list_flags);
mwifiex_write_data_complete(adapter, skb, 0, -1);
return;
}
skb_queue_tail(&ptr->skb_head, skb);
ptr->total_pkt_count++;
ptr->ba_pkt_count++;
tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT;
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock,
ra_list_flags);
} else {
mwifiex_rotate_priolists(priv, ptr, ptr_index);
atomic_dec(&priv->wmm.tx_pkts_queued);
}
}
/*
* This function checks if the first packet in the given RA list
* is already processed or not.
*/
static int
mwifiex_is_ptr_processed(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ptr)
{
struct sk_buff *skb;
struct mwifiex_txinfo *tx_info;
if (skb_queue_empty(&ptr->skb_head))
return false;
skb = skb_peek(&ptr->skb_head);
tx_info = MWIFIEX_SKB_TXCB(skb);
if (tx_info->flags & MWIFIEX_BUF_FLAG_REQUEUED_PKT)
return true;
return false;
}
/*
* This function sends a single processed packet to firmware for
* transmission.
*/
static void
mwifiex_send_processed_packet(struct mwifiex_private *priv,
struct mwifiex_ra_list_tbl *ptr, int ptr_index,
unsigned long ra_list_flags)
__releases(&priv->wmm.ra_list_spinlock)
{
struct mwifiex_tx_param tx_param;
struct mwifiex_adapter *adapter = priv->adapter;
int ret = -1;
struct sk_buff *skb, *skb_next;
struct mwifiex_txinfo *tx_info;
if (skb_queue_empty(&ptr->skb_head)) {
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock,
ra_list_flags);
return;
}
skb = skb_dequeue(&ptr->skb_head);
if (adapter->data_sent || adapter->tx_lock_flag) {
ptr->total_pkt_count--;
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock,
ra_list_flags);
skb_queue_tail(&adapter->tx_data_q, skb);
atomic_dec(&priv->wmm.tx_pkts_queued);
atomic_inc(&adapter->tx_queued);
return;
}
if (!skb_queue_empty(&ptr->skb_head))
skb_next = skb_peek(&ptr->skb_head);
else
skb_next = NULL;
tx_info = MWIFIEX_SKB_TXCB(skb);
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock, ra_list_flags);
if (adapter->iface_type == MWIFIEX_USB) {
ret = adapter->if_ops.host_to_card(adapter, priv->usb_port,
skb, NULL);
} else {
tx_param.next_pkt_len =
((skb_next) ? skb_next->len +
sizeof(struct txpd) : 0);
ret = adapter->if_ops.host_to_card(adapter, MWIFIEX_TYPE_DATA,
skb, &tx_param);
}
switch (ret) {
case -EBUSY:
mwifiex_dbg(adapter, ERROR, "data: -EBUSY is returned\n");
spin_lock_irqsave(&priv->wmm.ra_list_spinlock, ra_list_flags);
if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) {
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock,
ra_list_flags);
mwifiex_write_data_complete(adapter, skb, 0, -1);
return;
}
skb_queue_tail(&ptr->skb_head, skb);
tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT;
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock,
ra_list_flags);
break;
case -1:
mwifiex_dbg(adapter, ERROR, "host_to_card failed: %#x\n", ret);
adapter->dbg.num_tx_host_to_card_failure++;
mwifiex_write_data_complete(adapter, skb, 0, ret);
break;
case -EINPROGRESS:
break;
case 0:
mwifiex_write_data_complete(adapter, skb, 0, ret);
default:
break;
}
if (ret != -EBUSY) {
mwifiex_rotate_priolists(priv, ptr, ptr_index);
atomic_dec(&priv->wmm.tx_pkts_queued);
spin_lock_irqsave(&priv->wmm.ra_list_spinlock, ra_list_flags);
ptr->total_pkt_count--;
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock,
ra_list_flags);
}
}
/*
* This function dequeues a packet from the highest priority list
* and transmits it.
*/
static int
mwifiex_dequeue_tx_packet(struct mwifiex_adapter *adapter)
{
struct mwifiex_ra_list_tbl *ptr;
struct mwifiex_private *priv = NULL;
int ptr_index = 0;
u8 ra[ETH_ALEN];
int tid_del = 0, tid = 0;
unsigned long flags;
ptr = mwifiex_wmm_get_highest_priolist_ptr(adapter, &priv, &ptr_index);
if (!ptr)
return -1;
tid = mwifiex_get_tid(ptr);
mwifiex_dbg(adapter, DATA, "data: tid=%d\n", tid);
spin_lock_irqsave(&priv->wmm.ra_list_spinlock, flags);
if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) {
spin_unlock_irqrestore(&priv->wmm.ra_list_spinlock, flags);
return -1;
}
if (mwifiex_is_ptr_processed(priv, ptr)) {
mwifiex_send_processed_packet(priv, ptr, ptr_index, flags);
/* ra_list_spinlock has been freed in
mwifiex_send_processed_packet() */
return 0;
}
if (!ptr->is_11n_enabled ||
ptr->ba_status ||
priv->wps.session_enable) {
if (ptr->is_11n_enabled &&
ptr->ba_status &&
ptr->amsdu_in_ampdu &&
mwifiex_is_amsdu_allowed(priv, tid) &&
mwifiex_is_11n_aggragation_possible(priv, ptr,
adapter->tx_buf_size))
mwifiex_11n_aggregate_pkt(priv, ptr, ptr_index, flags);
/* ra_list_spinlock has been freed in
* mwifiex_11n_aggregate_pkt()
*/
else
mwifiex_send_single_packet(priv, ptr, ptr_index, flags);
/* ra_list_spinlock has been freed in
* mwifiex_send_single_packet()
*/
} else {
if (mwifiex_is_ampdu_allowed(priv, ptr, tid) &&
ptr->ba_pkt_count > ptr->ba_packet_thr) {
if (mwifiex_space_avail_for_new_ba_stream(adapter)) {
mwifiex_create_ba_tbl(priv, ptr->ra, tid,
BA_SETUP_INPROGRESS);
mwifiex_send_addba(priv, tid, ptr->ra);
} else if (mwifiex_find_stream_to_delete
(priv, tid, &tid_del, ra)) {
mwifiex_create_ba_tbl(priv, ptr->ra, tid,
BA_SETUP_INPROGRESS);
mwifiex_send_delba(priv, tid_del, ra, 1);
}
}
if (mwifiex_is_amsdu_allowed(priv, tid) &&
mwifiex_is_11n_aggragation_possible(priv, ptr,
adapter->tx_buf_size))
mwifiex_11n_aggregate_pkt(priv, ptr, ptr_index, flags);
/* ra_list_spinlock has been freed in
mwifiex_11n_aggregate_pkt() */
else
mwifiex_send_single_packet(priv, ptr, ptr_index, flags);
/* ra_list_spinlock has been freed in
mwifiex_send_single_packet() */
}
return 0;
}
void mwifiex_process_bypass_tx(struct mwifiex_adapter *adapter)
{
struct mwifiex_tx_param tx_param;
struct sk_buff *skb;
struct mwifiex_txinfo *tx_info;
struct mwifiex_private *priv;
int i;
if (adapter->data_sent || adapter->tx_lock_flag)
return;
for (i = 0; i < adapter->priv_num; ++i) {
priv = adapter->priv[i];
if (!priv)
continue;
if (adapter->if_ops.is_port_ready &&
!adapter->if_ops.is_port_ready(priv))
continue;
if (skb_queue_empty(&priv->bypass_txq))
continue;
skb = skb_dequeue(&priv->bypass_txq);
tx_info = MWIFIEX_SKB_TXCB(skb);
/* no aggregation for bypass packets */
tx_param.next_pkt_len = 0;
if (mwifiex_process_tx(priv, skb, &tx_param) == -EBUSY) {
skb_queue_head(&priv->bypass_txq, skb);
tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT;
} else {
atomic_dec(&adapter->bypass_tx_pending);
}
}
}
/*
* This function transmits the highest priority packet awaiting in the
* WMM Queues.
*/
void
mwifiex_wmm_process_tx(struct mwifiex_adapter *adapter)
{
do {
if (mwifiex_dequeue_tx_packet(adapter))
break;
if (adapter->iface_type != MWIFIEX_SDIO) {
if (adapter->data_sent ||
adapter->tx_lock_flag)
break;
} else {
if (atomic_read(&adapter->tx_queued) >=
MWIFIEX_MAX_PKTS_TXQ)
break;
}
} while (!mwifiex_wmm_lists_empty(adapter));
}
| {
"pile_set_name": "Github"
} |
using System;
namespace LightningQueues.Storage
{
public interface IMessageStore : IDisposable
{
ITransaction BeginTransaction();
void CreateQueue(string queueName);
void StoreIncomingMessages(params Message[] messages);
void StoreIncomingMessages(ITransaction transaction, params Message[] messages);
void DeleteIncomingMessages(params Message[] messages);
IObservable<Message> PersistedMessages(string queueName);
IObservable<OutgoingMessage> PersistedOutgoingMessages();
void MoveToQueue(ITransaction transaction, string queueName, Message message);
void SuccessfullyReceived(ITransaction transaction, Message message);
void StoreOutgoing(ITransaction tx, OutgoingMessage message);
int FailedToSend(OutgoingMessage message);
void SuccessfullySent(params OutgoingMessage[] messages);
Message GetMessage(string queueName, MessageId messageId);
string[] GetAllQueues();
void ClearAllStorage();
}
}
| {
"pile_set_name": "Github"
} |
"""Throughput server."""
import sys
from twisted.protocols.wire import Discard
from twisted.internet import protocol, reactor
from twisted.python import log
def main():
f = protocol.ServerFactory()
f.protocol = Discard
reactor.listenTCP(8000, f)
reactor.run()
if __name__ == '__main__':
main()
| {
"pile_set_name": "Github"
} |
function obj = loadobj(s)
% LOADOBJ Initialize a DagNN object from a structure.
% OBJ = LOADOBJ(S) initializes a DagNN objet from the structure
% S. It is the opposite of S = OBJ.SAVEOBJ().
% If S is a string, initializes the DagNN object with data
% from a mat-file S. Otherwise, if S is an instance of `dagnn.DagNN`,
% returns S.
% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if ischar(s) s = load(s); end
if isstruct(s)
assert(isfield(s, 'layers'), 'Invalid model.');
if ~isstruct(s.layers)
warning('The model appears to be `simplenn` model. Using `fromSimpleNN` instead.');
obj = dagnn.DagNN.fromSimpleNN(s);
return;
end
obj = dagnn.DagNN() ;
try
for l = 1:numel(s.layers)
constr = str2func(s.layers(l).type) ;
block = constr() ;
block.load(struct(s.layers(l).block)) ;
obj.addLayer(...
s.layers(l).name, ...
block, ...
s.layers(l).inputs, ...
s.layers(l).outputs, ...
s.layers(l).params,...
'skipRebuild', true) ;
end
catch e % Make sure the DagNN object is in valid state
obj.rebuild();
rethrow(e);
end
obj.rebuild();
if isfield(s, 'params')
for f = setdiff(fieldnames(s.params)','name')
f = char(f) ;
for i = 1:numel(s.params)
p = obj.getParamIndex(s.params(i).name) ;
obj.params(p).(f) = s.params(i).(f) ;
end
end
end
if isfield(s, 'vars')
for f = setdiff(fieldnames(s.vars)','name')
f = char(f) ;
for i = 1:numel(s.vars)
p = obj.getVarIndex(s.vars(i).name) ;
obj.vars(p).(f) = s.vars(i).(f) ;
end
end
end
for f = setdiff(fieldnames(s)', {'vars','params','layers'})
f = char(f) ;
obj.(f) = s.(f) ;
end
elseif isa(s, 'dagnn.DagNN')
obj = s ;
else
error('Unknown data type %s for `loadobj`.', class(s));
end
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.