text
stringlengths 2
1.04M
| meta
dict |
---|---|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| AUTO-LOADER
| -------------------------------------------------------------------
| This file specifies which systems should be loaded by default.
|
| In order to keep the framework as light-weight as possible only the
| absolute minimal resources are loaded by default. For example,
| the database is not connected to automatically since no assumption
| is made regarding whether you intend to use it. This file lets
| you globally define which systems you would like loaded with every
| request.
|
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Drivers
| 4. Helper files
| 5. Custom config files
| 6. Language files
| 7. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packages
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in system/libraries/ or your
| application/libraries/ directory, with the addition of the
| 'database' library, which is somewhat of a special case.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'email', 'session');
|
| You can also supply an alternative library name to be assigned
| in the controller:
|
| $autoload['libraries'] = array('user_agent' => 'ua');
*/
$autoload['libraries'] = array('breadcrumbs', 'parsedown', 'session','tools','jsondb','form_validation');
/*
| -------------------------------------------------------------------
| Auto-load Drivers
| -------------------------------------------------------------------
| These classes are located in system/libraries/ or in your
| application/libraries/ directory, but are also placed inside their
| own subdirectory and they extend the CI_Driver_Library class. They
| offer multiple interchangeable driver options.
|
| Prototype:
|
| $autoload['drivers'] = array('cache');
|
| You can also supply an alternative property name to be assigned in
| the controller:
|
| $autoload['drivers'] = array('cache' => 'cch');
|
*/
$autoload['drivers'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array('url');
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();
| {
"content_hash": "e13c7fbd103ce41c7400cd0888f4ad93",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 105,
"avg_line_length": 30.385185185185186,
"alnum_prop": 0.47952218430034127,
"repo_name": "mnavarrocarter/markdownblog",
"id": "b74a951523eb34c8454ebd8cae7c2fa25c34f793",
"size": "4102",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/config/autoload.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "CSS",
"bytes": "67738"
},
{
"name": "HTML",
"bytes": "34012"
},
{
"name": "JavaScript",
"bytes": "48165"
},
{
"name": "PHP",
"bytes": "1903463"
}
],
"symlink_target": ""
} |
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Comment',
{ text: { type: DataTypes.STRING,
validate: { notEmpty: {msg: "Falta Comentario"}}
},
accepted: { type: DataTypes.BOOLEAN,
defaultValue: false
}
});
}; | {
"content_hash": "a4c3e759b67eeff2c732bfe0a0ee42ee",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 49,
"avg_line_length": 24.5,
"alnum_prop": 0.689795918367347,
"repo_name": "quevedoclara/quiz",
"id": "869949cd1a786a07231aea321719b4f9cdb81075",
"size": "245",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "models/comment.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1109"
},
{
"name": "HTML",
"bytes": "8552"
},
{
"name": "JavaScript",
"bytes": "29689"
}
],
"symlink_target": ""
} |
package com.example.leon.coolweather.service;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import com.example.leon.coolweather.gson.Weather;
import com.example.leon.coolweather.util.HttpUtil;
import com.example.leon.coolweather.util.Utility;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class AutoUpdateService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Not yet implemented");
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
updateWeather();
updateBingPic();
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this,AutoUpdateService.class);
PendingIntent pi = PendingIntent.getService(this,0,i,0);
int anHour = 8 * 60 * 60 * 1000; //8小时的毫秒数
//Log.d("AutoUpdateService:","started");
long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
return super.onStartCommand(intent, flags, startId);
}
private void updateWeather() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = sharedPreferences.getString("weather",null);
if(weatherString != null){
Weather weather = Utility.handleWeatherResponse(weatherString);
String weatherId = weather.basic.weatherId;
String weatherUrl = "http://guolin.tech/api/weather?cityid="+weatherId+"&key=bc0418b57b2d4918819d3974ac1285d9";
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String weatherString = response.body().string();
Weather weather = Utility.handleWeatherResponse(weatherString);
if(weather != null && weather.status.equals("ok")){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("weather",weatherString);
editor.apply();
}
}
});
}
}
private void updateBingPic() {
String bingPicUrl = "http://guolin.tech/api/bing_pic";
HttpUtil.sendOkHttpRequest(bingPicUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String bingPicString = response.body().string();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("bingPic",bingPicString);
editor.apply();
}
});
}
}
| {
"content_hash": "fbb00db5485a758a957e7882b01181cc",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 132,
"avg_line_length": 38.103092783505154,
"alnum_prop": 0.6542207792207793,
"repo_name": "Leon-Scott/coolweather",
"id": "976fba99f789363941d2e2ff74eb0ab202a23ab6",
"size": "3708",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/example/leon/coolweather/service/AutoUpdateService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "34445"
}
],
"symlink_target": ""
} |
//
// RXAppStorePopViewController.m
// RXVerifyExample
//
// Created by Rush.D.Xzj on 2019/10/22.
// Copyright © 2019 Rush.D.Xzj. All rights reserved.
//
#import "RXAppStorePopViewController.h"
typedef struct {
BOOL responseScrollViewDidScroll:1;
BOOL responseScrollViewWillBeginDragging:1;
BOOL responseScrollViewWillEndDragging:1;
BOOL responseScrollViewDidEndDragging:1;
BOOL responseScrollViewWillBeginDecelerating:1;
BOOL responseScrollViewDidEndDecelerating:1;
BOOL responseScrollViewDidEndScrollingAnimation:1;
BOOL responseReloadFreeTrafficDataDone:1;
} KSFeedComponentScrollFlags;
@interface RXAppStorePopViewController ()
@property (nonatomic) KSFeedComponentScrollFlags flags;
@end
@implementation RXAppStorePopViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UIView *top = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
self.view.backgroundColor = [UIColor greenColor];
top.backgroundColor = [UIColor blueColor];
[self.view addSubview:top];
KSFeedComponentScrollFlags flag = self.flags;
flag.responseReloadFreeTrafficDataDone = YES;
self.flags = flag;
// _flags.responseScrollViewDidScroll = YES;
[self.view rx_addGestureRecognizerWithTarget:self action:@selector(viewAction2)];
}
- (void)viewAction2 {
[self dismissViewControllerAnimated:YES completion:^{
NSLog(@"5555");
}];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
| {
"content_hash": "0040c21b810fde487538d552e63496f2",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 102,
"avg_line_length": 30.416666666666668,
"alnum_prop": 0.7501369863013698,
"repo_name": "xzjxylophone/RXVerifyExample",
"id": "e711091785877c43410209972f65aa03ebf90ba7",
"size": "1826",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RXVerifyExample/RXVerifyExample/Verify/UI/AppStore/RXAppStorePopViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3331"
},
{
"name": "C++",
"bytes": "1578988"
},
{
"name": "JavaScript",
"bytes": "145"
},
{
"name": "LLVM",
"bytes": "45738"
},
{
"name": "Objective-C",
"bytes": "1454563"
},
{
"name": "Objective-C++",
"bytes": "9289"
},
{
"name": "Ruby",
"bytes": "1589"
}
],
"symlink_target": ""
} |
var rAF = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) { return window.setTimeout(callback, 1000 / 60); };
var cAF = window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.oCancelAnimationFrame ||
window.msCancelAnimationFrame ||
function (id) { clearTimeout(id); };
var utils = (function () {
var me = {};
var _elementStyle = document.createElement('div').style;
var _vendor = (function () {
var vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'],
transform,
i = 0,
l = vendors.length;
for ( ; i < l; i++ ) {
transform = vendors[i] + 'ransform';
if ( transform in _elementStyle ) return vendors[i].substr(0, vendors[i].length-1);
}
return false;
})();
function _prefixStyle (style) {
if ( _vendor === false ) return false;
if ( _vendor === '' ) return style;
return _vendor + style.charAt(0).toUpperCase() + style.substr(1);
}
me.getTime = Date.now || function getTime () { return new Date().getTime(); };
me.extend = function (target, obj) {
for ( var i in obj ) {
target[i] = obj[i];
}
};
me.addEvent = function (el, type, fn, capture) {
el.addEventListener(type, fn, !!capture);
};
me.removeEvent = function (el, type, fn, capture) {
el.removeEventListener(type, fn, !!capture);
};
me.prefixPointerEvent = function (pointerEvent) {
return window.MSPointerEvent ?
'MSPointer' + pointerEvent.charAt(9).toUpperCase() + pointerEvent.substr(10):
pointerEvent;
};
me.momentum = function (current, start, time, lowerMargin, wrapperSize, deceleration) {
var distance = current - start,
speed = Math.abs(distance) / time,
destination,
duration;
deceleration = deceleration === undefined ? 0.0006 : deceleration;
destination = current + ( speed * speed ) / ( 2 * deceleration ) * ( distance < 0 ? -1 : 1 );
duration = speed / deceleration;
if ( destination < lowerMargin ) {
destination = wrapperSize ? lowerMargin - ( wrapperSize / 2.5 * ( speed / 8 ) ) : lowerMargin;
distance = Math.abs(destination - current);
duration = distance / speed;
} else if ( destination > 0 ) {
destination = wrapperSize ? wrapperSize / 2.5 * ( speed / 8 ) : 0;
distance = Math.abs(current) + destination;
duration = distance / speed;
}
return {
destination: Math.round(destination),
duration: duration
};
};
var _transform = _prefixStyle('transform');
me.extend(me, {
hasTransform: _transform !== false,
hasPerspective: _prefixStyle('perspective') in _elementStyle,
hasTouch: 'ontouchstart' in window,
hasPointer: window.PointerEvent || window.MSPointerEvent, // IE10 is prefixed
hasTransition: _prefixStyle('transition') in _elementStyle
});
// This should find all Android browsers lower than build 535.19 (both stock browser and webview)
me.isBadAndroid = /Android /.test(window.navigator.appVersion) && !(/Chrome\/\d/.test(window.navigator.appVersion));
me.extend(me.style = {}, {
transform: _transform,
transitionTimingFunction: _prefixStyle('transitionTimingFunction'),
transitionDuration: _prefixStyle('transitionDuration'),
transitionDelay: _prefixStyle('transitionDelay'),
transformOrigin: _prefixStyle('transformOrigin')
});
me.hasClass = function (e, c) {
var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
return re.test(e.className);
};
me.addClass = function (e, c) {
if ( me.hasClass(e, c) ) {
return;
}
var newclass = e.className.split(' ');
newclass.push(c);
e.className = newclass.join(' ');
};
me.removeClass = function (e, c) {
if ( !me.hasClass(e, c) ) {
return;
}
var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g');
e.className = e.className.replace(re, ' ');
};
me.offset = function (el) {
var left = -el.offsetLeft,
top = -el.offsetTop;
// jshint -W084
while (el = el.offsetParent) {
left -= el.offsetLeft;
top -= el.offsetTop;
}
// jshint +W084
return {
left: left,
top: top
};
};
me.preventDefaultException = function (el, exceptions) {
for ( var i in exceptions ) {
if ( exceptions[i].test(el[i]) ) {
return true;
}
}
return false;
};
me.extend(me.eventType = {}, {
touchstart: 1,
touchmove: 1,
touchend: 1,
mousedown: 2,
mousemove: 2,
mouseup: 2,
pointerdown: 3,
pointermove: 3,
pointerup: 3,
MSPointerDown: 3,
MSPointerMove: 3,
MSPointerUp: 3
});
me.extend(me.ease = {}, {
quadratic: {
style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
fn: function (k) {
return k * ( 2 - k );
}
},
circular: {
style: 'cubic-bezier(0.1, 0.57, 0.1, 1)', // Not properly "circular" but this looks better, it should be (0.075, 0.82, 0.165, 1)
fn: function (k) {
return Math.sqrt( 1 - ( --k * k ) );
}
},
back: {
style: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)',
fn: function (k) {
var b = 4;
return ( k = k - 1 ) * k * ( ( b + 1 ) * k + b ) + 1;
}
},
bounce: {
style: '',
fn: function (k) {
if ( ( k /= 1 ) < ( 1 / 2.75 ) ) {
return 7.5625 * k * k;
} else if ( k < ( 2 / 2.75 ) ) {
return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
} else if ( k < ( 2.5 / 2.75 ) ) {
return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
} else {
return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
}
}
},
elastic: {
style: '',
fn: function (k) {
var f = 0.22,
e = 0.4;
if ( k === 0 ) { return 0; }
if ( k == 1 ) { return 1; }
return ( e * Math.pow( 2, - 10 * k ) * Math.sin( ( k - f / 4 ) * ( 2 * Math.PI ) / f ) + 1 );
}
}
});
me.tap = function (e, eventName) {
var ev = document.createEvent('Event');
ev.initEvent(eventName, true, true);
ev.pageX = e.pageX;
ev.pageY = e.pageY;
e.target.dispatchEvent(ev);
};
me.click = function (e) {
var target = e.target,
ev;
if ( !(/(SELECT|INPUT|TEXTAREA)/i).test(target.tagName) ) {
ev = document.createEvent('MouseEvents');
ev.initMouseEvent('click', true, true, e.view, 1,
target.screenX, target.screenY, target.clientX, target.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
0, null);
ev._constructed = true;
target.dispatchEvent(ev);
}
};
return me;
})();
| {
"content_hash": "da17691546cfbe5821e058de7da0c12e",
"timestamp": "",
"source": "github",
"line_count": 251,
"max_line_length": 131,
"avg_line_length": 25.41434262948207,
"alnum_prop": 0.6032293462925223,
"repo_name": "quarkstudio/iscroll",
"id": "e48545c3af3aff1e0cfb8d02100d7d14100fa418",
"size": "6379",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/utils.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "85273"
},
{
"name": "JavaScript",
"bytes": "285201"
},
{
"name": "PHP",
"bytes": "393"
}
],
"symlink_target": ""
} |
package com.pattern.flyweight;
import java.util.HashMap;
import java.util.Map;
/**
* @author krisjin
* @date 2015年1月26日
*/
public class ReportManagerFactory {
Map<String, IReportManager> financialReportManager = new HashMap<String, IReportManager>();
Map<String, IReportManager> employeeReportManager = new HashMap<String, IReportManager>();
public IReportManager getFinancialReportManager(String tenantId) {
IReportManager r = financialReportManager.get(tenantId);
if (r == null) {
r = new FinancialReportManager(tenantId);
financialReportManager.put(tenantId, r);
}
return r;
}
public IReportManager getEmployeeReportManager(String tenantId) {
IReportManager r = employeeReportManager.get(tenantId);
if (r == null) {
r = new EmployeeReportManager(tenantId);
employeeReportManager.put(tenantId, r);
}
return r;
}
}
| {
"content_hash": "3c58dcc61059c7ee6058a80b04a96143",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 95,
"avg_line_length": 29.12121212121212,
"alnum_prop": 0.6711758584807492,
"repo_name": "zoopaper/design-pattern",
"id": "310d6e9b4df8b2627f2811f29d39e0cf3c7c33f1",
"size": "967",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/pattern/flyweight/ReportManagerFactory.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "188962"
}
],
"symlink_target": ""
} |
using namespace std;
using namespace v8;
using namespace node;
enum DataType {
STRING_TYPE = 1,
BUFFER_TYPE
};
template<DataType DT> class BatchWrap {
public:
void push(const Local<Value>& val);
public:
Producer::BatchType& get() {
return _batch;
}
void reserve(size_t sz) {
_batch.reserve(sz);
}
private:
Producer::BatchType _batch;
};
template<> void BatchWrap<STRING_TYPE>::push(const Local<Value>& val) {
v8::Local<v8::String> toStr = val->ToString();
size_t size = toStr->Utf8Length();
Producer::ItemType item = Producer::ItemType::create(size + 1);
toStr->WriteUtf8(item.data());
_batch.push_back(std::move(item));
}
template<> void BatchWrap<BUFFER_TYPE>::push(const Local<Value>& val) {
_batch.push_back(Producer::ItemType(node::Buffer::Data(val), node::Buffer::Length(val)));
}
class ProducerWrap : public nnu::ClassWrap<ProducerWrap> {
public:
static const char * const CLASS_NAME; // "Producer"
static void setupMember(v8::Local<v8::FunctionTemplate>& tpl) {
Nan::SetPrototypeMethod(tpl, "pushString", wrapFunction<&ProducerWrap::push<STRING_TYPE> >);
Nan::SetPrototypeMethod(tpl, "pushBuffer", wrapFunction<&ProducerWrap::push<BUFFER_TYPE> >);
Nan::SetPrototypeMethod(tpl, "pushString2Cache", wrapFunction<&ProducerWrap::push2Cache<STRING_TYPE> >);
Nan::SetPrototypeMethod(tpl, "pushBuffer2Cache", wrapFunction<&ProducerWrap::push2Cache<BUFFER_TYPE> >);
}
static NAN_METHOD(ctor) {
Handle<Object> opt = info[0]->ToObject();
Nan::Utf8String path(opt->Get(nnu::newString("path")));
Nan::Utf8String topicName(opt->Get(nnu::newString("topic")));
TopicOpt topicOpt{ 1024 * 1024 * 1024, 8 };
Local<Value> chunkSize = opt->Get(nnu::newString("chunkSize"));
Local<Value> chunksToKeep = opt->Get(nnu::newString("chunksToKeep"));
Local<Value> bgFlush = opt->Get(nnu::newString("backgroundFlush"));
if (chunkSize->IsNumber()) topicOpt.chunkSize = size_t(chunkSize->NumberValue());
if (chunksToKeep->IsNumber()) topicOpt.chunksToKeep = size_t(chunksToKeep->NumberValue());
ProducerWrap* ptr = new ProducerWrap(*path, *topicName, &topicOpt, bgFlush->BooleanValue());
ptr->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
private:
template<DataType DT> NAN_METHOD(push) {
BatchWrap<DT> batch;
batch.reserve(info.Length());
for (int i = 0; i < info.Length(); i++) {
batch.push(info[i]);
}
_handle.push(batch.get());
}
template<DataType DT> NAN_METHOD(push2Cache) {
BatchWrap<DT> batch;
batch.reserve(info.Length());
for (int i = 0; i < info.Length(); i++) {
batch.push(info[i]);
}
_handle.push2Cache(batch.get());
}
private:
ProducerWrap(const char* path, const char* name, TopicOpt* opt, bool bgFlush) : _handle(path, name, opt) {
if (bgFlush) _handle.enableBackgroundFlush(chrono::milliseconds(200));
}
Producer _handle;
};
const char * const ProducerWrap::CLASS_NAME = "Producer";
template<DataType DT> class ReturnMaker {
public:
Local<Value> static make(const Consumer::ItemType& item);
};
template<> Local<Value> ReturnMaker<STRING_TYPE>::make(const Consumer::ItemType& item) {
return Nan::New(std::get<1>(item)).ToLocalChecked();
}
template<> Local<Value> ReturnMaker<BUFFER_TYPE>::make(const Consumer::ItemType& item) {
return Nan::CopyBuffer(std::get<1>(item), std::get<2>(item)).ToLocalChecked();
}
class ConsumerWrap : public nnu::ClassWrap<ConsumerWrap> {
public:
static const char * const CLASS_NAME; // "Consumer"
static void setupMember(v8::Local<v8::FunctionTemplate>& tpl) {
Nan::SetPrototypeMethod(tpl, "offset", wrapFunction<&ConsumerWrap::offset>);
Nan::SetPrototypeMethod(tpl, "popString", wrapFunction<&ConsumerWrap::pop<STRING_TYPE> >);
Nan::SetPrototypeMethod(tpl, "popBuffer", wrapFunction<&ConsumerWrap::pop<BUFFER_TYPE> >);
}
static NAN_METHOD(ctor) {
Local<Object> opt = info[0]->ToObject();
Nan::Utf8String path(opt->Get(nnu::newString("path")));
Nan::Utf8String topicName(opt->Get(nnu::newString("topic")));
Nan::Utf8String name(opt->Get(nnu::newString("name")));
TopicOpt topicOpt{ 1024 * 1024 * 1024, 0 };
Local<Value> chunkSize = opt->Get(nnu::newString("chunkSize"));
if (chunkSize->IsNumber()) topicOpt.chunkSize = size_t(chunkSize->NumberValue());
ConsumerWrap* ptr = new ConsumerWrap(*path, *topicName, *name, &topicOpt);
Local<Value> batchSize = opt->Get(nnu::newString("batchSize"));
if (batchSize->IsNumber()) {
size_t bs = size_t(batchSize->NumberValue());
if (bs > 0 && bs < 1024 * 1024) ptr->_batchSize = bs;
}
ptr->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
private:
NAN_METHOD(offset) {
if (_cur <= _batch.size()) {
Local<Value> ret = Nan::New(double(std::get<0>(_batch.at(_cur - 1))));
info.GetReturnValue().Set(ret);
}
}
template<DataType DT> NAN_METHOD(pop) {
if (_cur < _batch.size()) {
info.GetReturnValue().Set(ReturnMaker<DT>::make(_batch.at(_cur++)));
return ;
}
_batch.clear();
_cur = 1;
_handle.pop(_batch, _batchSize);
if (_batch.size() > 0) {
info.GetReturnValue().Set(ReturnMaker<DT>::make(_batch.at(0)));
return ;
}
}
private:
ConsumerWrap(const char* path, const char* topicName, const char* name, TopicOpt* opt) : _handle(path, topicName, name, opt), _cur(0), _batchSize(128) { }
Consumer _handle;
Consumer::BatchType _batch;
size_t _cur, _batchSize;
};
const char * const ConsumerWrap::CLASS_NAME = "Consumer";
class TopicWrap : public nnu::ClassWrap<TopicWrap> {
public:
static const char * const CLASS_NAME; // "Topic"
static void setupMember(v8::Local<v8::FunctionTemplate>& tpl) {
Nan::SetPrototypeMethod(tpl, "status", wrapFunction<&TopicWrap::status>);
}
static NAN_METHOD(ctor) {
Handle<Object> opt = info[0]->ToObject();
Nan::Utf8String path(opt->Get(nnu::newString("path")));
Nan::Utf8String topicName(opt->Get(nnu::newString("topic")));
TopicWrap *ptr = new TopicWrap(*path, *topicName);
ptr->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
private:
NAN_METHOD(status) {
TopicStatus st = _handle->status();
Local<Object> ret = Nan::New<Object>();
ret->Set(nnu::newString("producerHead"), Nan::New<Number>(double(st.producerHead)));
Local<Object> consumerHeads = Nan::New<Object>();
for (auto it : st.consumerHeads) {
consumerHeads->Set(Nan::New(it.first).ToLocalChecked(), Nan::New<Number>(double(it.second)));
}
ret->Set(nnu::newString("consumerHeads"), consumerHeads);
info.GetReturnValue().Set(ret);
}
private:
TopicWrap(const char* path, const char* topicName) : _handle(EnvManager::getEnv(path)->getTopic(topicName)) {
}
private:
Topic *_handle;
};
const char * const TopicWrap::CLASS_NAME = "Topic";
NAN_MODULE_INIT(InitAll) {
target->Set(nnu::newString("STRING_TYPE"), Nan::New(STRING_TYPE));
target->Set(nnu::newString("BUFFER_TYPE"), Nan::New(BUFFER_TYPE));
TopicWrap::setup(target);
ProducerWrap::setup(target);
ConsumerWrap::setup(target);
}
NODE_MODULE(lmdb_queue, InitAll); | {
"content_hash": "11843c5368b80c05e12ca9a0d294bb00",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 158,
"avg_line_length": 32.743589743589745,
"alnum_prop": 0.6272513703993735,
"repo_name": "talrasha007/lmdb-queue",
"id": "46891fa5295fbeab94b859bee8df7918cb65852e",
"size": "7744",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/module.cc",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "31300"
},
{
"name": "JavaScript",
"bytes": "1567"
},
{
"name": "Python",
"bytes": "1321"
}
],
"symlink_target": ""
} |
using System.IO;
using System.Xml.Serialization;
using Caliburn.Micro;
namespace csBookmarkPlugin
{
public class BookmarkList : BindableCollection<Bookmark>
{
public void Save(string file)
{
try
{
var xml = new FileStream(file, FileMode.Create);
var serializer2 = new XmlSerializer(typeof(BookmarkList));
serializer2.Serialize(xml, this);
xml.Close();
}
catch { }
}
public static BookmarkList Load(string file)
{
if (!File.Exists(file)) return new BookmarkList();
try {
using (var reader2 = new StreamReader(file)) {
var serializer2 = new XmlSerializer(typeof(BookmarkList));
var result = (BookmarkList) serializer2.Deserialize(reader2);
reader2.Close();
return result;
}
}
catch {
return new BookmarkList();
}
}
}
} | {
"content_hash": "14a2b3390028366369b6f5994d138782",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 81,
"avg_line_length": 28.128205128205128,
"alnum_prop": 0.495897903372835,
"repo_name": "TNOCS/csTouch",
"id": "ba7b3f8cfa4ae481ad56c87a341c54e2739a1506",
"size": "1099",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework/csCommonSense/Plugins/BookmarkPlugin/BookmarkList.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "6785953"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
<changeSet id="default-user-usergroup-role-update" author="ricci"
dbms="sqlite">
<comment>Update user role in default group to Administrator for all users</comment>
<sql>
UPDATE ofc_user_usergroup
SET role_code = 'A'
WHERE group_id = (SELECT ug.id FROM ofc_usergroup ug WHERE ug.name = 'default_public_group');
</sql>
</changeSet>
</databaseChangeLog> | {
"content_hash": "008c578d02d8929487f27c438a950a10",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 130,
"avg_line_length": 35.31578947368421,
"alnum_prop": 0.7302533532041728,
"repo_name": "openforis/collect",
"id": "058704c8835d0fd048dd03303dee8eeb5d8bd466",
"size": "671",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "collect-core/src/main/resources/org/openforis/collect/db/changelog/sqlite/db.changelog-20180126.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2032"
},
{
"name": "CSS",
"bytes": "492878"
},
{
"name": "HTML",
"bytes": "55093"
},
{
"name": "Java",
"bytes": "6027874"
},
{
"name": "JavaScript",
"bytes": "5049757"
},
{
"name": "Less",
"bytes": "60736"
},
{
"name": "SCSS",
"bytes": "310370"
},
{
"name": "Shell",
"bytes": "515"
},
{
"name": "TSQL",
"bytes": "1199"
},
{
"name": "XSLT",
"bytes": "8150"
}
],
"symlink_target": ""
} |
#=============================================================================
# Copyright 2006-2009 Kitware, Inc.
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
#FIXME we should put NSIS specific code here
#FIXME but I'm not doing it because I'm not able to test it...
| {
"content_hash": "18b5dd8be6ca3724f08e1c0aed8b760b",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 78,
"avg_line_length": 45.8125,
"alnum_prop": 0.5866302864938608,
"repo_name": "dava/dava.engine",
"id": "ff5083616fad2b1668f1059724bd2343a0acecc5",
"size": "4748",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "Bin/CMakeWin10/share/cmake-3.4/Modules/CPackNSIS.cmake",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "166572"
},
{
"name": "Batchfile",
"bytes": "18562"
},
{
"name": "C",
"bytes": "61621347"
},
{
"name": "C#",
"bytes": "574524"
},
{
"name": "C++",
"bytes": "50229645"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "11439187"
},
{
"name": "CSS",
"bytes": "32773"
},
{
"name": "Cuda",
"bytes": "37073"
},
{
"name": "DIGITAL Command Language",
"bytes": "27303"
},
{
"name": "Emacs Lisp",
"bytes": "44259"
},
{
"name": "Fortran",
"bytes": "8835"
},
{
"name": "GLSL",
"bytes": "3726"
},
{
"name": "Go",
"bytes": "1235"
},
{
"name": "HTML",
"bytes": "8621333"
},
{
"name": "Java",
"bytes": "232072"
},
{
"name": "JavaScript",
"bytes": "2560"
},
{
"name": "Lua",
"bytes": "43080"
},
{
"name": "M4",
"bytes": "165145"
},
{
"name": "Makefile",
"bytes": "1349214"
},
{
"name": "Mathematica",
"bytes": "4633"
},
{
"name": "Module Management System",
"bytes": "15224"
},
{
"name": "Objective-C",
"bytes": "1909821"
},
{
"name": "Objective-C++",
"bytes": "498191"
},
{
"name": "Pascal",
"bytes": "99390"
},
{
"name": "Perl",
"bytes": "396608"
},
{
"name": "Python",
"bytes": "782784"
},
{
"name": "QML",
"bytes": "43105"
},
{
"name": "QMake",
"bytes": "156"
},
{
"name": "Roff",
"bytes": "71083"
},
{
"name": "Ruby",
"bytes": "22742"
},
{
"name": "SAS",
"bytes": "16030"
},
{
"name": "Shell",
"bytes": "2482394"
},
{
"name": "Slash",
"bytes": "117430"
},
{
"name": "Smalltalk",
"bytes": "5908"
},
{
"name": "TeX",
"bytes": "428489"
},
{
"name": "Vim script",
"bytes": "133255"
},
{
"name": "Visual Basic",
"bytes": "54056"
},
{
"name": "WebAssembly",
"bytes": "13987"
}
],
"symlink_target": ""
} |
/*
* Changes:
* Mar 07, 2010: Created (Cristiano Giuffrida)
*/
#include "inc.h"
/* A single error entry. */
struct errentry {
int errnum;
char* errstr;
};
/* Initialization errors. */
PRIVATE struct errentry init_errlist[] = {
{ ENOSYS, "service does not support the requested initialization type" }
};
PRIVATE const int init_nerr = sizeof(init_errlist) / sizeof(init_errlist[0]);
/* Live update errors. */
PRIVATE struct errentry lu_errlist[] = {
{ ENOSYS, "service does not support live update" },
{ EINVAL, "service does not support the required state" },
{ EBUSY, "service is not able to prepare for the update now" },
{ EGENERIC, "generic error occurred while preparing for the update" }
};
PRIVATE const int lu_nerr = sizeof(lu_errlist) / sizeof(lu_errlist[0]);
/*===========================================================================*
* rs_strerror *
*===========================================================================*/
PRIVATE char * rs_strerror(int errnum, struct errentry *errlist, const int nerr)
{
int i;
for(i=0; i < nerr; i++) {
if(errnum == errlist[i].errnum)
return errlist[i].errstr;
}
return strerror(-errnum);
}
/*===========================================================================*
* init_strerror *
*===========================================================================*/
PUBLIC char * init_strerror(int errnum)
{
return rs_strerror(errnum, init_errlist, init_nerr);
}
/*===========================================================================*
* lu_strerror *
*===========================================================================*/
PUBLIC char * lu_strerror(int errnum)
{
return rs_strerror(errnum, lu_errlist, lu_nerr);
}
| {
"content_hash": "c3f1b8a4302401037ad33c7e71db11de",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 80,
"avg_line_length": 33.189655172413794,
"alnum_prop": 0.44467532467532467,
"repo_name": "ducis/operating-system-labs",
"id": "b866956b8fe2cc3bcc81eb98ae79c54cb8f6b627",
"size": "1925",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "sr/lsri/servers/rs/error.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "708516"
},
{
"name": "Awk",
"bytes": "10251"
},
{
"name": "Batchfile",
"bytes": "72"
},
{
"name": "C",
"bytes": "45522115"
},
{
"name": "C++",
"bytes": "219024"
},
{
"name": "CSS",
"bytes": "5460"
},
{
"name": "E",
"bytes": "73335"
},
{
"name": "HTML",
"bytes": "123135"
},
{
"name": "Lex",
"bytes": "56847"
},
{
"name": "M4",
"bytes": "26976"
},
{
"name": "Makefile",
"bytes": "592408"
},
{
"name": "Max",
"bytes": "11343"
},
{
"name": "Objective-C",
"bytes": "86604"
},
{
"name": "Perl",
"bytes": "313518"
},
{
"name": "Roff",
"bytes": "6262047"
},
{
"name": "Shell",
"bytes": "977936"
},
{
"name": "XSLT",
"bytes": "34635"
},
{
"name": "Yacc",
"bytes": "188442"
}
],
"symlink_target": ""
} |
package org.apache.spark.sql.types
import scala.math.{Fractional, Numeric, Ordering}
import scala.math.Numeric.DoubleAsIfIntegral
import scala.reflect.runtime.universe.typeTag
import org.apache.spark.annotation.DeveloperApi
import org.apache.spark.sql.catalyst.ScalaReflectionLock
import org.apache.spark.util.Utils
/**
* :: DeveloperApi ::
* The data type representing `Double` values. Please use the singleton [[DataTypes.DoubleType]].
*/
@DeveloperApi
class DoubleType private() extends FractionalType {
// The companion object and this class is separated so the companion object also subclasses
// this type. Otherwise, the companion object would be of type "DoubleType$" in byte code.
// Defined with a private constructor so the companion object is the only possible instantiation.
private[sql] type InternalType = Double
@transient private[sql] lazy val tag = ScalaReflectionLock.synchronized { typeTag[InternalType] }
private[sql] val numeric = implicitly[Numeric[Double]]
private[sql] val fractional = implicitly[Fractional[Double]]
private[sql] val ordering = new Ordering[Double] {
override def compare(x: Double, y: Double): Int = Utils.nanSafeCompareDoubles(x, y)
}
private[sql] val asIntegral = DoubleAsIfIntegral
/**
* The default size of a value of the DoubleType is 8 bytes.
*/
override def defaultSize: Int = 8
private[spark] override def asNullable: DoubleType = this
}
case object DoubleType extends DoubleType
| {
"content_hash": "d61644f0d8307d70a5bd425991bb2d4f",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 99,
"avg_line_length": 37.8974358974359,
"alnum_prop": 0.7679296346414073,
"repo_name": "gioenn/xSpark",
"id": "e553f65f3c99d1703df7a085da55f83b75777f8d",
"size": "2278",
"binary": false,
"copies": "2",
"ref": "refs/heads/dependabot/maven/fasterxml.jackson.version-2.10.1",
"path": "sql/catalyst/src/main/scala/org/apache/spark/sql/types/DoubleType.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "29610"
},
{
"name": "Batchfile",
"bytes": "24063"
},
{
"name": "C",
"bytes": "1493"
},
{
"name": "CSS",
"bytes": "23625"
},
{
"name": "HTML",
"bytes": "2924"
},
{
"name": "Java",
"bytes": "2573379"
},
{
"name": "JavaScript",
"bytes": "106909"
},
{
"name": "Makefile",
"bytes": "7774"
},
{
"name": "Python",
"bytes": "1960082"
},
{
"name": "R",
"bytes": "639321"
},
{
"name": "Roff",
"bytes": "26888"
},
{
"name": "SQLPL",
"bytes": "3603"
},
{
"name": "Scala",
"bytes": "18680196"
},
{
"name": "Shell",
"bytes": "134465"
},
{
"name": "Thrift",
"bytes": "33605"
}
],
"symlink_target": ""
} |
#pragma once
#include <memory>
#include "context.h"
namespace mica
{
class NotificationManager;
class ResManager;
namespace input
{
class KeyboardManager;
}
}
namespace mica
{
/**
* The normal implementation of Context
*/
class ContextImpl : public Context
{
public:
ContextImpl();
virtual ~ContextImpl();
input::KeyboardManager* getKeyboardManager() const override
{
return getKeyboardManager_();
}
NotificationManager* getNotificationManager() const override
{
return getNotificationManager_();
}
ResManager* getResManager() const override
{
return m_res_manager.get();
}
private:
input::KeyboardManager* getKeyboardManager_() const;
NotificationManager* getNotificationManager_() const;
std::unique_ptr<ResManager> m_res_manager;
// For lazy init
mutable std::unique_ptr<NotificationManager> m_notification_manager;
// For lazy init
mutable std::unique_ptr<input::KeyboardManager> m_keyboard_manager;
};
}
| {
"content_hash": "3b4fc7be18726e796f90912bed1b41fa",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 69,
"avg_line_length": 15.60655737704918,
"alnum_prop": 0.7457983193277311,
"repo_name": "nkming2/MagicalGirlMica",
"id": "637d7656b72bdcf65f5cfb0e0afaaaa753cefc93",
"size": "1061",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/context_impl.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1380"
},
{
"name": "C++",
"bytes": "67195"
},
{
"name": "Gnuplot",
"bytes": "3781"
}
],
"symlink_target": ""
} |
<?php
declare (strict_types=1);
namespace RectorPrefix20210615;
use Rector\PHPUnit\Rector\MethodCall\ReplaceAssertArraySubsetWithDmsPolyfillRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (\Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator $containerConfigurator) : void {
$services = $containerConfigurator->services();
$services->set(\Rector\PHPUnit\Rector\MethodCall\ReplaceAssertArraySubsetWithDmsPolyfillRector::class);
};
| {
"content_hash": "3058e85086aa690723a34c19920f5e72",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 137,
"avg_line_length": 48.72727272727273,
"alnum_prop": 0.8414179104477612,
"repo_name": "RectorPHP/Rector",
"id": "6cbbe70f02effc6157b05e3d9f6e3c9a803aa5dd",
"size": "536",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "vendor/rector/rector-phpunit/config/sets/phpunit80-dms.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "503421"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "7178cfd9b9c9ec6552b40b3dceabb00f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "5e03943cbc176decc7b7d674d5a3b8cd40f8d982",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rubus/Rubus bremon/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<h2>FreeStyleProjecthealthReport</h2>
<ul class="parameter">
<li class="param-required-false">description : String
<br/>
</li>
</ul>
<ul class="parameter">
<li class="param-required-false">iconClassName : String
<br/>
</li>
</ul>
<ul class="parameter">
<li class="param-required-false">iconUrl : String
<br/>
</li>
</ul>
<ul class="parameter">
<li class="param-required-false">score : Integer
<br/>
</li>
</ul>
<ul class="parameter">
<li class="param-required-false">Underscoreclass : String
<br/>
</li>
</ul>
| {
"content_hash": "5ec42b5ed2c63f6d16336261eaf06436",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 59,
"avg_line_length": 21.153846153846153,
"alnum_prop": 0.6345454545454545,
"repo_name": "cliffano/swaggy-jenkins",
"id": "cb0ec9e3df858903cc6d32ee42a583613aeb19e2",
"size": "551",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "clients/dynamic-html/generated/docs/models/FreeStyleProjecthealthReport.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ada",
"bytes": "569823"
},
{
"name": "Apex",
"bytes": "741346"
},
{
"name": "Batchfile",
"bytes": "14792"
},
{
"name": "C",
"bytes": "971274"
},
{
"name": "C#",
"bytes": "5131336"
},
{
"name": "C++",
"bytes": "7799032"
},
{
"name": "CMake",
"bytes": "20609"
},
{
"name": "CSS",
"bytes": "4873"
},
{
"name": "Clojure",
"bytes": "129018"
},
{
"name": "Crystal",
"bytes": "864941"
},
{
"name": "Dart",
"bytes": "876777"
},
{
"name": "Dockerfile",
"bytes": "7385"
},
{
"name": "Eiffel",
"bytes": "424642"
},
{
"name": "Elixir",
"bytes": "139252"
},
{
"name": "Elm",
"bytes": "187067"
},
{
"name": "Emacs Lisp",
"bytes": "191"
},
{
"name": "Erlang",
"bytes": "373074"
},
{
"name": "F#",
"bytes": "556012"
},
{
"name": "Gherkin",
"bytes": "951"
},
{
"name": "Go",
"bytes": "345227"
},
{
"name": "Groovy",
"bytes": "89524"
},
{
"name": "HTML",
"bytes": "2367424"
},
{
"name": "Haskell",
"bytes": "680841"
},
{
"name": "Java",
"bytes": "12164874"
},
{
"name": "JavaScript",
"bytes": "1959006"
},
{
"name": "Kotlin",
"bytes": "1280953"
},
{
"name": "Lua",
"bytes": "322316"
},
{
"name": "Makefile",
"bytes": "11882"
},
{
"name": "Nim",
"bytes": "65818"
},
{
"name": "OCaml",
"bytes": "94665"
},
{
"name": "Objective-C",
"bytes": "464903"
},
{
"name": "PHP",
"bytes": "4383673"
},
{
"name": "Perl",
"bytes": "743304"
},
{
"name": "PowerShell",
"bytes": "678274"
},
{
"name": "Python",
"bytes": "5529523"
},
{
"name": "QMake",
"bytes": "6915"
},
{
"name": "R",
"bytes": "840841"
},
{
"name": "Raku",
"bytes": "10945"
},
{
"name": "Ruby",
"bytes": "328360"
},
{
"name": "Rust",
"bytes": "1735375"
},
{
"name": "Scala",
"bytes": "1387368"
},
{
"name": "Shell",
"bytes": "407167"
},
{
"name": "Swift",
"bytes": "342562"
},
{
"name": "TypeScript",
"bytes": "3060093"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace DiContainerBenchmarks\Fixture\B;
class FixtureB675
{
}
| {
"content_hash": "57b1dc5299604deef196b0a2a31cbb9b",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 42,
"avg_line_length": 11,
"alnum_prop": 0.7676767676767676,
"repo_name": "kocsismate/php-di-container-benchmarks",
"id": "fb8b10d85bba980964aeb07f30b51d74bba8dc01",
"size": "99",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Fixture/B/FixtureB675.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "172"
},
{
"name": "HCL",
"bytes": "3637"
},
{
"name": "HTML",
"bytes": "107490"
},
{
"name": "Makefile",
"bytes": "1065"
},
{
"name": "PHP",
"bytes": "919987"
},
{
"name": "Shell",
"bytes": "2632"
}
],
"symlink_target": ""
} |
<?php
session_start();
if(session_destroy())
{
header("Location: ../admin/");
}
?> | {
"content_hash": "a07d569d9a38f4d3d6c0648d8b53dd1a",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 38,
"avg_line_length": 12.375,
"alnum_prop": 0.5050505050505051,
"repo_name": "dextel2/Admission",
"id": "c81cea4fb3519a8f72da43b71f63ce074331a28e",
"size": "99",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "admin/logout.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "44172"
},
{
"name": "Hack",
"bytes": "6195"
},
{
"name": "JavaScript",
"bytes": "4759"
},
{
"name": "PHP",
"bytes": "158691"
}
],
"symlink_target": ""
} |
using System;
using System.Collections;
using System.Collections.Generic;
using mattmc3.dotmore.Diagnostics;
namespace mattmc3.dotmore.Collections.Generic {
/// <summary>
/// This dictionary allows you to add items to it without checking whether the key already
/// exists. If it does, the value is just overwritten. Retrieval of items that don't exist
/// return Nothing instead of throwing an exception. Concept and name (but no code) comes
/// from Rhino ETL (http://www.codeproject.com/KB/cs/ETLWithCSharp.aspx).
/// </summary>
public class QuackingDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary {
#region Fields/Properties
private IDictionary<TKey, TValue> _dict;
public int Count {
get { return _dict.Count; }
}
public TValue this[TKey key] {
get {
TValue result;
if (_dict.TryGetValue(key, out result)) {
return result;
}
else {
return default(TValue);
}
}
set {
if (_dict.ContainsKey(key)) {
_dict[key] = value;
}
else {
_dict.Add(key, value);
}
}
}
public ICollection<TKey> Keys {
get { return _dict.Keys; }
}
public ICollection<TValue> Values {
get { return _dict.Values; }
}
#endregion
#region Constructors
public QuackingDictionary() {
_dict = new Dictionary<TKey, TValue>();
}
public QuackingDictionary(IEqualityComparer<TKey> comparer) {
_dict = new Dictionary<TKey, TValue>(comparer);
}
public QuackingDictionary(IDictionary<TKey, TValue> storageDictionary) {
if (storageDictionary == null) {
throw new ArgumentNullException("storageDictionary", "The dictionary to use as storage cannot be null.");
}
_dict = storageDictionary;
}
#endregion
#region Methods
public void Clear() {
_dict.Clear();
}
public bool Contains(TKey key, TValue value) {
return _dict.Contains(new KeyValuePair<TKey, TValue>(key, value));
}
public bool ContainsKey(TKey key) {
return _dict.ContainsKey(key);
}
public bool Remove(TKey key) {
return _dict.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value) {
return _dict.TryGetValue(key, out value);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
return _dict.GetEnumerator();
}
#endregion
#region IDictionary<TKey, TValue> interface implementation
void IDictionary<TKey, TValue>.Add(TKey key, TValue value) {
this[key] = value;
}
bool IDictionary<TKey, TValue>.ContainsKey(TKey key) {
return ContainsKey(key);
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys {
get {
return this.Keys;
}
}
bool IDictionary<TKey, TValue>.Remove(TKey key) {
return Remove(key);
}
bool IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value) {
return TryGetValue(key, out value);
}
ICollection<TValue> IDictionary<TKey, TValue>.Values {
get {
return this.Values;
}
}
TValue IDictionary<TKey, TValue>.this[TKey key] {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) {
this[item.Key] = item.Value;
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear() {
Clear();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) {
return Contains(item.Key, item.Value);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
_dict.CopyTo(array, arrayIndex);
}
int ICollection<KeyValuePair<TKey, TValue>>.Count {
get {
return this.Count;
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
get { throw new NotImplementedException(); }
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) {
return _dict.Remove(item);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() {
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
#endregion
#region IDictionary implementation
void IDictionary.Add(object key, object value) {
var d = GetIDictionary();
if (d.Contains(key)) {
d[key] = value;
}
else {
d.Add(key, value);
}
}
void IDictionary.Clear() {
Clear();
}
bool IDictionary.Contains(object key) {
return GetIDictionary().Contains(key);
}
IDictionaryEnumerator IDictionary.GetEnumerator() {
return GetIDictionary().GetEnumerator();
}
bool IDictionary.IsFixedSize {
get {
return GetIDictionary().IsFixedSize;
}
}
bool IDictionary.IsReadOnly {
get {
return GetIDictionary().IsReadOnly;
}
}
ICollection IDictionary.Keys {
get {
return GetIDictionary().Keys;
}
}
void IDictionary.Remove(object key) {
if (_dict.ContainsKey((TKey)key)) {
_dict.Remove((TKey)key);
}
}
ICollection IDictionary.Values {
get {
return GetIDictionary().Values;
}
}
object IDictionary.this[object key] {
get {
var d = GetIDictionary();
if (d.Contains(key)) {
return d[key];
}
else {
return null;
}
}
set {
var d = GetIDictionary();
if (d.Contains(key)) {
d[key] = value;
}
else {
d.Add(key, value);
}
}
}
void ICollection.CopyTo(Array array, int index) {
GetIDictionary().CopyTo(array, index);
}
int ICollection.Count {
get {
return this.Count;
}
}
bool ICollection.IsSynchronized {
get {
return GetIDictionary().IsSynchronized;
}
}
object ICollection.SyncRoot {
get {
return GetIDictionary().SyncRoot;
}
}
private IDictionary GetIDictionary() {
return (IDictionary)_dict;
}
#endregion
}
}
| {
"content_hash": "b3ae2c32d43ffb155cda3091d1fccecf",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 109,
"avg_line_length": 21.60070671378092,
"alnum_prop": 0.6301325044986095,
"repo_name": "mattmc3/dotmore",
"id": "a5691e927144b916aad9cdfe54521a4e4edb6567",
"size": "6115",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dotmore/Collections/Generic/QuackingDictionary.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "89127"
}
],
"symlink_target": ""
} |
<!--
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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.maven</groupId>
<artifactId>wso2-esb-sequence-plugin</artifactId>
<version>2.0.6</version>
<packaging>maven-plugin</packaging>
<name>Maven ESB Sequence Plugin</name>
<description>Maven plugin which creates and builds Sequence artifacts</description>
<build>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh</artifactId>
<version>1.0-beta-6</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
<distributionManagement>
<repository>
<id>wso2-maven2-repository</id>
<name>WSO2 Maven2 Repository</name>
<url>scp://dist.wso2.org/home/httpd/dist.wso2.org/maven2/</url>
</repository>
</distributionManagement>
<dependencies>
<dependency>
<groupId>biz.aQute</groupId>
<artifactId>bndlib</artifactId>
<version>0.0.357</version>
</dependency>
<dependency>
<groupId>net.sf.kxml</groupId>
<artifactId>kxml2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.bundlerepository</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.osgi.core</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.osgi.service.obr</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-model</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-archiver</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact-manager</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-settings</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-dependency-tree</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-provider-api</artifactId>
<version>1.0-beta-2</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-container-default</artifactId>
<version>1.0-alpha-9-stable-1</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-archiver</artifactId>
<version>1.0-alpha-7</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-utils</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-plugin-testing-harness</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wso2.maven</groupId>
<artifactId>org.wso2.maven.capp</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.wso2.maven</groupId>
<artifactId>org.wso2.maven.esb</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>run-its</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-invoker-plugin</artifactId>
<version>1.4</version>
<configuration>
<projectsDirectory>src/it</projectsDirectory>
<pomIncludes>
<pomInclude>*/pom.xml</pomInclude>
</pomIncludes>
<postBuildHookScript>verify</postBuildHookScript>
<localRepositoryPath>${project.build.directory}/local-repo</localRepositoryPath>
<goals>
<goal>clean</goal>
<goal>package</goal>
</goals>
<settingsFile>src/it/settings.xml</settingsFile>
<cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>install</goal>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<repositories>
<repository>
<id>wso2-maven2-repository-1</id>
<url>http://dist.wso2.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>wso2-maven2-repository-1</id>
<url>http://dist.wso2.org/maven2</url>
</pluginRepository>
<pluginRepository>
<id>wso2-maven2-repository-2</id>
<url>http://dist.wso2.org/snapshots/maven2</url>
</pluginRepository>
<pluginRepository>
<id>repository.dev.java.net-maven2</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</pluginRepository>
</pluginRepositories>
</project>
| {
"content_hash": "c92cc1e3ed1632b9da445b79ac033331",
"timestamp": "",
"source": "github",
"line_count": 219,
"max_line_length": 104,
"avg_line_length": 31.506849315068493,
"alnum_prop": 0.6673913043478261,
"repo_name": "asankas/developer-studio",
"id": "dd12142114488d16d1779c951416c7d4e0c4dff0",
"size": "6900",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dependencies/wso2-esb-sequence-plugin/pom.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
@charset "utf-8";
/* Icon */
.tabsHeader li.main a span span, #taskbar li .taskbutton span { background:url(./images/icon.png) no-repeat;}
/* Panel */
.panel,
.panel .panelHeader, .panel .panelHeaderContent, .panel .panelHeaderContent h1,
.panel .panelFooter, .panel .panelFooterContent { background:url(./images/panel/panel.png) no-repeat;}
.panel .expandable, .panel .collapsable { background:url(./images/panel/panel_icon.png) no-repeat;}
.panel .panelHeaderContent h1 { color:#183152; }
.panel .panelContent { border-color:#b8d0d6; background:#eef4f5;}
.panel .grid { border-color:#b8d0d6;}
/* Tabs */
.tabs, .tabsHeader, .tabsHeaderContent,
.tabs .tabsHeader ul, .tabs .tabsHeader li, .tabs .tabsHeader li a, .tabs .tabsHeader li span,
.tabs .tabsFooter, .tabs .tabsFooterContent { background:url(./images/tabs/tabspanel.png) no-repeat;}
.tabs .tabsHeader li a { color:#03408b;}
.tabs .tabsHeader li span { color:#183152;}
.tabs .tabsContent { border-color:#b8d0d6; background:#eef4f5;}
/* TabsPage */
.tabsPage .tabsPageHeader, .tabsPage .tabsPageHeader li, .tabsPage .tabsPageHeader li a, .tabsPage .tabsPageHeader li span { background:url(./images/tabs/tabspage.png) no-repeat;}
.tabsPage .tabsPageHeader { background-color:#e9f0f2;}
.tabsPage .tabsPageHeader { border-color:#b8d0d6;}
.tabsPage .tabsPageHeader li a { color:#183152;}
.tabsPage .tabsPageHeader li .close,
.tabsPage .tabsPageHeader li.hover .close,
.tabsPage .tabsPageHeader li.selected .close { background:url(./images/tabs/tabspage_icon.png) no-repeat;}
.tabsPage .tabsLeft, .tabsPage .tabsRight, .tabsPage .tabsMore { background:url(./images/tabs/tabscontrol.png) no-repeat;}
.tabsPage .tabsMoreList { border-color:#b8d0d6; background:#FFF;}
.tabsPage .tabsPageHeader .home_icon { background:url(./images/icon.png) no-repeat;}
.tabsPage .tabsPageContent { border-color:#b8d0d6; background:#FFF;}
/* Alert */
.alert .alertFooter, .alert .alertFooter_r, .alert .alertFooter_c { background:url(./images/alert/alertpanel.png) no-repeat;}
.alert .alertContent { border-color:#b8d0d6; background:#eef4f5;}
.alert .warn .alertInner { border-color:#e83e09; background:#fefacf;}
.alert .error .alertInner { border-color:#e50000; background:#fefacf;}
.alert .correct .alertInner, .alert .info .alertInner { border-color:#b8d0d6; background:#fefacf;}
.alert .confirm .alertInner { border-color:#b8d0d6; background:#fefacf;}
.alert h1 { border-color:#CCC; background:url(./images/alert/alertpanel_icon.png) no-repeat;}
/* Dialog */
.dialog .dialogHeader, .dialog .dialogHeader_r, .dialog .dialogHeader_c,
.dialog .dialogFooter, .dialog .dialogFooter_r, .dialog .dialogFooter_c { background:url(./images/dialog/dialogpanel.png) no-repeat;}
.dialog .dialogHeader h1, .dialog .dialogHeader .close, .dialog .dialogHeader .maximize, .dialog .dialogHeader .restore, .dialog .dialogHeader .minimize, .resizable_f_r { background:url(./images/dialog/dialogpanel_icon.png) no-repeat;}
.dialog .dialogHeader h1 { color:#183152;}
.dialog .dialogContent { border-color:#b8d0d6; background:#eef4f5;}
.resizable { border-color:#081629; background:#c3d7dc;}
/* Shadow */
.shadow .shadow_h_l { background:url(./images/shadow/shadow_h_l.png) no-repeat;}
.shadow .shadow_h_r { background:url(./images/shadow/shadow_h_r.png) no-repeat;}
.shadow .shadow_h_c { background:url(./images/shadow/shadow_h_c.png) repeat-x;}
.shadow .shadow_c_l { background:url(./images/shadow/shadow_c_l.png) repeat-y;}
.shadow .shadow_c_r { background:url(./images/shadow/shadow_c_r.png) repeat-y;}
.shadow .shadow_c_c { background:url(./images/shadow/shadow_c_c.png) repeat;}
.shadow .shadow_f_l { background:url(./images/shadow/shadow_f_l.png) no-repeat;}
.shadow .shadow_f_r { background:url(./images/shadow/shadow_f_r.png) no-repeat;}
.shadow .shadow_f_c { background:url(./images/shadow/shadow_f_c.png) repeat-x;}
/* Tree */
.tree div div { background:url(./images/tree/tree.png) no-repeat;}
.tree .folder_collapsable, .tree .folder_expandable, .tree .file { background:url(./images/tree/folder.png) no-repeat;}
.tree .checked, .tree .unchecked, .tree .indeterminate { background:url(./images/tree/check.png) no-repeat;}
.tree ul { background:#FFF;}
.tree li a, .tree li span { color:#183152;}
.tree .hover { background:#f5f5f5;}
.tree .selected { background-color:#e8edf3;}
/* Accordion */
.accordion .accordionHeader, .accordion .accordionHeader h2, .accordion .accordionHeader h2 span { color:#183152; background:url(./images/accordion/accordion.png);}
.accordion { border-color:#b8d0d6; background:#FFF;}
.accordion .accordionHeader { background-color:#eaf4ff;}
.accordion .accordionContent { border-color:#b8d0d6;}
/* Grid */
.panelBar,
.toolBar li.hover, .toolBar li.hover a, .toolBar li.hover span, .toolBar span,
.pagination, .pagination li.hover, .pagination li.hover a, .pagination li span,
.pagination li.disabled span span,
.panelBar .line, .pagination li.jumpto, .pagination li.jumpto .goto { background:url(./images/grid/grid.png) no-repeat;}
.panelBar { border-color:#b8d0d6; background-color:#efefef;}
.grid .gridHeader { background:#EEE;}
.grid { background:#FFF;}
.grid table { border-color:#d0d0d0;}
.grid .gridHeader, .grid .gridHeader th { border-color:#d0d0d0; background:#f0eff0 url(./images/grid/tableth.png) repeat-x;}
.grid table th div { border-left-color:#EEE; border-right-color:#d0d0d0;}
.grid table td { border-color:#ededed;}
.grid .resizeMarker, .grid .resizeProxy { background:url(./images/grid/resizeCol.png) repeat-y;}
.grid .gridHeader th.hover, .grid .gridHeader th.thSelected { border-color:#aaccf6; }
.grid .gridTbody .gridRowBg { background:#f7f7f7;}
.grid .gridTbody .gridRow { border-color:#ededed;}
.grid .gridTbody .gridRow td.tdLast { border-color:#ededed;}
.grid .gridTbody .hover { border-color:#dddddd; background:#f5f5f5;}
.grid .gridTbody .hover .tdSelected { background:#f5f5f5;}
.grid .gridTbody .selected { border-color:#b8d0d6; background:#7cc5e5;}
.grid .gridTbody .selected .tdSelected { background:#e8edf3;}
.grid .gridTbody .tdSelected { background:#f8f8f8;}
.grid .error{background:#fb7e81;}
/* ProgressBar */
.progressBar { border:solid 2px #86a5ad; background:#FFF url(./images/progressBar/progressBar_m.gif) no-repeat 10px 10px;}
/* ----------------------------------------------------------------- Form */
/* TextInput */
.textInput, input.focus, input.required, input.error, input.readonly, input.disabled,
textarea.focus, textarea.required, textarea.error, textarea.readonly, textarea.disabled { background:url(./images/form/input_bg.png) no-repeat scroll;}
.textInput, .textArea { border-color:#a2bac0 #b8d0d6 #b8d0d6 #a2bac0; background-color:#FFF;}
input.required, textarea.required { border-color:#a2bac0 #b8d0d6 #b8d0d6 #a2bac0; background-color:#FFF;}
input.error, textarea.error { border-color:#F80C11 #FB7E81 #FB7E81 #F80C11;}
input.focus, textarea.focus { border-color:#64aabc #a9d7e3 #a9d7e3 #64aabc; background-color:#f8fafc;}
input.readonly, textarea.readonly { border-color:#9eabb3 #d5dbdf #d5dbdf #9eabb3; background-color:#F6F6F6;}
input.disabled, textarea.disabled { border-color:#9eabb3 #d5dbdf #d5dbdf #9eabb3; background-color:#F6F6F6;}
.inputButton, .inputDateButton { background:url(./images/form/input_bt.png) no-repeat;}
/* Button */
.button, .button span,
.buttonDisabled, .buttonDisabled span,
.buttonActive, .buttonActive span,
.button .buttonContent, .buttonHover, .buttonHover .buttonContent,
.buttonActive .buttonContent, .buttonActiveHover, .buttonActiveHover .buttonContent,
.buttonDisabled .buttonContent { background:url(./images/button/button_s.png) no-repeat;}
.button span, .buttonDisabled span, .buttonActive span,
.button .buttonContent, .buttonHover, .buttonHover .buttonContent,
.buttonActive .buttonContent, .buttonDisabled .buttonContent,
.button button, .buttonHover button,
.buttonActive button, .buttonDisabled button { color:#183152;}
.buttonDisabled span, .buttonDisabled:hover span,
.buttonDisabled button { color:#999;}
/* ----------------------------------------------------------------- Pages */
/* Layout */
body, #splitBar { background:#e5edef;}
#splitBarProxy { border-color:#c0c0c0; background:#CCC;}
#header, #header .headerNav { background:url(./images/header_bg.png) repeat-x;}
#header { background-color:#102c4a;}
#header .logo { background:url(./images/logo.png) no-repeat;}
#header .nav li { float:left; margin-left:-1px; padding:0 8px; line-height:11px; background:url(./images/listLine.png) no-repeat;}
#header .nav li a { color:green;}
#header .themeList li div { background:url(./images/themeButton.png) no-repeat;}
.toggleCollapse, .toggleCollapse div { background:url(./images/layout/toggleSidebar.png) no-repeat;}
.toggleCollapse { border-style:solid; border-width:1px 1px 0 1px; border-color:#b8d0d6; background-color:#e7eff0;}
.toggleCollapse h2 { color:#183152;}
#sidebar_s .collapse { border:solid 1px #b8d0d6; background:#eff5f6;}
#sidebar_s .collapse:hover { background:#f5f9fa;}
#taskbar, #taskbar li, #taskbar li .taskbutton { background:url(./images/layout/taskbar.png) no-repeat;}
#taskbar .close, #taskbar .restore, #taskbar .minimize { background:url(./images/layout/taskbar_icon.png) no-repeat;}
#taskbar li .taskbutton span { color:#FFF;}
#taskbar .taskbarLeft, #taskbar .taskbarRight { background:url(./images/layout/taskbar_control.png) no-repeat;}
/* Menu */
#navMenu, #navMenu li, #navMenu li.selected a, #navMenu li.selected span { background:url(../default/images/menu/menu.png) no-repeat;}
#navMenu { background-color:#1871dd; }
#navMenu li a, #navMenu li span { color:#FFF; }
#navMenu li.selected span { color:#000; }
/* Homepage */
.sidebarContent { display:block; overflow:auto; height:500px; border:solid 1px #86B4EC; background:#FFF;}
.accountInfo { display:block; overflow:hidden; height:60px; padding:0 10px; background:url(./images/account_info_bg.png) repeat-x}
.accountInfo p { padding:8px 0 0 0; line-height:19px;}
.accountInfo p span { font-size:14px; font-weight:bold;}
.accountInfo .right { float:right; padding-right:10px; text-align:right;}
.accountInfo .alertInfo { float:right; width:300px; height:60px; padding-left:10px; border-left:solid 1px #accdf4;}
.accountInfo .alertInfo h2 { padding:8px 0; line-height:17px;}
.accountInfo .alertInfo a { padding:6px 0 0 0; line-height:21px;}
/* Pages */
.pageForm .inputInfo { color:#999;}
/* Pages dialog */
.dialog .pageHeader, .dialog .pageContent { border-color:#b8d0d6;}
.dialog .pageContent .pageFormContent { border-color:#b8d0d6; background:#FFF;}
/* Pages default */
.page .pageHeader, .formBar { border-color:#b8d0d6; background:#ebf0f5 url(../default/images/pageHeader_bg.png) repeat-x;}
.page .searchBar label { color:#183152;}
/* Pages Form */
.formBar { border-color:#b8d0d6;}
.divider { border-color:#b8d0d6;}
/* combox */
.combox .select a { color:#183152; }
.comboxop { border-color:#B8D0D6; }
.combox, .combox div, .combox div a { background:url(../default/images/search-bg.gif) no-repeat; }
| {
"content_hash": "ec7ab0d82412155aa03eb7631fa60355",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 235,
"avg_line_length": 54.614634146341466,
"alnum_prop": 0.7178456591639871,
"repo_name": "maojian/EaglePHP",
"id": "ea2d6eda8ee94a77fe263551a21c71c3952933a5",
"size": "11196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Public/share/plug/dwz/themes/default/style.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "324912"
},
{
"name": "JavaScript",
"bytes": "942119"
},
{
"name": "PHP",
"bytes": "2442081"
},
{
"name": "Shell",
"bytes": "1611"
}
],
"symlink_target": ""
} |
/* Generated By:JJTree: Do not edit this line. ASTDeleteData.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package org.openrdf.query.parser.sparql.ast;
public
class ASTDeleteData extends ASTUpdate {
public ASTDeleteData(int id) {
super(id);
}
public ASTDeleteData(SyntaxTreeBuilder p, int id) {
super(p, id);
}
/** Accept the visitor. **/
public Object jjtAccept(SyntaxTreeBuilderVisitor visitor, Object data) throws VisitorException {
return visitor.visit(this, data);
}
}
/* JavaCC - OriginalChecksum=560c0d10503859a175eede497041368d (do not edit this line) */
| {
"content_hash": "a0158d3b80f2721f2261e9fcd4be0b21",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 166,
"avg_line_length": 34.95238095238095,
"alnum_prop": 0.7493188010899182,
"repo_name": "ConstantB/ontop-spatial",
"id": "de20ed8d07b76df2549a4e7b19ae9f0a9bc4e3ae",
"size": "734",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "obdalib-sesame/src/main/java/org/openrdf/query/parser/sparql/ast/ASTDeleteData.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "725"
},
{
"name": "CSS",
"bytes": "2676"
},
{
"name": "GAP",
"bytes": "43623"
},
{
"name": "HTML",
"bytes": "2860560"
},
{
"name": "Java",
"bytes": "6929671"
},
{
"name": "PLpgSQL",
"bytes": "75540766"
},
{
"name": "Ruby",
"bytes": "52622"
},
{
"name": "Shell",
"bytes": "18315"
},
{
"name": "TeX",
"bytes": "10376"
},
{
"name": "Web Ontology Language",
"bytes": "52563785"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VentaElectrodomesticos.Core.Model.Containers
{
public class TableroControlInfo
{
public int TotalVentas { get; set; }
public double? TotalFacturacion { get; set; }
public int? FacturasEfectivo { get; set; }
public double? MayorFactura { get; set; }
public string MayorDeudor { get; set; }
public string VendedorAnio { get; set; }
public string ProductoAnio { get; set; }
public string FaltanteStock { get; set; }
}
}
| {
"content_hash": "061bd88310c05097caec53d8d77dfa40",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 54,
"avg_line_length": 31.105263157894736,
"alnum_prop": 0.6598984771573604,
"repo_name": "navarroaxel/VentaElectrodomesticos",
"id": "aff990bdc78441e294f9f106c75e3afad9261d30",
"size": "593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "VentaElectrodomesticosCore/Model/Containers/TableroControlInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "229601"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Boost.Geometry (aka GGL, Generic Geometry Library)</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head>
<table cellpadding="2" width="100%">
<tbody>
<tr>
<td valign="top">
<img alt="Boost.Geometry" src="images/ggl-logo-big.png" height="80" width="200">
</td>
<td valign="top" align="right">
<a href="http://www.boost.org">
<img alt="Boost C++ Libraries" src="images/accepted_by_boost.png" height="80" width="230" border="0">
</a>
</td>
</tr>
</tbody>
</table>
<!-- Generated by Doxygen 1.7.6.1 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
</div>
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> |
<a href="#namespaces">Namespaces</a> </div>
<div class="headertitle">
<div class="title">/home/travis/build/boostorg/boost/boost/geometry/strategies/spherical/distance_cross_track_point_box.hpp File Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classboost_1_1geometry_1_1strategy_1_1distance_1_1cross__track__point__box.html">boost::geometry::strategy::distance::cross_track_point_box< CalculationType, Strategy ></a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Strategy functor for distance point to box calculation. <a href="classboost_1_1geometry_1_1strategy_1_1distance_1_1cross__track__point__box.html#details">More...</a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structboost_1_1geometry_1_1strategy_1_1distance_1_1cross__track__point__box_1_1return__type.html">boost::geometry::strategy::distance::cross_track_point_box< CalculationType, Strategy >::return_type< Point, Box ></a></td></tr>
<tr><td colspan="2"><h2><a name="namespaces"></a>
Namespaces</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">namespace  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceboost.html">boost</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">namespace  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceboost_1_1geometry.html">boost::geometry</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">namespace  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceboost_1_1geometry_1_1strategy.html">boost::geometry::strategy</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">namespace  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceboost_1_1geometry_1_1strategy_1_1distance.html">boost::geometry::strategy::distance</a></td></tr>
</table>
</div><!-- contents -->
<hr size="1">
<table width="100%">
<tbody>
<tr>
<td align="left"><small>
<p>April 2, 2011</p>
</small></td>
<td align="right">
<small>
Copyright © 2007-2011 Barend Gehrels, Amsterdam, the Netherlands<br>
Copyright © 2008-2011 Bruno Lalande, Paris, France<br>
Copyright © 2009-2010 Mateusz Loskot, London, UK<br>
</small>
</td>
</tr>
</tbody>
</table>
<address style="text-align: right;"><small>
Documentation is generated by <a href="http://www.doxygen.org/index.html">Doxygen</a>
</small></address>
</body>
</html>
| {
"content_hash": "f2b3e197cf8b3fa771e64d11b81aff18",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 372,
"avg_line_length": 50.23863636363637,
"alnum_prop": 0.6731508708437005,
"repo_name": "nicecapj/crossplatfromMmorpgServer",
"id": "699f60dcfc74775d09aac91b3d531cb0d1f0e74a",
"size": "4421",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "ThirdParty/boost_1_61_0/libs/geometry/doc/doxy/doxygen_output/html_by_doxygen/distance__cross__track__point__box_8hpp.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "223360"
},
{
"name": "Batchfile",
"bytes": "33694"
},
{
"name": "C",
"bytes": "3967798"
},
{
"name": "C#",
"bytes": "2093216"
},
{
"name": "C++",
"bytes": "197077824"
},
{
"name": "CMake",
"bytes": "203207"
},
{
"name": "CSS",
"bytes": "427824"
},
{
"name": "CWeb",
"bytes": "174166"
},
{
"name": "Cuda",
"bytes": "52444"
},
{
"name": "DIGITAL Command Language",
"bytes": "6246"
},
{
"name": "Emacs Lisp",
"bytes": "7822"
},
{
"name": "Fortran",
"bytes": "1856"
},
{
"name": "Go",
"bytes": "8549"
},
{
"name": "HTML",
"bytes": "234971359"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "Java",
"bytes": "3809828"
},
{
"name": "JavaScript",
"bytes": "1112586"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "M4",
"bytes": "135271"
},
{
"name": "Makefile",
"bytes": "1266088"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "2928243"
},
{
"name": "Objective-C++",
"bytes": "3527"
},
{
"name": "PHP",
"bytes": "59372"
},
{
"name": "Perl",
"bytes": "38649"
},
{
"name": "Perl6",
"bytes": "2053"
},
{
"name": "Protocol Buffer",
"bytes": "1576976"
},
{
"name": "Python",
"bytes": "3257634"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Roff",
"bytes": "5189"
},
{
"name": "Ruby",
"bytes": "97584"
},
{
"name": "Shell",
"bytes": "787152"
},
{
"name": "Swift",
"bytes": "20519"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "32117"
},
{
"name": "Vim script",
"bytes": "3759"
},
{
"name": "XSLT",
"bytes": "552736"
},
{
"name": "Yacc",
"bytes": "19623"
}
],
"symlink_target": ""
} |
package eu.crushedpixel.littlstar.api.data;
/**
* An interface for objects to be wrapped in a SendWrapper object
*/
public interface ApiSend {
/**
* @return The Object's key in the JSON Payload sent to the Littlstar API
*/
String getKey();
}
| {
"content_hash": "9bab5681e6402d951566e95f96c6c17e",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 77,
"avg_line_length": 17.8,
"alnum_prop": 0.6704119850187266,
"repo_name": "CrushedPixel/littlstar-java-sdk",
"id": "89d23cabc5b23614d154eb2b4e826cb330593cc4",
"size": "889",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/eu/crushedpixel/littlstar/api/data/ApiSend.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "61999"
}
],
"symlink_target": ""
} |
<div class="container">
<?php echo form_open('/Admin_panel/save_question_changes', 'class="form-horizontal", id="ciena-form"'); ?>
<?php echo form_hidden('question_id', $question['question_id']); ?>
<fieldset>
<!-- Form Name -->
<h2 class="text-center">Edit Question</h2>
<hr>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-2 control-label" for="question_text">Question Text</label>
<div class="col-md-10">
<?php echo form_textarea('question_text', $question['question_text'], array('placeholder' => 'Question text', 'class' => 'form-control')); ?>
</div>
</div>
<!-- Multiple Radios (inline) -->
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-2 control-label" for="right_choice">Proper Answer?</label>
<div class="col-md-4">
<?php
$options = array(
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
);
echo form_dropdown('right_choice', $options, $question['right_choice'], 'class="form-control"');
?>
</div>
</div>
<!-- Textarea -->
<div class="row">
<div class="form-group">
<label class="col-md-2 control-label" for="ans_1">Answer 1</label>
<div class="col-md-4">
<?php echo form_textarea('answer_a', $question['answer_a'], array('placeholder' => 'Answer 1 text', 'class' => 'form-control')); ?>
</div>
<!-- Textarea -->
<label class="col-md-2 control-label" for="ans_2">Answer 2</label>
<div class="col-md-4">
<?php echo form_textarea('answer_b', $question['answer_b'], array('placeholder' => 'Answer 2 text', 'class' => 'form-control')); ?>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="col-md-2 control-label" for="ans_3">Answer 3</label>
<div class="col-md-4">
<?php echo form_textarea('answer_c', $question['answer_c'], array('placeholder' => 'Answer 3 text', 'class' => 'form-control')); ?>
</div>
<!-- Textarea -->
<label class="col-md-2 control-label" for="ans_4">Answer 4</label>
<div class="col-md-4">
<?php echo form_textarea('answer_d', $question['answer_d'], array('placeholder' => 'Answer 4 text', 'class' => 'form-control')); ?>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="col-md-2 control-label" for="ans_4">Extra Info</label>
<div class="col-md-10">
<?php echo form_textarea('extra_info', $question['extra_info'], array('placeholder' => 'Extra info after user answers', 'class' => 'form-control skinny')); ?>
</div>
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<div class="col-md-4 pull-right">
<?php echo anchor('/Admin_panel/delete_question/'.$question['question_id'], 'Delete Question', array('title' => 'Delete Question', 'class' => 'btn btn-ciena-no btn-lg')); ?>
<?php echo form_submit('', 'Save Changes', array('class' => 'btn btn-ciena-yes btn-lg')); ?>
</div>
</div>
</fieldset>
</form>
</div> | {
"content_hash": "d20a5c89db170a2cef7da0f36013ad27",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 177,
"avg_line_length": 34.63333333333333,
"alnum_prop": 0.5595123516201476,
"repo_name": "Jonyorker/ciena-quiz",
"id": "4468992134cd43490e9a97dc545cfef65c3cdd67",
"size": "3117",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/admin/edit_question_view.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "15978"
},
{
"name": "HTML",
"bytes": "8515431"
},
{
"name": "JavaScript",
"bytes": "56666"
},
{
"name": "PHP",
"bytes": "1808428"
}
],
"symlink_target": ""
} |
import numpy as np
from federatedml.linear_model.linear_model_base import BaseLinearModel
from federatedml.linear_model.linear_model_weight import LinearModelWeights as PoissonRegressionWeights
from federatedml.param.evaluation_param import EvaluateParam
from federatedml.param.poisson_regression_param import PoissonParam
from federatedml.protobuf.generated import poisson_model_meta_pb2, poisson_model_param_pb2
from federatedml.secureprotol import PaillierEncrypt
from federatedml.util.fate_operator import vec_dot
class BasePoissonRegression(BaseLinearModel):
def __init__(self):
super(BasePoissonRegression, self).__init__()
self.model_param = PoissonParam()
# attribute:
self.model_name = 'PoissonRegression'
self.model_param_name = 'PoissonRegressionParam'
self.model_meta_name = 'PoissonRegressionMeta'
self.cipher_operator = PaillierEncrypt()
self.exposure_index = -1
def _init_model(self, params):
super()._init_model(params)
self.exposure_colname = params.exposure_colname
@staticmethod
def get_exposure_index(header, exposure_colname):
try:
exposure_index = header.index(exposure_colname)
except BaseException:
exposure_index = -1
return exposure_index
@staticmethod
def load_instance(data_instance, exposure_index):
"""
return data_instance without exposure
Parameters
----------
data_instance: Table of Instances, input data
exposure_index: column index of exposure variable
"""
if exposure_index == -1:
return data_instance
if exposure_index >= len(data_instance.features):
raise ValueError(
"exposure_index {} out of features' range".format(exposure_index))
data_instance.features = np.delete(data_instance.features, exposure_index)
return data_instance
@staticmethod
def load_exposure(data_instance, exposure_index):
"""
return exposure of a given data_instance
Parameters
----------
data_instance: Table of Instances, input data
exposure_index: column index of exposure variable
"""
if exposure_index == -1:
exposure = 1
else:
exposure = data_instance.features[exposure_index]
return exposure
@staticmethod
def safe_log(v):
if v == 0:
return np.log(1e-7)
return np.log(v)
@staticmethod
def compute_mu(data_instances, coef_, intercept_=0, exposure=None):
if exposure is None:
mu = data_instances.mapValues(
lambda v: np.exp(vec_dot(v.features, coef_) + intercept_))
else:
offset = exposure.mapValues(lambda v: BasePoissonRegression.safe_log(v))
mu = data_instances.join(offset,
lambda v, m: np.exp(vec_dot(v.features, coef_) + intercept_ + m))
return mu
@staticmethod
def compute_wx(data_instances, coef_, intercept_=0):
return data_instances.mapValues(lambda v: vec_dot(v.features, coef_) + intercept_)
def _get_meta(self):
meta_protobuf_obj = poisson_model_meta_pb2.PoissonModelMeta(
penalty=self.model_param.penalty,
tol=self.model_param.tol,
alpha=self.alpha,
optimizer=self.model_param.optimizer,
batch_size=self.batch_size,
learning_rate=self.model_param.learning_rate,
max_iter=self.max_iter,
early_stop=self.model_param.early_stop,
fit_intercept=self.fit_intercept,
exposure_colname=self.exposure_colname)
return meta_protobuf_obj
def _get_param(self):
header = self.header
# LOGGER.debug("In get_param, header: {}".format(header))
weight_dict, intercept_ = {}, None
if header is not None:
for idx, header_name in enumerate(header):
coef_i = self.model_weights.coef_[idx]
weight_dict[header_name] = coef_i
intercept_ = self.model_weights.intercept_
best_iteration = -1 if self.validation_strategy is None else self.validation_strategy.best_iteration
param_protobuf_obj = poisson_model_param_pb2.PoissonModelParam(iters=self.n_iter_,
loss_history=self.loss_history,
is_converged=self.is_converged,
weight=weight_dict,
intercept=intercept_,
header=header,
best_iteration=best_iteration)
return param_protobuf_obj
def load_model(self, model_dict):
result_obj = list(model_dict.get('model').values())[0].get(
self.model_param_name)
meta_obj = list(model_dict.get('model').values())[0].get(self.model_meta_name)
fit_intercept = meta_obj.fit_intercept
self.exposure_colname = meta_obj.exposure_colname
self.header = list(result_obj.header)
# For poisson regression arbiter predict function
if self.header is None:
return
feature_shape = len(self.header)
tmp_vars = np.zeros(feature_shape)
weight_dict = dict(result_obj.weight)
self.intercept_ = result_obj.intercept
for idx, header_name in enumerate(self.header):
tmp_vars[idx] = weight_dict.get(header_name)
if fit_intercept:
tmp_vars = np.append(tmp_vars, result_obj.intercept)
self.model_weights = PoissonRegressionWeights(l=tmp_vars,
fit_intercept=fit_intercept,
raise_overflow_error=False)
self.n_iter_ = result_obj.iters
def get_metrics_param(self):
return EvaluateParam(eval_type="regression", metrics=self.metrics)
| {
"content_hash": "9b81c454a1830a1d171d5e5f47ae5126",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 108,
"avg_line_length": 41.666666666666664,
"alnum_prop": 0.58704,
"repo_name": "FederatedAI/FATE",
"id": "eb3418dfae729685a3035864a478a908a5d9aa83",
"size": "6914",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/federatedml/linear_model/coordinated_linear_model/poisson_regression/base_poisson_regression.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Lua",
"bytes": "19716"
},
{
"name": "Python",
"bytes": "5121767"
},
{
"name": "Rust",
"bytes": "3971"
},
{
"name": "Shell",
"bytes": "19676"
}
],
"symlink_target": ""
} |
R-MethIll
=========
Statistical Analysis Protocol of DNA Methylation Data from Illumina
* Cancel batch effects
* Cluster samples by correlation
* Visualize clusters by multi dimensionsal scaling
* ...
=========
For data, see the gene expression omnibus (GEO):
* [Illumina HumanMethylation450 BeadChip](http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GPL13534)
* [Illumina HumanMethylation27 BeadChip](http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GPL8490)
=========
Integrate other software
* [ComBat](http://www.bu.edu/jlab/wp-assets/ComBat/Abstract.html) by Johnson et al.
* [Principles from SampleNetwork](http://labs.genetics.ucla.edu/horvath/CoexpressionNetwork/Rpackages/WGCNA/) by Horvath et al.
| {
"content_hash": "027f022b126946464293751006403be5",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 128,
"avg_line_length": 39.666666666666664,
"alnum_prop": 0.7507002801120448,
"repo_name": "fabricecolas/R-MethIll",
"id": "8adf6e066aa8ef71b5aeb795ad9c8f0496126ce4",
"size": "714",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "R",
"bytes": "34712"
}
],
"symlink_target": ""
} |
#pragma warning disable GU0009 // Name the boolean parameter.
namespace Gu.Wpf.ToolTips.UiTests
{
using Gu.Wpf.UiAutomation;
using NUnit.Framework;
[TestFixture("DefaultAdornerLayerWindow")]
[TestFixture("ExplicitAdornerDecoratorWindow")]
public class WindowTests
{
private const string ExeFileName = "Gu.Wpf.ToolTips.Demo.exe";
private readonly string windowName;
public WindowTests(string windowName)
{
this.windowName = windowName;
}
[OneTimeSetUp]
public void OneTimeSetUp()
{
// Touch must be initialized before the app to test touch on is started.
// Not sure why but my guess is the call to InitializeTouchInjection adds a touch device making WPF start listening for touch input.
Touch.Initialize();
}
[SetUp]
public void SetUp()
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
Mouse.Position = window.FindButton("Lose focus").Bounds.Center();
window.FindCheckBox("IsElementEnabled").IsChecked = false;
window.FindCheckBox("IsElementVisible").IsChecked = true;
window.FindCheckBox("ToolTipServiceIsEnabled").IsChecked = true;
window.FindCheckBox("TouchToolTipServiceIsEnabled").IsChecked = true;
window.WaitUntilResponsive();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
Application.KillLaunched(ExeFileName, this.windowName);
}
[TestCase("Button 1", "Button_1_disabled_with_overlay.png", "Button_1_disabled.png")]
[TestCase("Button 2", "Button_2_disabled_with_overlay.png", "Button_2_disabled.png")]
[TestCase("TextBlock 1", "TextBlock_1_disabled_with_overlay.png", "TextBlock_1_disabled.png")]
[TestCase("Label 1", "Label_1_disabled_with_overlay.png", "Label_1_disabled.png")]
public void TouchToolTipServiceIsEnabled(string name, string withOverlay, string noOverlay)
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var element = window.FindFirstChild(Conditions.ByName(name), x => new UiElement(x));
ImageAssert.AreEqual($"Images\\{TestImage.Current}\\{withOverlay}", element, TestImage.OnFail);
window.FindCheckBox("TouchToolTipServiceIsEnabled").IsChecked = false;
ImageAssert.AreEqual($"Images\\{TestImage.Current}\\{noOverlay}", element, TestImage.OnFail);
window.FindCheckBox("TouchToolTipServiceIsEnabled").IsChecked = true;
ImageAssert.AreEqual($"Images\\{TestImage.Current}\\{withOverlay}", element, TestImage.OnFail);
}
[TestCase("Button 1", "Button_1_disabled_with_overlay.png", "Button_1_disabled.png")]
[TestCase("Button 2", "Button_2_disabled_with_overlay.png", "Button_2_disabled.png")]
[TestCase("TextBlock 1", "TextBlock_1_disabled_with_overlay.png", "TextBlock_1_disabled.png")]
[TestCase("Label 1", "Label_1_disabled_with_overlay.png", "Label_1_disabled.png")]
public void ToolTipServiceIsEnabled(string name, string withOverlay, string noOverlay)
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var element = window.FindFirstChild(Conditions.ByName(name), x => new UiElement(x));
ImageAssert.AreEqual($"Images\\{TestImage.Current}\\{withOverlay}", element, TestImage.OnFail);
window.FindCheckBox("ToolTipServiceIsEnabled").IsChecked = false;
ImageAssert.AreEqual($"Images\\{TestImage.Current}\\{noOverlay}", element, TestImage.OnFail);
window.FindCheckBox("ToolTipServiceIsEnabled").IsChecked = true;
ImageAssert.AreEqual($"Images\\{TestImage.Current}\\{withOverlay}", element, TestImage.OnFail);
}
[TestCase("Button 1", "Button_1_disabled_with_overlay.png")]
[TestCase("Button 2", "Button_2_disabled_with_overlay.png")]
[TestCase("TextBlock 1", "TextBlock_1_disabled_with_overlay.png")]
[TestCase("Label 1", "Label_1_disabled_with_overlay.png")]
public void IsElementVisible(string name, string withOverlay)
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var element = window.FindFirstChild(Conditions.ByName(name), x => new UiElement(x));
ImageAssert.AreEqual($"Images\\{TestImage.Current}\\{withOverlay}", element, TestImage.OnFail);
window.FindCheckBox("IsElementVisible").IsChecked = false;
window.FindCheckBox("IsElementVisible").IsChecked = true;
ImageAssert.AreEqual($"Images\\{TestImage.Current}\\{withOverlay}", element, TestImage.OnFail);
}
[TestCase("Button 1")]
[TestCase("Button 2")]
[TestCase("TextBlock 1")]
[TestCase("Label 1")]
public void MouseOver(string name)
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var element = window.FindFirstChild(Conditions.ByName(name), x => new UiElement(x));
Mouse.Position = element.Bounds.Center();
AssertToolTip.IsOpen(true, element);
window.FindButton("Lose focus").Click(moveMouse: true);
AssertToolTip.IsOpen(false, element);
}
[TestCase("Button 1")]
[TestCase("Button 2")]
[TestCase("TextBlock 1")]
[TestCase("Label 1")]
public void TapThenClick(string name)
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var element = window.FindFirstChild(Conditions.ByName(name), x => new UiElement(x));
Touch.Tap(element.Bounds.Center());
AssertToolTip.IsOpen(true, element);
Mouse.Click(MouseButton.Left, element.Bounds.Center());
AssertToolTip.IsOpen(false, element);
}
[TestCase("Button 1")]
[TestCase("Button 2")]
[TestCase("TextBlock 1")]
[TestCase("Label 1")]
public void TapThenMouseOver(string name)
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var element = window.FindFirstChild(Conditions.ByName(name), x => new UiElement(x));
Touch.Tap(element.Bounds.Center());
AssertToolTip.IsOpen(true, element);
Mouse.MoveTo(element.Bounds.Center());
AssertToolTip.IsOpen(true, element);
window.FindButton("Lose focus").Click(moveMouse: true);
AssertToolTip.IsOpen(false, element);
}
[TestCase("Button 1")]
[TestCase("Button 2")]
[TestCase("TextBlock 1")]
[TestCase("Label 1")]
public void TapTwice(string name)
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var element = window.FindFirstChild(Conditions.ByName(name), x => new UiElement(x));
Touch.Tap(element.Bounds.Center());
AssertToolTip.IsOpen(true, element);
Touch.Tap(element.Bounds.Center());
AssertToolTip.IsOpen(false, element);
}
[TestCase("Button 1")]
[TestCase("Button 2")]
[TestCase("TextBlock 1")]
[TestCase("Label 1")]
public void TapTwiceLoop(string name)
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var element = window.FindFirstChild(Conditions.ByName(name), x => new UiElement(x));
for (var i = 0; i < 4; i++)
{
Touch.Tap(element.Bounds.Center());
AssertToolTip.IsOpen(true, element);
Touch.Tap(element.Bounds.Center());
AssertToolTip.IsOpen(false, element);
}
}
[TestCase("Button 1")]
[TestCase("Button 2")]
[TestCase("TextBlock 1")]
[TestCase("Label 1")]
public void TapThenTapLoseFocus(string name)
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var element = window.FindFirstChild(Conditions.ByName(name), x => new UiElement(x));
Touch.Tap(element.Bounds.Center());
AssertToolTip.IsOpen(true, element);
Touch.Tap(window.FindButton("Lose focus").Bounds.Center());
AssertToolTip.IsOpen(false, element);
}
[TestCase("Button 1")]
[TestCase("Button 2")]
[TestCase("TextBlock 1")]
[TestCase("Label 1")]
public void TapThenTapLoseFocusLoop(string name)
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var element = window.FindFirstChild(Conditions.ByName(name), x => new UiElement(x));
for (var i = 0; i < 4; i++)
{
Touch.Tap(element.Bounds.Center());
AssertToolTip.IsOpen(true, element);
Touch.Tap(window.FindButton("Lose focus").Bounds.Center());
AssertToolTip.IsOpen(false, element);
}
}
[Test]
public void TapElementsInSequence()
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var button1 = window.FindButton("Button 1");
var button2 = window.FindButton("Button 2");
var textBlock = window.FindTextBlock("TextBlock 1");
var label = window.FindLabel("Label 1");
Touch.Tap(button1.Bounds.Center());
AssertToolTip.IsOpen(true, button1);
AssertToolTip.IsOpen(false, button2);
AssertToolTip.IsOpen(false, textBlock);
AssertToolTip.IsOpen(false, label);
Touch.Tap(button2.Bounds.Center());
AssertToolTip.IsOpen(false, button1);
AssertToolTip.IsOpen(true, button2);
AssertToolTip.IsOpen(false, textBlock);
AssertToolTip.IsOpen(false, label);
Touch.Tap(textBlock.Bounds.Center());
AssertToolTip.IsOpen(false, button1);
AssertToolTip.IsOpen(false, button2);
AssertToolTip.IsOpen(true, textBlock);
AssertToolTip.IsOpen(false, label);
Touch.Tap(label.Bounds.Center());
AssertToolTip.IsOpen(false, button1);
AssertToolTip.IsOpen(false, button2);
AssertToolTip.IsOpen(false, textBlock);
AssertToolTip.IsOpen(true, label);
}
[Test]
public void TapElementsInSequenceManyTimes()
{
using var app = Application.AttachOrLaunch(ExeFileName, this.windowName);
var window = app.MainWindow;
var button1 = window.FindButton("Button 1");
var button2 = window.FindButton("Button 2");
var textBlock = window.FindTextBlock("TextBlock 1");
var label = window.FindLabel("Label 1");
for (var i = 0; i < 4; i++)
{
Touch.Tap(button1.Bounds.Center());
AssertToolTip.IsOpen(true, button1);
AssertToolTip.IsOpen(false, button2);
AssertToolTip.IsOpen(false, textBlock);
AssertToolTip.IsOpen(false, label);
Touch.Tap(button2.Bounds.Center());
AssertToolTip.IsOpen(false, button1);
AssertToolTip.IsOpen(true, button2);
AssertToolTip.IsOpen(false, textBlock);
AssertToolTip.IsOpen(false, label);
Touch.Tap(textBlock.Bounds.Center());
AssertToolTip.IsOpen(false, button1);
AssertToolTip.IsOpen(false, button2);
AssertToolTip.IsOpen(true, textBlock);
AssertToolTip.IsOpen(false, label);
Touch.Tap(label.Bounds.Center());
AssertToolTip.IsOpen(false, button1);
AssertToolTip.IsOpen(false, button2);
AssertToolTip.IsOpen(false, textBlock);
AssertToolTip.IsOpen(true, label);
}
}
}
}
| {
"content_hash": "026f57866a02cd8aaea3ec03301ea980",
"timestamp": "",
"source": "github",
"line_count": 292,
"max_line_length": 144,
"avg_line_length": 43.52054794520548,
"alnum_prop": 0.6056027699087189,
"repo_name": "JohanLarsson/Gu.Wpf.ToolTips",
"id": "a631c235e3556f864a0ef27c9c53b5174c5e4a97",
"size": "12710",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Gu.Wpf.ToolTips.UiTests/WindowTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "40730"
}
],
"symlink_target": ""
} |
<?php
namespace backend\modules\masterdata\models;
use Yii;
/**
* This is the model class for table "quotation".
*
* @property integer $quotationid
* @property string $quotationtitle
* @property integer $picto
* @property integer $picfrom
* @property integer $companyid
* @property string $quotationdate
* @property string $senderreerence
* @property integer $createby
* @property string $createdate
* @property integer $updateby
* @property string $updatedate
* @property integer $active
* @property string $status
*/
class Quotation extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'quotation';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['picto', 'picfrom', 'companyid', 'createby', 'updateby', 'active'], 'integer'],
[['companyid', 'quotationdate', 'senderreerence', 'createby', 'createdate', 'updateby', 'updatedate', 'status'], 'required'],
[['quotationdate', 'createdate', 'updatedate'], 'safe'],
[['quotationtitle'], 'string', 'max' => 255],
[['senderreerence', 'status'], 'string', 'max' => 20]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'quotationid' => 'Quotationid',
'quotationtitle' => 'Quotationtitle',
'picto' => 'Picto',
'picfrom' => 'Picfrom',
'companyid' => 'Companyid',
'quotationdate' => 'Quotationdate',
'senderreerence' => 'Senderreerence',
'createby' => 'Createby',
'createdate' => 'Createdate',
'updateby' => 'Updateby',
'updatedate' => 'Updatedate',
'active' => 'Active',
'status' => 'Status',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCompany()
{
return $this->hasOne(Company::className(), ['companyid' => 'companyid']);
}
public function getTopic()
{
return $this->hasOne(User::className(), ['id' => 'picto']);
}
public function getfrompic()
{
return $this->hasOne(User::className(), ['id' => 'picfrom']);
}
}
| {
"content_hash": "e6add1f87151abc550ccb4ec4a43f4af",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 137,
"avg_line_length": 26.137931034482758,
"alnum_prop": 0.5514511873350924,
"repo_name": "ariandi/ktmavia",
"id": "6f2d82ede581f3daa43c796019ee7fde4c1aa294",
"size": "2274",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/modules/masterdata/models/Quotation.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "838998"
},
{
"name": "HTML",
"bytes": "3011603"
},
{
"name": "JavaScript",
"bytes": "2866501"
},
{
"name": "PHP",
"bytes": "1968627"
},
{
"name": "Python",
"bytes": "32324"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe "multi_stage", dbscope: :example, js: true do
let(:site) { cms_site }
let(:group) { cms_group }
let(:layout) { create_cms_layout }
let(:node) { create(:article_node_page, cur_site: site, layout_id: layout.id) }
let!(:item) { create(:article_page, cur_site: site, cur_node: node, layout_id: layout.id, state: 'closed') }
let(:show_path) { article_page_path(site, node, item) }
let(:role_ids) { cms_user.cms_role_ids }
let(:group_ids) { cms_user.group_ids }
let(:user1) { create(:cms_test_user, group_ids: group_ids, cms_role_ids: role_ids) }
let(:user2) { create(:cms_test_user, group_ids: group_ids, cms_role_ids: role_ids) }
let(:user3) { create(:cms_test_user, group_ids: group_ids, cms_role_ids: role_ids) }
let(:user4) { create(:cms_test_user, group_ids: group_ids, cms_role_ids: role_ids) }
let(:user5) { create(:cms_test_user, group_ids: group_ids, cms_role_ids: role_ids) }
let(:route_name) { unique_id }
let(:workflow_comment) { unique_id }
let(:approve_comment1) { unique_id }
let(:approve_comment2) { unique_id }
let(:approve_comment3) { unique_id }
let(:remand_comment3) { unique_id }
before do
ActionMailer::Base.deliveries = []
end
after do
ActionMailer::Base.deliveries = []
end
context "all users must be approved" do
context "single user at a stage" do
let!(:route_single_user) do
create(
:workflow_route, name: route_name,
approvers: [
{ "level" => 1, "user_id" => user1.id },
{ "level" => 2, "user_id" => user2.id },
{ "level" => 3, "user_id" => user3.id },
],
required_counts: [ false, false, false, false, false ]
)
end
it do
expect(item.backups.count).to eq 1
#
# admin: send request
#
login_cms_user
visit show_path
within ".mod-workflow-request" do
select route_name, from: "workflow_route"
click_on I18n.t("workflow.buttons.select")
fill_in "workflow[comment]", with: workflow_comment
click_on I18n.t("workflow.buttons.request")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(user1.uid)}/)
item.reload
expect(item.workflow_user_id).to eq cms_user.id
expect(item.workflow_state).to eq "request"
expect(item.state).to eq "closed"
expect(item.workflow_comment).to eq workflow_comment
expect(item.workflow_approvers.count).to eq 3
expect(item.workflow_approvers[0]).to eq({level: 1, user_id: user1.id, editable: '', state: 'request', comment: ''})
expect(item.workflow_approvers[1]).to eq({level: 2, user_id: user2.id, editable: '', state: 'pending', comment: ''})
expect(item.workflow_approvers[2]).to eq({level: 3, user_id: user3.id, editable: '', state: 'pending', comment: ''})
# no backups are created while requesting approve
expect(item.backups.count).to eq 1
expect(Sys::MailLog.count).to eq 1
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user1.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
#
# user1: approve request
#
login_user user1
visit show_path
within ".mod-workflow-approve" do
fill_in "remand[comment]", with: approve_comment1
click_on I18n.t("workflow.buttons.approve")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(approve_comment1)}/)
item.reload
expect(item.workflow_state).to eq "request"
expect(item.state).to eq "closed"
expect(item.workflow_approvers[0]).to \
include({level: 1, user_id: user1.id, editable: '', state: 'approve', comment: approve_comment1})
expect(item.workflow_approvers[1]).to include({level: 2, user_id: user2.id, editable: '', state: 'request', comment: ''})
expect(item.workflow_approvers[2]).to include({level: 3, user_id: user3.id, editable: '', state: 'pending', comment: ''})
# no backups are created while requesting approve
expect(item.backups.count).to eq 1
expect(Sys::MailLog.count).to eq 2
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user2.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
#
# user2: approve request
#
login_user user2
visit show_path
within ".mod-workflow-approve" do
fill_in "remand[comment]", with: approve_comment2
click_on I18n.t("workflow.buttons.approve")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(approve_comment2)}/)
item.reload
expect(item.workflow_state).to eq "request"
expect(item.state).to eq "closed"
expect(item.workflow_approvers[0]).to \
include({level: 1, user_id: user1.id, editable: '', state: 'approve', comment: approve_comment1})
expect(item.workflow_approvers[1]).to \
include({level: 2, user_id: user2.id, editable: '', state: 'approve', comment: approve_comment2})
expect(item.workflow_approvers[2]).to include({level: 3, user_id: user3.id, editable: '', state: 'request', comment: ''})
# no backups are created while requesting approve
expect(item.backups.count).to eq 1
expect(Sys::MailLog.count).to eq 3
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user3.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
#
# user3: approve request, he is the last one
#
login_user user3
visit show_path
within ".mod-workflow-approve" do
fill_in "remand[comment]", with: approve_comment3
click_on I18n.t("workflow.buttons.approve")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(approve_comment3)}/)
item.reload
expect(item.workflow_state).to eq "approve"
expect(item.state).to eq "public"
expect(item.workflow_approvers[0]).to \
include({level: 1, user_id: user1.id, editable: '', state: 'approve', comment: approve_comment1})
expect(item.workflow_approvers[1]).to \
include({level: 2, user_id: user2.id, editable: '', state: 'approve', comment: approve_comment2})
expect(item.workflow_approvers[2]).to \
include({level: 3, user_id: user3.id, editable: '', state: 'approve', comment: approve_comment3})
# backup is created because page is in public
expect(item.backups.count).to eq 2
expect(Sys::MailLog.count).to eq 4
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq user3.email
expect(mail.to.first).to eq cms_user.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.approve')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(item.name)
end
end
end
context "multiple users at first stage" do
let!(:route) do
create(
:workflow_route, name: route_name,
approvers: [
{ "level" => 1, "user_id" => user1.id },
{ "level" => 1, "user_id" => user2.id },
{ "level" => 2, "user_id" => user3.id },
],
required_counts: [ false, false, false, false, false ]
)
end
it do
login_cms_user
visit show_path
#
# admin: send request
#
within ".mod-workflow-request" do
select route_name, from: "workflow_route"
click_on I18n.t("workflow.buttons.select")
fill_in "workflow[comment]", with: workflow_comment
click_on I18n.t("workflow.buttons.request")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(user1.uid)}/)
item.reload
expect(item.workflow_user_id).to eq cms_user.id
expect(item.workflow_state).to eq "request"
expect(item.state).to eq "closed"
expect(item.workflow_comment).to eq workflow_comment
expect(item.workflow_approvers.count).to eq 3
expect(item.workflow_approvers[0]).to eq({level: 1, user_id: user1.id, editable: '', state: 'request', comment: ''})
expect(item.workflow_approvers[1]).to eq({level: 1, user_id: user2.id, editable: '', state: 'request', comment: ''})
expect(item.workflow_approvers[2]).to eq({level: 2, user_id: user3.id, editable: '', state: 'pending', comment: ''})
expect(Sys::MailLog.count).to eq 2
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.first.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user1.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
ActionMailer::Base.deliveries.second.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user2.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
#
# user1: approve request
#
login_user user1
visit show_path
within ".mod-workflow-approve" do
fill_in "remand[comment]", with: approve_comment1
click_on I18n.t("workflow.buttons.approve")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(approve_comment1)}/)
item.reload
expect(item.workflow_state).to eq "request"
expect(item.state).to eq "closed"
expect(item.workflow_approvers[0]).to \
include({level: 1, user_id: user1.id, editable: '', state: 'approve', comment: approve_comment1})
expect(item.workflow_approvers[1]).to include({level: 1, user_id: user2.id, editable: '', state: 'request', comment: ''})
expect(item.workflow_approvers[2]).to include({level: 2, user_id: user3.id, editable: '', state: 'pending', comment: ''})
expect(Sys::MailLog.count).to eq 2
#
# user2: approve request
#
login_user user2
visit show_path
within ".mod-workflow-approve" do
fill_in "remand[comment]", with: approve_comment2
click_on I18n.t("workflow.buttons.approve")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(approve_comment2)}/)
item.reload
expect(item.workflow_state).to eq "request"
expect(item.state).to eq "closed"
expect(item.workflow_approvers[0]).to \
include({level: 1, user_id: user1.id, editable: '', state: 'approve', comment: approve_comment1})
expect(item.workflow_approvers[1]).to \
include({level: 1, user_id: user2.id, editable: '', state: 'approve', comment: approve_comment2})
expect(item.workflow_approvers[2]).to include({level: 2, user_id: user3.id, editable: '', state: 'request', comment: ''})
expect(Sys::MailLog.count).to eq 3
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user3.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
#
# user3: approve request, he is the last one
#
login_user user3
visit show_path
within ".mod-workflow-approve" do
fill_in "remand[comment]", with: approve_comment3
click_on I18n.t("workflow.buttons.approve")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(approve_comment3)}/)
item.reload
expect(item.workflow_state).to eq "approve"
expect(item.state).to eq "public"
expect(item.workflow_approvers[0]).to \
include({level: 1, user_id: user1.id, editable: '', state: 'approve', comment: approve_comment1})
expect(item.workflow_approvers[1]).to \
include({level: 1, user_id: user2.id, editable: '', state: 'approve', comment: approve_comment2})
expect(item.workflow_approvers[2]).to \
include({level: 2, user_id: user3.id, editable: '', state: 'approve', comment: approve_comment3})
expect(Sys::MailLog.count).to eq 4
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq user3.email
expect(mail.to.first).to eq cms_user.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.approve')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(item.name)
end
end
end
context "remand a request" do
let!(:route_single_user) do
create(
:workflow_route, name: route_name,
approvers: [
{ "level" => 1, "user_id" => user1.id },
{ "level" => 2, "user_id" => user2.id },
{ "level" => 3, "user_id" => user3.id },
],
required_counts: [ false, false, false, false, false ]
)
end
it do
login_cms_user
visit show_path
#
# admin: send request
#
within ".mod-workflow-request" do
select route_name, from: "workflow_route"
click_on I18n.t("workflow.buttons.select")
fill_in "workflow[comment]", with: workflow_comment
click_on I18n.t("workflow.buttons.request")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(user1.uid)}/)
item.reload
expect(item.workflow_user_id).to eq cms_user.id
expect(item.workflow_state).to eq "request"
expect(item.state).to eq "closed"
expect(item.workflow_comment).to eq workflow_comment
expect(item.workflow_approvers.count).to eq 3
expect(item.workflow_approvers[0]).to eq({level: 1, user_id: user1.id, editable: '', state: 'request', comment: ''})
expect(item.workflow_approvers[1]).to eq({level: 2, user_id: user2.id, editable: '', state: 'pending', comment: ''})
expect(item.workflow_approvers[2]).to eq({level: 3, user_id: user3.id, editable: '', state: 'pending', comment: ''})
expect(Sys::MailLog.count).to eq 1
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user1.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
#
# user1: approve request
#
login_user user1
visit show_path
within ".mod-workflow-approve" do
fill_in "remand[comment]", with: approve_comment1
click_on I18n.t("workflow.buttons.approve")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(approve_comment1)}/)
item.reload
expect(item.workflow_state).to eq "request"
expect(item.state).to eq "closed"
expect(item.workflow_approvers[0]).to \
include({level: 1, user_id: user1.id, editable: '', state: 'approve', comment: approve_comment1})
expect(item.workflow_approvers[1]).to include({level: 2, user_id: user2.id, editable: '', state: 'request', comment: ''})
expect(item.workflow_approvers[2]).to include({level: 3, user_id: user3.id, editable: '', state: 'pending', comment: ''})
expect(Sys::MailLog.count).to eq 2
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user2.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
#
# user2: approve request
#
login_user user2
visit show_path
within ".mod-workflow-approve" do
fill_in "remand[comment]", with: approve_comment2
click_on I18n.t("workflow.buttons.approve")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(approve_comment2)}/)
item.reload
expect(item.workflow_state).to eq "request"
expect(item.state).to eq "closed"
expect(item.workflow_approvers[0]).to \
include({level: 1, user_id: user1.id, editable: '', state: 'approve', comment: approve_comment1})
expect(item.workflow_approvers[1]).to \
include({level: 2, user_id: user2.id, editable: '', state: 'approve', comment: approve_comment2})
expect(item.workflow_approvers[2]).to include({level: 3, user_id: user3.id, editable: '', state: 'request', comment: ''})
expect(Sys::MailLog.count).to eq 3
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user3.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
#
# user3: remand request, he is the last one
#
login_user user3
visit show_path
within ".mod-workflow-approve" do
fill_in "remand[comment]", with: remand_comment3
click_on I18n.t("workflow.buttons.remand")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(remand_comment3)}/)
item.reload
expect(item.workflow_state).to eq "remand"
expect(item.state).to eq "closed"
expect(item.workflow_approvers[0]).to \
include({level: 1, user_id: user1.id, editable: '', state: 'approve', comment: approve_comment1})
expect(item.workflow_approvers[1]).to \
include({level: 2, user_id: user2.id, editable: '', state: 'approve', comment: approve_comment2})
expect(item.workflow_approvers[2]).to \
include({level: 3, user_id: user3.id, editable: '', state: 'remand', comment: remand_comment3})
expect(Sys::MailLog.count).to eq 4
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq user3.email
expect(mail.to.first).to eq cms_user.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.remand')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(user3.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(remand_comment3)
end
end
end
end
context "any users must be approved" do
context "multiple users at a stage and any of users must be approved" do
let!(:route) do
create(
:workflow_route, name: route_name,
approvers: [
{ "level" => 1, "user_id" => user1.id },
{ "level" => 1, "user_id" => user2.id },
{ "level" => 2, "user_id" => user3.id },
],
required_counts: [ 1, false, false, false, false ]
)
end
it do
login_cms_user
visit show_path
#
# admin: send request
#
within ".mod-workflow-request" do
select route_name, from: "workflow_route"
click_on I18n.t("workflow.buttons.select")
fill_in "workflow[comment]", with: workflow_comment
click_on I18n.t("workflow.buttons.request")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(user1.uid)}/)
item.reload
expect(item.workflow_user_id).to eq cms_user.id
expect(item.workflow_state).to eq "request"
expect(item.state).to eq "closed"
expect(item.workflow_comment).to eq workflow_comment
expect(item.workflow_approvers.count).to eq 3
expect(item.workflow_approvers[0]).to eq({level: 1, user_id: user1.id, editable: '', state: 'request', comment: ''})
expect(item.workflow_approvers[1]).to eq({level: 1, user_id: user2.id, editable: '', state: 'request', comment: ''})
expect(item.workflow_approvers[2]).to eq({level: 2, user_id: user3.id, editable: '', state: 'pending', comment: ''})
expect(Sys::MailLog.count).to eq 2
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.first.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user1.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
ActionMailer::Base.deliveries.second.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user2.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
#
# user1: approve request
#
login_user user1
visit show_path
within ".mod-workflow-approve" do
fill_in "remand[comment]", with: approve_comment1
click_on I18n.t("workflow.buttons.approve")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(approve_comment1)}/)
item.reload
expect(item.workflow_state).to eq "request"
expect(item.state).to eq "closed"
expect(item.workflow_approvers[0]).to \
include({level: 1, user_id: user1.id, editable: '', state: 'approve', comment: approve_comment1})
expect(item.workflow_approvers[1]).to \
include({level: 1, user_id: user2.id, editable: '', state: 'other_approved', comment: ''})
expect(item.workflow_approvers[2]).to include({level: 2, user_id: user3.id, editable: '', state: 'request', comment: ''})
expect(Sys::MailLog.count).to eq 3
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq cms_user.email
expect(mail.to.first).to eq user3.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.request')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(cms_user.name)
expect(mail.body.raw_source).to include(item.name)
expect(mail.body.raw_source).to include(workflow_comment)
end
#
# user3: approve request, user2 no needs to approve request
#
login_user user3
visit show_path
within ".mod-workflow-approve" do
fill_in "remand[comment]", with: approve_comment3
click_on I18n.t("workflow.buttons.approve")
end
expect(page).to have_css(".mod-workflow-view dd", text: /#{::Regexp.escape(approve_comment3)}/)
item.reload
expect(item.workflow_state).to eq "approve"
expect(item.state).to eq "public"
expect(item.workflow_approvers[0]).to \
include({level: 1, user_id: user1.id, editable: '', state: 'approve', comment: approve_comment1})
expect(item.workflow_approvers[1]).to \
include({level: 1, user_id: user2.id, editable: '', state: 'other_approved', comment: ''})
expect(item.workflow_approvers[2]).to \
include({level: 2, user_id: user3.id, editable: '', state: 'approve', comment: approve_comment3})
expect(Sys::MailLog.count).to eq 4
expect(ActionMailer::Base.deliveries.length).to eq Sys::MailLog.count
ActionMailer::Base.deliveries.last.tap do |mail|
expect(mail.from.first).to eq user3.email
expect(mail.to.first).to eq cms_user.email
expect(mail.subject).to eq "[#{I18n.t('workflow.mail.subject.approve')}]#{item.name} - #{site.name}"
expect(mail.body.multipart?).to be_falsey
expect(mail.body.raw_source).to include(item.name)
end
end
end
end
end
| {
"content_hash": "cae3911026dd3f1adc091e2edd67fda7",
"timestamp": "",
"source": "github",
"line_count": 634,
"max_line_length": 129,
"avg_line_length": 44.75552050473186,
"alnum_prop": 0.6114537444933921,
"repo_name": "MasakiInaya/shirasagi",
"id": "8bf0d25f73272597bcfda3fd6d70e46eecebc38f",
"size": "28375",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "spec/features/workflow/multi_stage_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "528135"
},
{
"name": "HTML",
"bytes": "2985497"
},
{
"name": "JavaScript",
"bytes": "4946932"
},
{
"name": "Ruby",
"bytes": "7064536"
},
{
"name": "Shell",
"bytes": "20886"
}
],
"symlink_target": ""
} |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using HETSAPI.Models;
using HETSAPI.ViewModels;
namespace HETSAPI.Services.Impl
{
/// <summary>
///
/// </summary>
public class SeniorityAuditService : ISeniorityAuditService
{
private readonly DbAppContext _context;
/// <summary>
/// Create a service and set the database context
/// </summary>
public SeniorityAuditService(DbAppContext context)
{
_context = context;
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <response code="201">SeniorityAudit created</response>
public virtual IActionResult SeniorityauditsBulkPostAsync(SeniorityAudit[] items)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <response code="200">OK</response>
public virtual IActionResult SeniorityauditsGetAsync()
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SeniorityAudit to delete</param>
/// <response code="200">OK</response>
/// <response code="404">SeniorityAudit not found</response>
public virtual IActionResult SeniorityauditsIdDeletePostAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SeniorityAudit to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">SeniorityAudit not found</response>
public virtual IActionResult SeniorityauditsIdGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SeniorityAudit to fetch</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">SeniorityAudit not found</response>
public virtual IActionResult SeniorityauditsIdPutAsync(int id, SeniorityAudit item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <response code="201">SeniorityAudit created</response>
public virtual IActionResult SeniorityauditsPostAsync(SeniorityAudit item)
{
var result = "";
return new ObjectResult(result);
}
}
}
| {
"content_hash": "294f5d528b680e4233cb52d967109e76",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 467,
"avg_line_length": 32.57657657657658,
"alnum_prop": 0.6042588495575221,
"repo_name": "plavoieBC/hets",
"id": "e8ea103d9b457664e34df576377fa631d7c8039e",
"size": "3616",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "APISpec/gen/src/HETSAPI/Services.Impl/SeniorityAuditService.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9077"
},
{
"name": "C#",
"bytes": "4126242"
},
{
"name": "CSS",
"bytes": "60442"
},
{
"name": "HTML",
"bytes": "343352"
},
{
"name": "JavaScript",
"bytes": "475168"
},
{
"name": "PowerShell",
"bytes": "805"
},
{
"name": "Python",
"bytes": "4784"
},
{
"name": "Shell",
"bytes": "5609"
}
],
"symlink_target": ""
} |
from hyquest.models import QuestSet, UserQuestSetAction
from hyquest.actionmanager import beginQuestSet
from hyquest.constants import MAX_ACTIVE_QUESTS
import time
# Here are the methods used to ensure proper quest flow for users
# These are called for each user whenever the dashboard is loaded
def replenishQuestSets(user):
activeQuests = UserQuestSetAction.objects.filter(user=user, questset__featured=False, questset__active=True).count()
if(activeQuests < MAX_ACTIVE_QUESTS):
#Get all completed quests
completed = UserQuestSetAction.objects.filter(user=user, complete=True).values_list('questset', flat=True)
#filter quest sets where dependancies are met or dependancies are null
newquests = QuestSet.objects.filter(depends_on__in=completed, active=True) | QuestSet.objects.filter(depends_on__isnull=True, active=True)
#filter out quest sets which have an action
withactions = UserQuestSetAction.objects.filter(user=user).values_list('questset', flat=True)
newquests = newquests.exclude(id__in=withactions)
for newquest in newquests:
if activeQuests >= MAX_ACTIVE_QUESTS:
return
beginQuestSet(user, newquest)
activeQuests += 1
#time.sleep(0.5)
def activateFeaturedQuestSets(user):
for questset in QuestSet.objects.filter(featured=True):
if not UserQuestSetAction.objects.filter(user=user, questset=questset).exists():
beginQuestSet(user, questset)
| {
"content_hash": "e7ee9c98a1a33954c84a5a2245145750",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 146,
"avg_line_length": 47.34375,
"alnum_prop": 0.7254125412541255,
"repo_name": "Edmonton-Public-Library/centennial",
"id": "f4c22a138bde71d59346b580ecc758fef8eb00cf",
"size": "1515",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hyquest/questmanager.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "142503"
},
{
"name": "JavaScript",
"bytes": "879929"
},
{
"name": "Python",
"bytes": "149260"
},
{
"name": "Shell",
"bytes": "890"
}
],
"symlink_target": ""
} |
package packets
import (
"github.com/bnch/bancho/pid"
)
// ChannelJoin returns a packet of successful joining of a channel.
func ChannelJoin(channel string) Packet {
return StringPacket(pid.BanchoChannelJoinSuccess, channel)
}
| {
"content_hash": "cd4ee0ff980f398c601b3de6a50774e0",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 67,
"avg_line_length": 23.1,
"alnum_prop": 0.7878787878787878,
"repo_name": "bnch/bancho",
"id": "94129806599065b0e15874e692f44ea00a1c336b",
"size": "231",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packets/channel_join.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "21518"
},
{
"name": "Go",
"bytes": "69410"
},
{
"name": "HTML",
"bytes": "2800"
},
{
"name": "JavaScript",
"bytes": "711"
},
{
"name": "Makefile",
"bytes": "278"
}
],
"symlink_target": ""
} |
require 'geocoder'
require 'timezone'
module Fonecal
class GrandPrix
attr_accessor :events, :circuit
def initialize(eventWebsite)
@crawler = EventCrawler.new(eventWebsite)
self.circuit= CircuitInfo.new(@crawler.circuitInfo)
self.events = []
createEvents
end
def location
if @res ||= Geocoder.search("#{@circuit.name}, #{@circuit.city}").first
@res
elsif @res ||= Geocoder.search("#{@circuit.city}").first
@res
elsif res ||= Geocoder.search("#{@circuit.name}").first
@res
else
@res
end
end
def city
@circuit.city
end
def country
location.country
end
def timezone
@timezone ||= Timezone::Zone.new :latlon => location.geometry["location"].values
end
def raceTitle
title = @crawler.gp.split(/(\W)/).map(&:capitalize).join
# Dirty decapitalization hack
title = title.gsub(/Í/, 'í')
title = title.gsub(/J/, 'j')
end
def grandPrix
"#{country} GP"
# Belgian Grand Prix
end
private
def createEvents
@crawler.timeTables.each do |day|
day[:sessions].each do |event|
type = event[:type]
event[:date] = day[:date]
if ['practice 1', 'practice 2', 'practice 3'].include?(type.downcase)
@events << Practice.new(event, timezone)
elsif type == "Qualifying"
@events << Qualifying.new(event, timezone)
elsif type == "Race"
@events << Race.new(event, timezone)
end
end
end
end
end
end
| {
"content_hash": "1372a1f8822e0566bdc5929188a9e625",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 86,
"avg_line_length": 22.47222222222222,
"alnum_prop": 0.5686032138442522,
"repo_name": "martinbjeldbak/fonecal",
"id": "d7061e218b3a24fc348f5a56ae8301d016c865e8",
"size": "1620",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/fonecal/grand_prix.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "34156"
}
],
"symlink_target": ""
} |
require 'spec_helper'
module Deathstare
describe UpstreamSession do
context "subclassing" do
it "generation" do
device = SpecSession.generate FactoryGirl.create(:end_point)
device.save!
expect(device).to be_valid
end
it "warms up" do
@session_token = SecureRandom.uuid
device = SpecSession.generate FactoryGirl.create(:end_point)
device.save!
client = double('Client')
expect(client).to receive(:http).
with(:post, '/api/login', device.session_params).
and_return(RequestPromise::Success.new(response: {session_token: @session_token}))
device.register_and_login(client)
expect(device.info.session_token).to eq @session_token
end
end
end
end
| {
"content_hash": "5a17f7e5e1c77449cfdbe3e61088b273",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 94,
"avg_line_length": 28,
"alnum_prop": 0.6403061224489796,
"repo_name": "cloudcity/deathstare",
"id": "5dbbf096bfc1b123d38a8427163b2b94836a7720",
"size": "784",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/models/upstream_session_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1426"
},
{
"name": "CoffeeScript",
"bytes": "3346"
},
{
"name": "JavaScript",
"bytes": "857"
},
{
"name": "Ruby",
"bytes": "112361"
}
],
"symlink_target": ""
} |
<a name="0x1_DesignatedDealer"></a>
# Module `0x1::DesignatedDealer`
Module providing functionality for designated dealers.
- [Resource `Dealer`](#0x1_DesignatedDealer_Dealer)
- [Resource `TierInfo`](#0x1_DesignatedDealer_TierInfo)
- [Struct `ReceivedMintEvent`](#0x1_DesignatedDealer_ReceivedMintEvent)
- [Constants](#@Constants_0)
- [Function `publish_designated_dealer_credential`](#0x1_DesignatedDealer_publish_designated_dealer_credential)
- [Function `add_currency`](#0x1_DesignatedDealer_add_currency)
- [Function `tiered_mint`](#0x1_DesignatedDealer_tiered_mint)
- [Function `exists_at`](#0x1_DesignatedDealer_exists_at)
- [Module Specification](#@Module_Specification_1)
<pre><code><b>use</b> <a href="Diem.md#0x1_Diem">0x1::Diem</a>;
<b>use</b> <a href="../../../../../../move-stdlib/docs/Errors.md#0x1_Errors">0x1::Errors</a>;
<b>use</b> <a href="../../../../../../move-stdlib/docs/Event.md#0x1_Event">0x1::Event</a>;
<b>use</b> <a href="Roles.md#0x1_Roles">0x1::Roles</a>;
<b>use</b> <a href="../../../../../../move-stdlib/docs/Signer.md#0x1_Signer">0x1::Signer</a>;
<b>use</b> <a href="XUS.md#0x1_XUS">0x1::XUS</a>;
</code></pre>
<a name="0x1_DesignatedDealer_Dealer"></a>
## Resource `Dealer`
A <code><a href="DesignatedDealer.md#0x1_DesignatedDealer">DesignatedDealer</a></code> always holds this <code><a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a></code> resource regardless of the
currencies it can hold. All <code><a href="DesignatedDealer.md#0x1_DesignatedDealer_ReceivedMintEvent">ReceivedMintEvent</a></code> events for all
currencies will be emitted on <code>mint_event_handle</code>.
<pre><code><b>struct</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a> has key
</code></pre>
<details>
<summary>Fields</summary>
<dl>
<dt>
<code>mint_event_handle: <a href="../../../../../../move-stdlib/docs/Event.md#0x1_Event_EventHandle">Event::EventHandle</a><<a href="DesignatedDealer.md#0x1_DesignatedDealer_ReceivedMintEvent">DesignatedDealer::ReceivedMintEvent</a>></code>
</dt>
<dd>
Handle for mint events
</dd>
</dl>
</details>
<a name="0x1_DesignatedDealer_TierInfo"></a>
## Resource `TierInfo`
The <code><a href="DesignatedDealer.md#0x1_DesignatedDealer_TierInfo">TierInfo</a></code> resource holds the information needed to track which
tier a mint to a DD needs to be in.
DEPRECATED: This resource is no longer used and will be removed from the system
<pre><code><b>struct</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_TierInfo">TierInfo</a><CoinType> has key
</code></pre>
<details>
<summary>Fields</summary>
<dl>
<dt>
<code>window_start: u64</code>
</dt>
<dd>
Time window start in microseconds
</dd>
<dt>
<code>window_inflow: u64</code>
</dt>
<dd>
The minted inflow during this time window
</dd>
<dt>
<code>tiers: vector<u64></code>
</dt>
<dd>
0-indexed array of tier upperbounds
</dd>
</dl>
</details>
<a name="0x1_DesignatedDealer_ReceivedMintEvent"></a>
## Struct `ReceivedMintEvent`
Message for mint events
<pre><code><b>struct</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_ReceivedMintEvent">ReceivedMintEvent</a> has drop, store
</code></pre>
<details>
<summary>Fields</summary>
<dl>
<dt>
<code>currency_code: vector<u8></code>
</dt>
<dd>
The currency minted
</dd>
<dt>
<code>destination_address: address</code>
</dt>
<dd>
The address that receives the mint
</dd>
<dt>
<code>amount: u64</code>
</dt>
<dd>
The amount minted (in base units of <code>currency_code</code>)
</dd>
</dl>
</details>
<a name="@Constants_0"></a>
## Constants
<a name="0x1_DesignatedDealer_EDEALER"></a>
The <code><a href="DesignatedDealer.md#0x1_DesignatedDealer">DesignatedDealer</a></code> resource is in an invalid state
<pre><code><b>const</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_EDEALER">EDEALER</a>: u64 = 0;
</code></pre>
<a name="0x1_DesignatedDealer_EINVALID_MINT_AMOUNT"></a>
A zero mint amount was provided
<pre><code><b>const</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_EINVALID_MINT_AMOUNT">EINVALID_MINT_AMOUNT</a>: u64 = 4;
</code></pre>
<a name="0x1_DesignatedDealer_publish_designated_dealer_credential"></a>
## Function `publish_designated_dealer_credential`
Publishes a <code><a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a></code> resource under <code>dd</code> with a <code>PreburnQueue</code>.
If <code>add_all_currencies = <b>true</b></code> this will add a <code>PreburnQueue</code>,
for each known currency at launch.
<pre><code><b>public</b>(<b>friend</b>) <b>fun</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_publish_designated_dealer_credential">publish_designated_dealer_credential</a><CoinType>(dd: &signer, tc_account: &signer, add_all_currencies: bool)
</code></pre>
<details>
<summary>Implementation</summary>
<pre><code><b>public</b>(<b>friend</b>) <b>fun</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_publish_designated_dealer_credential">publish_designated_dealer_credential</a><CoinType>(
dd: &signer,
tc_account: &signer,
add_all_currencies: bool,
){
<a href="Roles.md#0x1_Roles_assert_treasury_compliance">Roles::assert_treasury_compliance</a>(tc_account);
<a href="Roles.md#0x1_Roles_assert_designated_dealer">Roles::assert_designated_dealer</a>(dd);
<b>assert</b>(!<b>exists</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a>>(<a href="../../../../../../move-stdlib/docs/Signer.md#0x1_Signer_address_of">Signer::address_of</a>(dd)), <a href="../../../../../../move-stdlib/docs/Errors.md#0x1_Errors_already_published">Errors::already_published</a>(<a href="DesignatedDealer.md#0x1_DesignatedDealer_EDEALER">EDEALER</a>));
move_to(dd, <a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a> { mint_event_handle: <a href="../../../../../../move-stdlib/docs/Event.md#0x1_Event_new_event_handle">Event::new_event_handle</a><<a href="DesignatedDealer.md#0x1_DesignatedDealer_ReceivedMintEvent">ReceivedMintEvent</a>>(dd) });
<b>if</b> (add_all_currencies) {
<a href="DesignatedDealer.md#0x1_DesignatedDealer_add_currency">add_currency</a><<a href="XUS.md#0x1_XUS">XUS</a>>(dd, tc_account);
} <b>else</b> {
<a href="DesignatedDealer.md#0x1_DesignatedDealer_add_currency">add_currency</a><CoinType>(dd, tc_account);
};
}
</code></pre>
</details>
<details>
<summary>Specification</summary>
<pre><code><b>pragma</b> opaque;
<b>let</b> dd_addr = <a href="../../../../../../move-stdlib/docs/Signer.md#0x1_Signer_spec_address_of">Signer::spec_address_of</a>(dd);
<b>include</b> <a href="Roles.md#0x1_Roles_AbortsIfNotTreasuryCompliance">Roles::AbortsIfNotTreasuryCompliance</a>{account: tc_account};
<b>include</b> <a href="Roles.md#0x1_Roles_AbortsIfNotDesignatedDealer">Roles::AbortsIfNotDesignatedDealer</a>{account: dd};
<b>aborts_if</b> <b>exists</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a>>(dd_addr) <b>with</b> <a href="../../../../../../move-stdlib/docs/Errors.md#0x1_Errors_ALREADY_PUBLISHED">Errors::ALREADY_PUBLISHED</a>;
<b>include</b> <b>if</b> (add_all_currencies) <a href="DesignatedDealer.md#0x1_DesignatedDealer_AddCurrencyAbortsIf">AddCurrencyAbortsIf</a><<a href="XUS.md#0x1_XUS">XUS</a>>{dd_addr: dd_addr}
<b>else</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_AddCurrencyAbortsIf">AddCurrencyAbortsIf</a><CoinType>{dd_addr: dd_addr};
<b>modifies</b> <b>global</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a>>(dd_addr);
<b>ensures</b> <b>exists</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a>>(dd_addr);
<b>modifies</b> <b>global</b><<a href="../../../../../../move-stdlib/docs/Event.md#0x1_Event_EventHandleGenerator">Event::EventHandleGenerator</a>>(dd_addr);
<b>modifies</b> <b>global</b><<a href="Diem.md#0x1_Diem_PreburnQueue">Diem::PreburnQueue</a><CoinType>>(dd_addr);
<b>modifies</b> <b>global</b><<a href="Diem.md#0x1_Diem_PreburnQueue">Diem::PreburnQueue</a><<a href="XUS.md#0x1_XUS">XUS</a>>>(dd_addr);
</code></pre>
</details>
<a name="0x1_DesignatedDealer_add_currency"></a>
## Function `add_currency`
Adds the needed resources to the DD account <code>dd</code> in order to work with <code>CoinType</code>.
Public so that a currency can be added to a DD later on. Will require
multi-signer transactions in order to add a new currency to an existing DD.
<pre><code><b>public</b> <b>fun</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_add_currency">add_currency</a><CoinType>(dd: &signer, tc_account: &signer)
</code></pre>
<details>
<summary>Implementation</summary>
<pre><code><b>public</b> <b>fun</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_add_currency">add_currency</a><CoinType>(dd: &signer, tc_account: &signer) {
<a href="Roles.md#0x1_Roles_assert_treasury_compliance">Roles::assert_treasury_compliance</a>(tc_account);
<b>let</b> dd_addr = <a href="../../../../../../move-stdlib/docs/Signer.md#0x1_Signer_address_of">Signer::address_of</a>(dd);
<b>assert</b>(<a href="DesignatedDealer.md#0x1_DesignatedDealer_exists_at">exists_at</a>(dd_addr), <a href="../../../../../../move-stdlib/docs/Errors.md#0x1_Errors_not_published">Errors::not_published</a>(<a href="DesignatedDealer.md#0x1_DesignatedDealer_EDEALER">EDEALER</a>));
<a href="Diem.md#0x1_Diem_publish_preburn_queue_to_account">Diem::publish_preburn_queue_to_account</a><CoinType>(dd, tc_account);
}
</code></pre>
</details>
<details>
<summary>Specification</summary>
<pre><code><b>pragma</b> opaque;
<b>let</b> dd_addr = <a href="../../../../../../move-stdlib/docs/Signer.md#0x1_Signer_spec_address_of">Signer::spec_address_of</a>(dd);
<b>include</b> <a href="Roles.md#0x1_Roles_AbortsIfNotTreasuryCompliance">Roles::AbortsIfNotTreasuryCompliance</a>{account: tc_account};
<b>include</b> <a href="Roles.md#0x1_Roles_AbortsIfNotDesignatedDealer">Roles::AbortsIfNotDesignatedDealer</a>{account: dd};
<b>include</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_AbortsIfNoDealer">AbortsIfNoDealer</a>{dd_addr: dd_addr};
<b>include</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_AddCurrencyAbortsIf">AddCurrencyAbortsIf</a><CoinType>{dd_addr: dd_addr};
<b>modifies</b> <b>global</b><<a href="Diem.md#0x1_Diem_PreburnQueue">Diem::PreburnQueue</a><CoinType>>(dd_addr);
</code></pre>
<a name="0x1_DesignatedDealer_AddCurrencyAbortsIf"></a>
<pre><code><b>schema</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_AddCurrencyAbortsIf">AddCurrencyAbortsIf</a><CoinType> {
dd_addr: address;
<b>include</b> <a href="Diem.md#0x1_Diem_AbortsIfNoCurrency">Diem::AbortsIfNoCurrency</a><CoinType>;
<b>aborts_if</b> <a href="Diem.md#0x1_Diem_is_synthetic_currency">Diem::is_synthetic_currency</a><CoinType>() <b>with</b> <a href="../../../../../../move-stdlib/docs/Errors.md#0x1_Errors_INVALID_ARGUMENT">Errors::INVALID_ARGUMENT</a>;
<b>aborts_if</b> <b>exists</b><<a href="Diem.md#0x1_Diem_PreburnQueue">Diem::PreburnQueue</a><CoinType>>(dd_addr) <b>with</b> <a href="../../../../../../move-stdlib/docs/Errors.md#0x1_Errors_ALREADY_PUBLISHED">Errors::ALREADY_PUBLISHED</a>;
<b>aborts_if</b> <b>exists</b><<a href="Diem.md#0x1_Diem_Preburn">Diem::Preburn</a><CoinType>>(dd_addr) <b>with</b> <a href="../../../../../../move-stdlib/docs/Errors.md#0x1_Errors_INVALID_STATE">Errors::INVALID_STATE</a>;
}
</code></pre>
</details>
<a name="0x1_DesignatedDealer_tiered_mint"></a>
## Function `tiered_mint`
<pre><code><b>public</b> <b>fun</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_tiered_mint">tiered_mint</a><CoinType>(tc_account: &signer, amount: u64, dd_addr: address, _tier_index: u64): <a href="Diem.md#0x1_Diem_Diem">Diem::Diem</a><CoinType>
</code></pre>
<details>
<summary>Implementation</summary>
<pre><code><b>public</b> <b>fun</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_tiered_mint">tiered_mint</a><CoinType>(
tc_account: &signer,
amount: u64,
dd_addr: address,
// tiers are deprecated. We <b>continue</b> <b>to</b> accept this argument for backward
// compatibility, but it will be ignored.
_tier_index: u64,
): <a href="Diem.md#0x1_Diem_Diem">Diem::Diem</a><CoinType> <b>acquires</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a>, <a href="DesignatedDealer.md#0x1_DesignatedDealer_TierInfo">TierInfo</a> {
<a href="Roles.md#0x1_Roles_assert_treasury_compliance">Roles::assert_treasury_compliance</a>(tc_account);
<b>assert</b>(amount > 0, <a href="../../../../../../move-stdlib/docs/Errors.md#0x1_Errors_invalid_argument">Errors::invalid_argument</a>(<a href="DesignatedDealer.md#0x1_DesignatedDealer_EINVALID_MINT_AMOUNT">EINVALID_MINT_AMOUNT</a>));
<b>assert</b>(<a href="DesignatedDealer.md#0x1_DesignatedDealer_exists_at">exists_at</a>(dd_addr), <a href="../../../../../../move-stdlib/docs/Errors.md#0x1_Errors_not_published">Errors::not_published</a>(<a href="DesignatedDealer.md#0x1_DesignatedDealer_EDEALER">EDEALER</a>));
// Delete deprecated `<a href="DesignatedDealer.md#0x1_DesignatedDealer_TierInfo">TierInfo</a>` resources.
// TODO: delete this code once there are no more <a href="DesignatedDealer.md#0x1_DesignatedDealer_TierInfo">TierInfo</a> resources in the system
<b>if</b> (<b>exists</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_TierInfo">TierInfo</a><CoinType>>(dd_addr)) {
<b>let</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_TierInfo">TierInfo</a> { window_start: _, window_inflow: _, tiers: _ } = move_from<<a href="DesignatedDealer.md#0x1_DesignatedDealer_TierInfo">TierInfo</a><CoinType>>(dd_addr);
};
// Send <a href="DesignatedDealer.md#0x1_DesignatedDealer_ReceivedMintEvent">ReceivedMintEvent</a>
<a href="../../../../../../move-stdlib/docs/Event.md#0x1_Event_emit_event">Event::emit_event</a><<a href="DesignatedDealer.md#0x1_DesignatedDealer_ReceivedMintEvent">ReceivedMintEvent</a>>(
&<b>mut</b> borrow_global_mut<<a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a>>(dd_addr).mint_event_handle,
<a href="DesignatedDealer.md#0x1_DesignatedDealer_ReceivedMintEvent">ReceivedMintEvent</a> {
currency_code: <a href="Diem.md#0x1_Diem_currency_code">Diem::currency_code</a><CoinType>(),
destination_address: dd_addr,
amount
},
);
<a href="Diem.md#0x1_Diem_mint">Diem::mint</a><CoinType>(tc_account, amount)
}
</code></pre>
</details>
<details>
<summary>Specification</summary>
<pre><code><b>pragma</b> opaque;
<b>include</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_TieredMintAbortsIf">TieredMintAbortsIf</a><CoinType>;
<b>modifies</b> <b>global</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a>>(dd_addr);
<b>modifies</b> <b>global</b><<a href="Diem.md#0x1_Diem_CurrencyInfo">Diem::CurrencyInfo</a><CoinType>>(@CurrencyInfo);
<b>ensures</b> <b>exists</b><<a href="Diem.md#0x1_Diem_CurrencyInfo">Diem::CurrencyInfo</a><CoinType>>(@CurrencyInfo);
<b>modifies</b> <b>global</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_TierInfo">TierInfo</a><CoinType>>(dd_addr);
<b>ensures</b> !<b>exists</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_TierInfo">TierInfo</a><CoinType>>(dd_addr);
<b>let</b> currency_info = <b>global</b><<a href="Diem.md#0x1_Diem_CurrencyInfo">Diem::CurrencyInfo</a><CoinType>>(@CurrencyInfo);
<b>let</b> post post_currency_info = <b>global</b><<a href="Diem.md#0x1_Diem_CurrencyInfo">Diem::CurrencyInfo</a><CoinType>>(@CurrencyInfo);
<b>ensures</b> result.value == amount;
<b>ensures</b> post_currency_info == update_field(currency_info, total_value, currency_info.total_value + amount);
</code></pre>
<a name="0x1_DesignatedDealer_TieredMintAbortsIf"></a>
<pre><code><b>schema</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_TieredMintAbortsIf">TieredMintAbortsIf</a><CoinType> {
tc_account: signer;
dd_addr: address;
amount: u64;
<b>include</b> <a href="Roles.md#0x1_Roles_AbortsIfNotTreasuryCompliance">Roles::AbortsIfNotTreasuryCompliance</a>{account: tc_account};
<b>aborts_if</b> amount == 0 <b>with</b> <a href="../../../../../../move-stdlib/docs/Errors.md#0x1_Errors_INVALID_ARGUMENT">Errors::INVALID_ARGUMENT</a>;
<b>include</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_AbortsIfNoDealer">AbortsIfNoDealer</a>;
<b>aborts_if</b> !<b>exists</b><<a href="Diem.md#0x1_Diem_MintCapability">Diem::MintCapability</a><CoinType>>(<a href="../../../../../../move-stdlib/docs/Signer.md#0x1_Signer_spec_address_of">Signer::spec_address_of</a>(tc_account)) <b>with</b> <a href="../../../../../../move-stdlib/docs/Errors.md#0x1_Errors_REQUIRES_CAPABILITY">Errors::REQUIRES_CAPABILITY</a>;
<b>include</b> <a href="Diem.md#0x1_Diem_MintAbortsIf">Diem::MintAbortsIf</a><CoinType>{value: amount};
}
</code></pre>
</details>
<a name="0x1_DesignatedDealer_exists_at"></a>
## Function `exists_at`
<pre><code><b>public</b> <b>fun</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_exists_at">exists_at</a>(dd_addr: address): bool
</code></pre>
<details>
<summary>Implementation</summary>
<pre><code><b>public</b> <b>fun</b> <a href="DesignatedDealer.md#0x1_DesignatedDealer_exists_at">exists_at</a>(dd_addr: address): bool {
<b>exists</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a>>(dd_addr)
}
</code></pre>
</details>
<details>
<summary>Specification</summary>
<pre><code><b>pragma</b> opaque;
<b>aborts_if</b> <b>false</b>;
<b>ensures</b> result == <b>exists</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a>>(dd_addr);
</code></pre>
</details>
<a name="@Module_Specification_1"></a>
## Module Specification
resource struct Dealer persists after publication
<pre><code><b>invariant</b> <b>update</b> <b>forall</b> addr: address <b>where</b> <b>old</b>(<b>exists</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a>>(addr)): <b>exists</b><<a href="DesignatedDealer.md#0x1_DesignatedDealer_Dealer">Dealer</a>>(addr);
</code></pre>
[//]: # ("File containing references which can be used from documentation")
[ACCESS_CONTROL]: https://github.com/diem/dip/blob/main/dips/dip-2.md
[ROLE]: https://github.com/diem/dip/blob/main/dips/dip-2.md#roles
[PERMISSION]: https://github.com/diem/dip/blob/main/dips/dip-2.md#permissions
| {
"content_hash": "751c946f35cdd9e057b137816e2dff49",
"timestamp": "",
"source": "github",
"line_count": 435,
"max_line_length": 402,
"avg_line_length": 43.232183908045975,
"alnum_prop": 0.6998298415399341,
"repo_name": "libra/libra",
"id": "5273db3f045c930fed20290a183b14b568b81681",
"size": "18807",
"binary": false,
"copies": "1",
"ref": "refs/heads/dependabot/github_actions/actions/cache-3.0.1",
"path": "diem-move/diem-framework/DPN/releases/artifacts/release-1.4.0-rc0/docs/modules/DesignatedDealer.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "9268"
},
{
"name": "Dockerfile",
"bytes": "13236"
},
{
"name": "HCL",
"bytes": "52195"
},
{
"name": "HTML",
"bytes": "50430"
},
{
"name": "Makefile",
"bytes": "269"
},
{
"name": "Python",
"bytes": "2907"
},
{
"name": "RenderScript",
"bytes": "117"
},
{
"name": "Rust",
"bytes": "7142555"
},
{
"name": "Shell",
"bytes": "58888"
},
{
"name": "TeX",
"bytes": "17294"
}
],
"symlink_target": ""
} |
/*
* 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.
*/
/*
* This code was generated by https://github.com/google/apis-client-generator/
* (build: 2017-02-15 17:18:02 UTC)
* on 2017-04-23 at 19:31:11 UTC
* Modify at your own risk.
*/
package io.bloombox.bloombox.client.EmbedAPI;
/**
* EmbedAPI request initializer for setting properties like key and userIp.
*
* <p>
* The simplest usage is to use it to set the key parameter:
* </p>
*
* <pre>
public static final GoogleClientRequestInitializer KEY_INITIALIZER =
new EmbedAPIRequestInitializer(KEY);
* </pre>
*
* <p>
* There is also a constructor to set both the key and userIp parameters:
* </p>
*
* <pre>
public static final GoogleClientRequestInitializer INITIALIZER =
new EmbedAPIRequestInitializer(KEY, USER_IP);
* </pre>
*
* <p>
* If you want to implement custom logic, extend it like this:
* </p>
*
* <pre>
public static class MyRequestInitializer extends EmbedAPIRequestInitializer {
{@literal @}Override
public void initializeEmbedAPIRequest(EmbedAPIRequest{@literal <}?{@literal >} request)
throws IOException {
// custom logic
}
}
* </pre>
*
* <p>
* Finally, to set the key and userIp parameters and insert custom logic, extend it like this:
* </p>
*
* <pre>
public static class MyRequestInitializer2 extends EmbedAPIRequestInitializer {
public MyKeyRequestInitializer() {
super(KEY, USER_IP);
}
{@literal @}Override
public void initializeEmbedAPIRequest(EmbedAPIRequest{@literal <}?{@literal >} request)
throws IOException {
// custom logic
}
}
* </pre>
*
* <p>
* Subclasses should be thread-safe.
* </p>
*
* @since 1.12
*/
public class EmbedAPIRequestInitializer extends com.google.api.client.googleapis.services.json.CommonGoogleJsonClientRequestInitializer {
public EmbedAPIRequestInitializer() {
super();
}
/**
* @param key API key or {@code null} to leave it unchanged
*/
public EmbedAPIRequestInitializer(String key) {
super(key);
}
/**
* @param key API key or {@code null} to leave it unchanged
* @param userIp user IP or {@code null} to leave it unchanged
*/
public EmbedAPIRequestInitializer(String key, String userIp) {
super(key, userIp);
}
@Override
public final void initializeJsonRequest(com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest<?> request) throws java.io.IOException {
super.initializeJsonRequest(request);
initializeEmbedAPIRequest((EmbedAPIRequest<?>) request);
}
/**
* Initializes EmbedAPI request.
*
* <p>
* Default implementation does nothing. Called from
* {@link #initializeJsonRequest(com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest)}.
* </p>
*
* @throws java.io.IOException I/O exception
*/
protected void initializeEmbedAPIRequest(EmbedAPIRequest<?> request) throws java.io.IOException {
}
}
| {
"content_hash": "d8b5ff6aa545cfd08865198e02679dc2",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 161,
"avg_line_length": 28.727272727272727,
"alnum_prop": 0.703970080552359,
"repo_name": "Bloombox/bloombox-client",
"id": "2a36fc02ebf50f16e7810ac27b492b51c87010da",
"size": "3476",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Java/Embed/src/main/java/io/bloombox/bloombox/client/EmbedAPI/EmbedAPIRequestInitializer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3017"
},
{
"name": "Java",
"bytes": "33271"
},
{
"name": "JavaScript",
"bytes": "38980"
},
{
"name": "Makefile",
"bytes": "4827"
},
{
"name": "Objective-C",
"bytes": "23290"
},
{
"name": "Python",
"bytes": "21461"
}
],
"symlink_target": ""
} |
// flow-typed signature: 0a23a8e8191f9efe1e1d641395365ff9
// flow-typed version: <<STUB>>/gulp_v^3.9.0/flow_v0.37.4
/**
* This is an autogenerated libdef stub for:
*
* 'gulp'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'gulp' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'gulp/bin/gulp' {
declare module.exports: any;
}
declare module 'gulp/lib/completion' {
declare module.exports: any;
}
declare module 'gulp/lib/taskTree' {
declare module.exports: any;
}
// Filename aliases
declare module 'gulp/bin/gulp.js' {
declare module.exports: $Exports<'gulp/bin/gulp'>;
}
declare module 'gulp/index' {
declare module.exports: $Exports<'gulp'>;
}
declare module 'gulp/index.js' {
declare module.exports: $Exports<'gulp'>;
}
declare module 'gulp/lib/completion.js' {
declare module.exports: $Exports<'gulp/lib/completion'>;
}
declare module 'gulp/lib/taskTree.js' {
declare module.exports: $Exports<'gulp/lib/taskTree'>;
}
| {
"content_hash": "6cb19dfef16b50c76c78ed2a15d93f06",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 77,
"avg_line_length": 25.173076923076923,
"alnum_prop": 0.7081741787624141,
"repo_name": "grommet/grommet-cms-boilerplate",
"id": "ff06a9566ab017a323a279358eb8abe736392a31",
"size": "1309",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flow-typed/npm/gulp_vx.x.x.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7491"
},
{
"name": "HTML",
"bytes": "15159"
},
{
"name": "JavaScript",
"bytes": "815618"
}
],
"symlink_target": ""
} |
package org.olat.lms.search.document.file;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.poi.poifs.eventfilesystem.POIFSReader;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.util.LittleEndian;
import org.olat.data.commons.vfs.VFSLeaf;
import org.olat.lms.search.SearchResourceContext;
import org.olat.system.logging.log4j.LoggerHelper;
/**
* Lucene document mapper.
*
* @author Christian Guretzki
*/
public class PowerPointDocument extends FileDocument {
public final static String FILE_TYPE = "type.file.ppt";
private static final Logger log = LoggerHelper.getLogger();
private static final long serialVersionUID = 4569822467064358575L;
public PowerPointDocument() {
super();
}
public static Document createDocument(final SearchResourceContext leafResourceContext, final VFSLeaf leaf, final String mimeType) throws IOException,
DocumentException {
final PowerPointDocument powerPointDocument = new PowerPointDocument();
powerPointDocument.init(leafResourceContext, leaf, mimeType);
powerPointDocument.setFileType(FILE_TYPE);
powerPointDocument.setCssIcon("b_filetype_ppt");
if (log.isDebugEnabled()) {
log.debug(powerPointDocument.toString());
}
return powerPointDocument.getLuceneDocument();
}
@Override
protected boolean documentUsesTextBuffer() {
return true;
}
@Override
public String readContent(final VFSLeaf leaf) throws IOException, DocumentException {
BufferedInputStream bis = null;
OutputStream oStream = null;
if (log.isDebugEnabled()) {
log.debug("read PPT Content of leaf=" + leaf.getName());
}
try {
bis = new BufferedInputStream(leaf.getInputStream());
oStream = new ByteArrayOutputStream();
extractText(bis, oStream);
final String content = oStream.toString();
return removeUnvisibleChars(content);
} catch (final Exception e) {
throw new DocumentException("Can not read PPT Content. File=" + leaf.getName());
} finally {
if (bis != null) {
bis.close();
}
if (oStream != null) {
oStream.close();
}
}
}
/**
* Remove unvisible chars form input string.
*
* @param inputString
* @return Return filtered string
*/
private static String removeUnvisibleChars(final String inputString) {
final Pattern p = Pattern.compile("[^a-zA-Z0-9\n\r!&#<>{}]");
final Matcher m = p.matcher(inputString);
final String output = m.replaceAll(" ");
return output;
}
private static void extractText(final InputStream inStream, final OutputStream stream) throws IOException {
final POIFSReader r = new POIFSReader();
/* Register a listener for *all* documents. */
r.registerListener(new MyPOIFSReaderListener(stream));
r.read(inStream);
}
private static class MyPOIFSReaderListener implements POIFSReaderListener {
private final OutputStream oStream;
public MyPOIFSReaderListener(final OutputStream oStream) {
this.oStream = oStream;
}
@Override
public void processPOIFSReaderEvent(final POIFSReaderEvent event) {
int errorCounter = 0;
try {
DocumentInputStream dis = null;
dis = event.getStream();
final byte btoWrite[] = new byte[dis.available()];
dis.read(btoWrite, 0, dis.available());
for (int i = 0; i < btoWrite.length - 20; i++) {
final long type = LittleEndian.getUShort(btoWrite, i + 2);
final long size = LittleEndian.getUInt(btoWrite, i + 4);
if (type == 4008) {
try {
oStream.write(btoWrite, i + 4 + 1, (int) size + 3);
} catch (final IndexOutOfBoundsException ex) {
errorCounter++;
}
}
}
} catch (final Exception ex) {
// FIXME:chg: Remove general Exception later, for now make it run
log.warn("Can not read PPT content.", ex);
}
if (errorCounter > 0) {
if (log.isDebugEnabled()) {
log.debug("Could not parse ppt properly. There were " + errorCounter + " IndexOutOfBoundsException");
}
}
}
}
}
| {
"content_hash": "2a45aa64f90611142f6baa8091158d8f",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 153,
"avg_line_length": 35.236111111111114,
"alnum_prop": 0.6162790697674418,
"repo_name": "huihoo/olat",
"id": "9f931e9134ac0e1ccc10ebbd259117c50e41f480",
"size": "5870",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "olat7.8/src/main/java/org/olat/lms/search/document/file/PowerPointDocument.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "24445"
},
{
"name": "AspectJ",
"bytes": "36132"
},
{
"name": "CSS",
"bytes": "2135670"
},
{
"name": "HTML",
"bytes": "2950677"
},
{
"name": "Java",
"bytes": "50804277"
},
{
"name": "JavaScript",
"bytes": "31237972"
},
{
"name": "PLSQL",
"bytes": "64492"
},
{
"name": "Perl",
"bytes": "10717"
},
{
"name": "Shell",
"bytes": "79994"
},
{
"name": "XSLT",
"bytes": "186520"
}
],
"symlink_target": ""
} |
import { Context } from '../@types/custom';
export const skipReasons = (...args: Function[]) => {
return (ctx: Context) => {
let reason = '';
args.some((skip) => {
reason = skip(ctx);
return !!reason;
});
return reason;
};
};
export const skipInstallation = (ctx: Context) => {
const { skipInstall } = ctx.argv;
return typeof skipInstall === 'undefined' ?
'' :
'--skipInstall';
};
export const skipIfError = (ctx: Context) => {
return ctx.error ?
`Something happened: ${ctx.error.message}` :
'';
};
export const skipIfAborted = (ctx: Context) => {
return ctx.abort ?
'Process aborted' :
'';
};
const skipArgument = (argument: string) => {
return (ctx: Context) => {
return ctx.argv[argument] ?
`--${argument}` :
'';
};
};
export const skipIfForced = skipArgument('force');
export const skipIfJustRelease = skipArgument('justRelease');
| {
"content_hash": "ecbb83897da4e9b16f0fb537e80b03a8",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 61,
"avg_line_length": 21.574468085106382,
"alnum_prop": 0.5384615384615384,
"repo_name": "sonarwhal/sonar",
"id": "475e6fc05060e36cd31acefd8920b54d15507564",
"size": "1014",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "release/lib/skippers.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "507"
},
{
"name": "HTML",
"bytes": "8263"
},
{
"name": "JavaScript",
"bytes": "11468"
},
{
"name": "TypeScript",
"bytes": "620538"
}
],
"symlink_target": ""
} |
from model.group import Group
import random
from random import randrange
def test_delete_some_group(app,db,check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name="Group for delete"))
old_groups = db.get_group_list()
group=random.choice(old_groups)
id=group.id
#[TEST]
app.group.delete_group_by_id(id)
new_groups = db.get_group_list()
assert len(old_groups)-1 == len(new_groups) # хеш функция - считает количество элементов
old_groups.remove(group)
assert old_groups == new_groups
if check_ui:
assert sorted(new_groups,key=Group.id_or_max) == sorted(app.group.get_group_list(),key=Group.id_or_max)
# удаление всех групп != 0: или оставляем 3 группы > 3:
def test_del_all_group(app,db):
while app.group.count() > 0:
#app.group.delete_group_by_index(randrange(app.group.count()))
test_delete_some_group(app,db,check_ui="True") | {
"content_hash": "f4707300aa3d6d1d4600366aba1114fd",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 117,
"avg_line_length": 39.84,
"alnum_prop": 0.6255020080321285,
"repo_name": "maximencia/python_traning",
"id": "577ff55c47f6a53139401e496b64f68e25cfedc1",
"size": "1092",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_del_group.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "73712"
}
],
"symlink_target": ""
} |
package org.apache.arrow.vector.complex;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.arrow.memory.BaseAllocator;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.util.Preconditions;
import org.apache.arrow.vector.AddOrGetResult;
import org.apache.arrow.vector.BaseFixedWidthVector;
import org.apache.arrow.vector.BaseValueVector;
import org.apache.arrow.vector.BaseVariableWidthVector;
import org.apache.arrow.vector.DensityAwareVector;
import org.apache.arrow.vector.FieldVector;
import org.apache.arrow.vector.UInt4Vector;
import org.apache.arrow.vector.ValueVector;
import org.apache.arrow.vector.ZeroVector;
import org.apache.arrow.vector.types.pojo.ArrowType.ArrowTypeID;
import org.apache.arrow.vector.types.pojo.FieldType;
import org.apache.arrow.vector.util.CallBack;
import org.apache.arrow.vector.util.OversizedAllocationException;
import org.apache.arrow.vector.util.SchemaChangeRuntimeException;
import io.netty.buffer.ArrowBuf;
public abstract class BaseRepeatedValueVector extends BaseValueVector implements RepeatedValueVector {
public static final FieldVector DEFAULT_DATA_VECTOR = ZeroVector.INSTANCE;
public static final String DATA_VECTOR_NAME = "$data$";
public static final byte OFFSET_WIDTH = 4;
protected ArrowBuf offsetBuffer;
protected FieldVector vector;
protected final CallBack callBack;
protected int valueCount;
protected int offsetAllocationSizeInBytes = INITIAL_VALUE_ALLOCATION * OFFSET_WIDTH;
protected BaseRepeatedValueVector(String name, BufferAllocator allocator, CallBack callBack) {
this(name, allocator, DEFAULT_DATA_VECTOR, callBack);
}
protected BaseRepeatedValueVector(String name, BufferAllocator allocator, FieldVector vector, CallBack callBack) {
super(name, allocator);
this.offsetBuffer = allocator.getEmpty();
this.vector = Preconditions.checkNotNull(vector, "data vector cannot be null");
this.callBack = callBack;
this.valueCount = 0;
}
@Override
public boolean allocateNewSafe() {
boolean dataAlloc = false;
try {
allocateOffsetBuffer(offsetAllocationSizeInBytes);
dataAlloc = vector.allocateNewSafe();
} catch (Exception e) {
e.printStackTrace();
clear();
return false;
} finally {
if (!dataAlloc) {
clear();
}
}
return dataAlloc;
}
protected void allocateOffsetBuffer(final long size) {
final int curSize = (int) size;
offsetBuffer = allocator.buffer(curSize);
offsetBuffer.readerIndex(0);
offsetAllocationSizeInBytes = curSize;
offsetBuffer.setZero(0, offsetBuffer.capacity());
}
@Override
public void reAlloc() {
reallocOffsetBuffer();
vector.reAlloc();
}
protected void reallocOffsetBuffer() {
final int currentBufferCapacity = offsetBuffer.capacity();
long baseSize = offsetAllocationSizeInBytes;
if (baseSize < (long) currentBufferCapacity) {
baseSize = (long) currentBufferCapacity;
}
long newAllocationSize = baseSize * 2L;
newAllocationSize = BaseAllocator.nextPowerOfTwo(newAllocationSize);
assert newAllocationSize >= 1;
if (newAllocationSize > MAX_ALLOCATION_SIZE) {
throw new OversizedAllocationException("Unable to expand the buffer");
}
final ArrowBuf newBuf = allocator.buffer((int) newAllocationSize);
newBuf.setBytes(0, offsetBuffer, 0, currentBufferCapacity);
newBuf.setZero(currentBufferCapacity, newBuf.capacity() - currentBufferCapacity);
offsetBuffer.release(1);
offsetBuffer = newBuf;
offsetAllocationSizeInBytes = (int) newAllocationSize;
}
@Override
@Deprecated
public UInt4Vector getOffsetVector() {
throw new UnsupportedOperationException("There is no inner offset vector");
}
@Override
public FieldVector getDataVector() {
return vector;
}
@Override
public void setInitialCapacity(int numRecords) {
offsetAllocationSizeInBytes = (numRecords + 1) * OFFSET_WIDTH;
if (vector instanceof BaseFixedWidthVector || vector instanceof BaseVariableWidthVector) {
vector.setInitialCapacity(numRecords * RepeatedValueVector.DEFAULT_REPEAT_PER_RECORD);
} else {
vector.setInitialCapacity(numRecords);
}
}
/**
* Specialized version of setInitialCapacity() for ListVector. This is
* used by some callers when they want to explicitly control and be
* conservative about memory allocated for inner data vector. This is
* very useful when we are working with memory constraints for a query
* and have a fixed amount of memory reserved for the record batch. In
* such cases, we are likely to face OOM or related problems when
* we reserve memory for a record batch with value count x and
* do setInitialCapacity(x) such that each vector allocates only
* what is necessary and not the default amount but the multiplier
* forces the memory requirement to go beyond what was needed.
*
* @param numRecords value count
* @param density density of ListVector. Density is the average size of
* list per position in the List vector. For example, a
* density value of 10 implies each position in the list
* vector has a list of 10 values.
* A density value of 0.1 implies out of 10 positions in
* the list vector, 1 position has a list of size 1 and
* remaining positions are null (no lists) or empty lists.
* This helps in tightly controlling the memory we provision
* for inner data vector.
*/
@Override
public void setInitialCapacity(int numRecords, double density) {
if ((numRecords * density) >= Integer.MAX_VALUE) {
throw new OversizedAllocationException("Requested amount of memory is more than max allowed");
}
offsetAllocationSizeInBytes = (numRecords + 1) * OFFSET_WIDTH;
int innerValueCapacity = Math.max((int)(numRecords * density), 1);
if (vector instanceof DensityAwareVector) {
((DensityAwareVector)vector).setInitialCapacity(innerValueCapacity, density);
} else {
vector.setInitialCapacity(innerValueCapacity);
}
}
@Override
public int getValueCapacity() {
final int offsetValueCapacity = Math.max(getOffsetBufferValueCapacity() - 1, 0);
if (vector == DEFAULT_DATA_VECTOR) {
return offsetValueCapacity;
}
return Math.min(vector.getValueCapacity(), offsetValueCapacity);
}
protected int getOffsetBufferValueCapacity() {
return (int) ((offsetBuffer.capacity() * 1.0) / OFFSET_WIDTH);
}
@Override
public int getBufferSize() {
if (getValueCount() == 0) {
return 0;
}
return ((valueCount + 1) * OFFSET_WIDTH) + vector.getBufferSize();
}
@Override
public int getBufferSizeFor(int valueCount) {
if (valueCount == 0) {
return 0;
}
return ((valueCount + 1) * OFFSET_WIDTH) + vector.getBufferSizeFor(valueCount);
}
@Override
public Iterator<ValueVector> iterator() {
return Collections.<ValueVector>singleton(getDataVector()).iterator();
}
@Override
public void clear() {
offsetBuffer = releaseBuffer(offsetBuffer);
vector.clear();
valueCount = 0;
super.clear();
}
@Override
public void reset() {
offsetBuffer.setZero(0, offsetBuffer.capacity());
vector.reset();
valueCount = 0;
}
@Override
public ArrowBuf[] getBuffers(boolean clear) {
final ArrowBuf[] buffers;
if (getBufferSize() == 0) {
buffers = new ArrowBuf[0];
} else {
List<ArrowBuf> list = new ArrayList<>();
list.add(offsetBuffer);
list.addAll(Arrays.asList(vector.getBuffers(false)));
buffers = list.toArray(new ArrowBuf[list.size()]);
}
if (clear) {
for (ArrowBuf buffer : buffers) {
buffer.retain();
}
clear();
}
return buffers;
}
/**
* Get value indicating if inner vector is set.
* @return 1 if inner vector is explicitly set via #addOrGetVector else 0
*/
public int size() {
return vector == DEFAULT_DATA_VECTOR ? 0 : 1;
}
public <T extends ValueVector> AddOrGetResult<T> addOrGetVector(FieldType fieldType) {
boolean created = false;
if (vector instanceof ZeroVector) {
vector = fieldType.createNewSingleVector(DATA_VECTOR_NAME, allocator, callBack);
// returned vector must have the same field
created = true;
if (callBack != null &&
// not a schema change if changing from ZeroVector to ZeroVector
(fieldType.getType().getTypeID() != ArrowTypeID.Null)) {
callBack.doWork();
}
}
if (vector.getField().getType().getTypeID() != fieldType.getType().getTypeID()) {
final String msg = String.format("Inner vector type mismatch. Requested type: [%s], actual type: [%s]",
fieldType.getType().getTypeID(), vector.getField().getType().getTypeID());
throw new SchemaChangeRuntimeException(msg);
}
return new AddOrGetResult<>((T) vector, created);
}
protected void replaceDataVector(FieldVector v) {
vector.clear();
vector = v;
}
@Override
public int getValueCount() {
return valueCount;
}
/* returns the value count for inner data vector for this list vector */
public int getInnerValueCount() {
return vector.getValueCount();
}
/* returns the value count for inner data vector at a particular index */
public int getInnerValueCountAt(int index) {
return offsetBuffer.getInt((index + 1) * OFFSET_WIDTH) -
offsetBuffer.getInt(index * OFFSET_WIDTH);
}
public boolean isNull(int index) {
return false;
}
public boolean isEmpty(int index) {
return false;
}
public int startNewValue(int index) {
while (index >= getOffsetBufferValueCapacity()) {
reallocOffsetBuffer();
}
int offset = offsetBuffer.getInt(index * OFFSET_WIDTH);
offsetBuffer.setInt((index + 1) * OFFSET_WIDTH, offset);
setValueCount(index + 1);
return offset;
}
public void setValueCount(int valueCount) {
this.valueCount = valueCount;
while (valueCount > getOffsetBufferValueCapacity()) {
reallocOffsetBuffer();
}
final int childValueCount = valueCount == 0 ? 0 :
offsetBuffer.getInt(valueCount * OFFSET_WIDTH);
vector.setValueCount(childValueCount);
}
}
| {
"content_hash": "c6f0c5518bf0d24c71b7bcab2d0f3a09",
"timestamp": "",
"source": "github",
"line_count": 322,
"max_line_length": 116,
"avg_line_length": 32.48136645962733,
"alnum_prop": 0.7000669280045894,
"repo_name": "itaiin/arrow",
"id": "4c61dfb493cf97ca81de86665858140d22558902",
"size": "11259",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "java/vector/src/main/java/org/apache/arrow/vector/complex/BaseRepeatedValueVector.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "73655"
},
{
"name": "Awk",
"bytes": "3683"
},
{
"name": "Batchfile",
"bytes": "31917"
},
{
"name": "C",
"bytes": "328104"
},
{
"name": "C#",
"bytes": "399342"
},
{
"name": "C++",
"bytes": "7227843"
},
{
"name": "CMake",
"bytes": "401580"
},
{
"name": "CSS",
"bytes": "3946"
},
{
"name": "Dockerfile",
"bytes": "42193"
},
{
"name": "FreeMarker",
"bytes": "2274"
},
{
"name": "Go",
"bytes": "364102"
},
{
"name": "HTML",
"bytes": "23047"
},
{
"name": "Java",
"bytes": "2296962"
},
{
"name": "JavaScript",
"bytes": "84850"
},
{
"name": "Lua",
"bytes": "8741"
},
{
"name": "M4",
"bytes": "8713"
},
{
"name": "MATLAB",
"bytes": "9068"
},
{
"name": "Makefile",
"bytes": "44853"
},
{
"name": "Meson",
"bytes": "36931"
},
{
"name": "Objective-C",
"bytes": "7559"
},
{
"name": "PLpgSQL",
"bytes": "56995"
},
{
"name": "Perl",
"bytes": "3799"
},
{
"name": "Python",
"bytes": "1548321"
},
{
"name": "R",
"bytes": "155922"
},
{
"name": "Ruby",
"bytes": "679269"
},
{
"name": "Rust",
"bytes": "1592353"
},
{
"name": "Shell",
"bytes": "251833"
},
{
"name": "Thrift",
"bytes": "137291"
},
{
"name": "TypeScript",
"bytes": "932690"
}
],
"symlink_target": ""
} |
package com.team254.lib.util;
/**
* This class holds a bunch of static methods and variables needed for
* mathematics
*/
public class ChezyMath {
/**
* Get the difference in angle between two angles.
*
* @param from The first angle
* @param to The second angle
* @return The change in angle from the first argument necessary to line up
* with the second. Always between -Pi and Pi
*/
public static double getDifferenceInAngleRadians(double from, double to) {
return boundAngleNegPiToPiRadians(to - from);
}
/**
* Get the difference in angle between two angles.
*
* @param from The first angle
* @param to The second angle
* @return The change in angle from the first argument necessary to line up
* with the second. Always between -180 and 180
*/
public static double getDifferenceInAngleDegrees(double from, double to) {
return boundAngleNeg180to180Degrees(to - from);
}
public static double boundAngle0to360Degrees(double angle) {
// Naive algorithm
while (angle >= 360.0) {
angle -= 360.0;
}
while (angle < 0.0) {
angle += 360.0;
}
return angle;
}
public static double boundAngleNeg180to180Degrees(double angle) {
// Naive algorithm
while (angle >= 180.0) {
angle -= 360.0;
}
while (angle < -180.0) {
angle += 360.0;
}
return angle;
}
public static double boundAngle0to2PiRadians(double angle) {
// Naive algorithm
while (angle >= 2.0 * Math.PI) {
angle -= 2.0 * Math.PI;
}
while (angle < 0.0) {
angle += 2.0 * Math.PI;
}
return angle;
}
public static double boundAngleNegPiToPiRadians(double angle) {
// Naive algorithm
while (angle >= Math.PI) {
angle -= 2.0 * Math.PI;
}
while (angle < -Math.PI) {
angle += 2.0 * Math.PI;
}
return angle;
}
public ChezyMath() {
}
}
| {
"content_hash": "805f0cf627285996b89c5f80759afce6",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 79,
"avg_line_length": 27.21794871794872,
"alnum_prop": 0.5652378709373528,
"repo_name": "Team254/FRC-2015",
"id": "4bc5655eb1ae415a94e4f5aa019f8a949706d457",
"size": "2123",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/team254/lib/util/ChezyMath.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "525"
},
{
"name": "HTML",
"bytes": "6523"
},
{
"name": "Java",
"bytes": "237152"
},
{
"name": "JavaScript",
"bytes": "259672"
},
{
"name": "Shell",
"bytes": "81"
}
],
"symlink_target": ""
} |
package com.learning.designpattern.structural.filter;
import java.util.ArrayList;
import java.util.List;
public class CriteriaMale implements Criteria {
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> malePersons = new ArrayList<Person>();
for(Person person:persons){
if("MALE".equalsIgnoreCase(person.getGender())){
malePersons.add(person);
}
}
return malePersons;
}
}
| {
"content_hash": "03af971455414be6d6e3c3aaaf1d038c",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 57,
"avg_line_length": 20.61904761904762,
"alnum_prop": 0.7321016166281755,
"repo_name": "mandheer/learnjava",
"id": "49a13ff3dc611a376d6cbbdcbe5569d8bd9adee0",
"size": "433",
"binary": false,
"copies": "1",
"ref": "refs/heads/WorkBranch",
"path": "learn/tutorial/designpatterns/src/test/java/com/learning/designpattern/structural/filter/CriteriaMale.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "219771"
}
],
"symlink_target": ""
} |
Changelog
=========
Next Version
------------
2.5.0 (2019-10-30)
------------------
* Support ``fromJSON`` classmethod for all Munch subclasses (PR [#55](https://github.com/Infinidat/munch/pull/55))
* Fix return value of DefaultMunch and DefaultFactoryMunch's get method (fixes [#53](https://github.com/Infinidat/munch/issues/53))
* Support ``fromYAML`` classmethod for all Munch subclasses (PR [#52](https://github.com/Infinidat/munch/pull/52) fixes [#34](https://github.com/Infinidat/munch/issues/34)
2.4.0 (2019-10-29)
------------------
* Remove usage of deprecated API: Add default loader to yaml loads (PR [#51](https://github.com/Infinidat/munch/pull/51))
* Switch to PBR #49 (PR [#49](https://github.com/Infinidat/munch/pull/49))
* Add constructors to all PyYAML loaders (PR [#47](https://github.com/Infinidat/munch/pull/47))
* Fix namedtuple handling (PR [#46](https://github.com/Infinidat/munch/pull/46) - thanks @atleta)
* Correctly handle object cycles in munchify and unmunchify (PR [#41](https://github.com/Infinidat/munch/pull/41) - thanks @airbornemint)
* Improve subclassing behavior (PR [#38](https://github.com/Infinidat/munch/pull/38) - thanks @JosePVB)
2.3.2 (2018-05-06)
------------------
* Limit travis deployment conditions
* Build python wheels (PR [#32](https://github.com/Infinidat/munch/pull/32) - thanks @pabelanger)
2.3.1 (2018-04-11)
------------------
* Avoid running yaml tests when in no-deps environment
* Use flat dicts in ``__getstate__`` (closes [#32](https://github.com/Infinidat/munch/issues/30) - thanks @harlowja)
2.3.0 (2018-04-09)
------------------
* Remove default from constructor and fromDict, Make DefaultFactoryMunch which lets users provide a factory to generate missing values (PR [#28](https://github.com/Infinidat/munch/pull/28) - thanks @ekuecks)
* ``__setattr__`` will now ``munchify()`` any provided dict (PR [#27](https://github.com/Infinidat/munch/pulls/27) - thanks @kbni)
* Implement the pickling interface (PR [#23](https://github.com/Infinidat/munch/pulls/23) & [#25](https://github.com/Infinidat/munch/pulls/25) - thanks @JamshedVesuna)
* Drop support for Python 2.6, 3.3, 3.4
* Add ``__dict__`` property that calls ``toDict()`` (PR [#20](https://github.com/Infinidat/munch/pulls/20) - thanks @bobh66)
2.2.0 (2017-07-27)
------------------
* Fix for Python 2.6: str.format must field names
* Changed ``__repr__`` to use str.format instead of x % y
* Added DefaultMunch, which returns a special value for missing attributes (PR [#16](https://github.com/Infinidat/munch/pulls/16) - thanks @z0u)
2.1.1 (2017-03-20)
------------------
* Fix python 3 compatibility to work with IronPython (fixes [#13](https://github.com/Infinidat/munch/issues/13) - thanks @yiyuan1840)
* Deploy from Travis
* Add python 3.6
2.1.0 (2017-01-10)
------------------
* Implement copy method (fixes [#10](https://github.com/Infinidat/munch/issues/10))
* Fix ``__contains__`` returning True for Munch’s default attributes (PR [#7](https://github.com/Infinidat/munch/pull/7) - thanks @jmagnusson)
2.0.4 (2015-11-03)
------------------
* Fixed String representation of objects with keys that have spaces (PR [#4](https://github.com/Infinidat/munch/pull/4))
2.0.3 (2015-10-02)
------------------
* Python 3.5 support
* Test against Python 3.4
* Add support for running ``dir()`` on munches
2.0.2 (2014-01-16)
------------------
* Fix packaging manifest
2.0.1 (2014-01-16)
------------------
* Rename to Munch
* Fix Py3 compatibility check
* Drop Python 3.2 support, add 3.3
2.0.0 (2014-01-16)
------------------
* Initial release: Forking bunch --> infi.bunch.
| {
"content_hash": "134a57a761b7dd5cd648f9e2aa028990",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 207,
"avg_line_length": 39.369565217391305,
"alnum_prop": 0.6637217007178354,
"repo_name": "Infinidat/munch",
"id": "c918f17805ca4722ffcfb1722b4bbb67fdb6ca9c",
"size": "3624",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "410"
},
{
"name": "Python",
"bytes": "41954"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace makeDigest
{
public partial class Form1 : Form
{
private static readonly string passwordChars = "0123456789abcdefghijklmnopqrstuvwxyz";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var a1 = textBox1.Text;
var nonce = textBox2.Text;
var nc = textBox3.Text;
var cnonce = textBox4.Text;
var qop = textBox5.Text;
var a2 = textBox6.Text;
var response = GetMD5(a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + a2);
textBox8.Text = response;
textBox7.Text = "Authorization: Digest username=\"" + userNameBox.Text + "\", realm=\"" + realmBox.Text + "\", nonce=\"" + nonce + "\", uri=\"" + urlBox.Text + "\", algorithm=MD5, response=\"" + response + "\", qop=\"" + textBox5.Text + "\", nc=" + textBox3.Text + ", cnonce=\"" + cnonce + "\"";
}
private string GetMD5(string str)
{
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
var data = Encoding.UTF8.GetBytes(str);
var bs = md5.ComputeHash(data);
md5.Clear();
string result = BitConverter.ToString(bs).ToLower().Replace("-","");
return result;
}
private void button2_Click(object sender, EventArgs e)
{
Dive("", 13, respBox.Text);
}
private void button3_Click(object sender, EventArgs e)
{
textBox4.Text = GeneratePassword(8);
}
public string GeneratePassword(int length)
{
StringBuilder sb = new StringBuilder(length);
Random r = new Random();
for (int i = 0; i < length; i++)
{
int pos = r.Next(passwordChars.Length);
char c = passwordChars[pos];
sb.Append(c);
}
return sb.ToString();
}
private void button4_Click(object sender, EventArgs e)
{
textBox1.Text = GetMD5(userNameBox.Text + ":" + realmBox.Text + ":" + passwordBox.Text);
}
private void button5_Click(object sender, EventArgs e)
{
textBox6.Text = GetMD5(((string)(comboBox1.SelectedItem)) + ":" + urlBox.Text);
}
//よくない
int maxlength = 14;
string ValidChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,|+_-=\\][{}';\":/.,<>?!@#$%^&*()";
private void Attack(string targetresp)
{
int level = 1;
string prefix = "";
var user = userNameBox.Text;
var realm = realmBox.Text;
var nonce = textBox2.Text;
var nc = textBox3.Text;
var cnonce = textBox4.Text;
var qop = textBox5.Text;
var a2 = GetMD5(((string)(comboBox1.SelectedItem)) + ":" + urlBox.Text);
while (level <= 12)
{
foreach (char c in ValidChars)
{
prefix += c;
var a1 = GetMD5(user + ":" + realm + ":" + prefix);
var response = GetMD5(a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + a2);
if (level < maxlength)
{
//Dive(prefix + c, level);
}
}
}
}
private void Dive(string prefix, int level, string targetresp)
{
var user = userNameBox.Text;
var realm = realmBox.Text;
var nonce = textBox2.Text;
var nc = textBox3.Text;
var cnonce = textBox4.Text;
var qop = textBox5.Text;
var a2 = GetMD5(((string)(comboBox1.SelectedItem)) + ":" + urlBox.Text);
level += 1;
foreach (char c in ValidChars)
{
var a1 = GetMD5(user + ":" + realm + ":" + prefix);
var response = GetMD5(a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + a2);
if (targetresp == response)
break;
if (level < maxlength)
{
Dive(prefix + c, level, targetresp);
}
}
}
}
}
| {
"content_hash": "c3ceacbd8f3ca6bdc03d1bf07f54d74a",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 298,
"avg_line_length": 29.528985507246375,
"alnum_prop": 0.5673619631901841,
"repo_name": "misodengaku/makeDigest",
"id": "0504cddc65803884d12ec69da59b14541a1e6900",
"size": "4085",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "makeDigest/Form1.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "6253"
}
],
"symlink_target": ""
} |
from __future__ import print_function
import pymysql
import re
err = pymysql.err
cursors = pymysql.cursors
class DictMySQL:
def __init__(self, host, user, passwd, db=None, port=3306, charset='utf8', init_command='SET NAMES UTF8',
cursorclass=cursors.Cursor, use_unicode=True, autocommit=False):
self.host = host
self.port = int(port)
self.user = user
self.passwd = passwd
self.db = db
self.cursorclass = cursorclass
self.charset = charset
self.init_command = init_command
self.use_unicode = use_unicode
self.autocommit_mode = bool(autocommit)
self.connection = self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user,
passwd=self.passwd, db=self.db, charset=charset,
init_command=init_command, cursorclass=self.cursorclass,
use_unicode=self.use_unicode, autocommit=self.autocommit_mode)
self.cursor = self.cur = self.conn.cursor()
self.debug = False
def reconnect(self):
self.connection = self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user,
passwd=self.passwd, db=self.db, cursorclass=self.cursorclass,
charset=self.charset, init_command=self.init_command,
use_unicode=self.use_unicode, autocommit=self.autocommit_mode)
self.cursor = self.cur = self.conn.cursor()
return True
def query(self, sql, args=None):
"""
:param sql: string. SQL query.
:param args: tuple. Arguments of this query.
"""
return self.cur.execute(sql, args)
@staticmethod
def _backtick_columns(cols):
"""
Quote the column names
"""
def bt(s):
b = '' if s == '*' or not s else '`'
return [_ for _ in [b + (s or '') + b] if _]
formatted = []
for c in cols:
if c[0] == '#':
formatted.append(c[1:])
elif c.startswith('(') and c.endswith(')'):
# WHERE (column_a, column_b) IN ((1,10), (1,20))
formatted.append(c)
else:
# backtick the former part when it meets the first dot, and then all the rest
formatted.append('.'.join(bt(c.split('.')[0]) + bt('.'.join(c.split('.')[1:]))))
return ', '.join(formatted)
def _backtick(self, value):
return self._backtick_columns((value,))
@staticmethod
def _whitespace_decorator(s, p=True, n=False):
return ''.join((' ' if p else '', s, ' ' if n else ''))
def _tablename_parser(self, table):
result = re.match('^(\[(|>|<|<>|><)\])??(\w+)(\((|\w+)\))??$', table.replace(' ', ''))
join_type = ''
alias = ''
formatted_tablename = self._backtick(table)
if result:
alias = result.group(5) if result.group(5) else ''
tablename = result.group(3)
formatted_tablename = ' '.join([self._backtick(tablename),
'AS', self._backtick(alias)]) if alias else self._backtick(tablename)
join_type = {'>': 'LEFT', '<': 'RIGHT', '<>': 'FULL', '><': 'INNER'}.get(result.group(2), '')
else:
tablename = table
return {'join_type': join_type,
'tablename': tablename,
'alias': alias,
'formatted_tablename': formatted_tablename}
def _value_parser(self, value, columnname=False, placeholder='%s'):
"""
Input: {'c1': 'v', 'c2': None, '#c3': 'uuid()'}
Output:
('%s, %s, uuid()', [None, 'v']) # insert; columnname=False
('`c2` = %s, `c1` = %s, `c3` = uuid()', [None, 'v']) # update; columnname=True
No need to transform NULL value since it's supported in execute()
"""
if not isinstance(value, dict):
raise TypeError('Input value should be a dictionary')
q = []
a = []
for k, v in value.items():
if k[0] == '#': # if is sql function
q.append(' = '.join([self._backtick(k[1:]), str(v)]) if columnname else v)
else:
q.append(' = '.join([self._backtick(k), placeholder]) if columnname else placeholder)
a.append(v)
return ', '.join(q), tuple(a)
def _join_parser(self, join):
if not join:
return ''
# JOIN only supports <, <=, >, >=, <> and =
_operators = {
'$=': '=',
'$EQ': '=',
'$<': '<',
'$LT': '<',
'$>': '>',
'$GT': '>',
'$<=': '<=',
'$LTE': '<=',
'$>=': '>=',
'$GTE': '>=',
'$<>': '<>',
'$NE': '<>',
}
join_query = ''
for j_table, j_on in join.items():
join_table = self._tablename_parser(j_table)
joins = []
for left_column, join_right_column in j_on.items():
# {'left_table': {'$<>': 'right_table', }, }
if isinstance(join_right_column, dict):
join_right_tables = []
for join_method, right_column in join_right_column.items():
j_symbol = _operators[join_method.upper()]
join_right_tables.append(j_symbol.join([self._backtick(left_column),
self._backtick(right_column)]))
joins.append(' AND '.join(join_right_tables))
# {'left_table': 'right_table', }
else:
joins.append('='.join([self._backtick(left_column), self._backtick(join_right_column)]))
join_query += ''.join([(' ' + join_table['join_type']) if join_table['join_type'] else '',
' JOIN ',
join_table['formatted_tablename'],
' ON ',
' AND '.join(joins)])
return join_query
def _where_parser(self, where, placeholder='%s'):
if not where:
return '', ()
result = {'q': [], 'v': ()}
_operators = {
'$=': '=',
'$EQ': '=',
'$<': '<',
'$LT': '<',
'$>': '>',
'$GT': '>',
'$<=': '<=',
'$LTE': '<=',
'$>=': '>=',
'$GTE': '>=',
'$<>': '<>',
'$NE': '<>',
'$LIKE': 'LIKE',
'$BETWEEN': 'BETWEEN',
'$IN': 'IN'
}
_connectors = {
'$AND': 'AND',
'$OR': 'OR'
}
negative_symbol = {
'=': '<>',
'<': '>=',
'>': '<=',
'<=': '>',
'>=': '<',
'<>': '=',
'LIKE': 'NOT LIKE',
'BETWEEN': 'NOT BETWEEN',
'IN': 'NOT IN',
'AND': 'OR',
'OR': 'AND'
}
# TODO: confirm datetime support for more operators
# TODO: LIKE Wildcard support
def _get_connector(c, is_not, whitespace=False):
c = c or '='
c = negative_symbol.get(c) if is_not else c
return ' ' + c + ' ' if whitespace else c
placeholder = '%s'
def _combining(_cond, _operator=None, upper_key=None, connector=None, _not=False):
if isinstance(_cond, dict):
i = 1
for k, v in _cond.items():
# {'$AND':{'value':10}}
if k.upper() in _connectors:
result['q'].append('(')
_combining(v, upper_key=upper_key, _operator=_operator, connector=_connectors[k.upper()], _not=_not)
result['q'].append(')')
# {'>':{'value':10}}
elif k.upper() in _operators:
_combining(v, _operator=_operators[k.upper()], upper_key=upper_key, connector=connector, _not=_not)
# {'$NOT':{'value':10}}
elif k.upper() == '$NOT':
_combining(v, upper_key=upper_key, _operator=_operator, connector=connector, _not=not _not)
# {'value':10}
else:
_combining(v, upper_key=k, _operator=_operator, connector=connector, _not=_not)
# append 'AND' by default except for the last one
if i < len(_cond):
result['q'].append(_get_connector('AND', is_not=_not, whitespace=True))
i += 1
elif isinstance(_cond, list):
# [{'age': {'$>': 22}}, {'amount': {'$<': 100}}]
if all(isinstance(c, dict) for c in _cond):
l_index = 1
for l in _cond:
_combining(l, _operator=_operator, upper_key=upper_key, connector=connector, _not=_not)
if l_index < len(_cond):
result['q'].append(_get_connector(connector, is_not=_not, whitespace=True))
l_index += 1
elif _operator in ['=', 'IN'] or not _operator:
s_q = self._backtick(upper_key) + (' NOT' if _not else '') + ' IN (' + ', '.join(['%s']*len(_cond)) + ')'
result['q'].append('(' + s_q + ')')
result['v'] += tuple(_cond)
elif _operator == 'BETWEEN':
s_q = self._backtick(upper_key) + (' NOT' if _not else '') + ' BETWEEN ' + ' AND '.join(['%s']*len(_cond))
result['q'].append('(' + s_q + ')')
result['v'] += tuple(_cond)
elif _operator == 'LIKE':
s_q = ' OR '.join(['(' + self._backtick(upper_key) + (' NOT' if _not else '') + ' LIKE %s)'] * len(_cond))
result['q'].append('(' + s_q + ')')
result['v'] += tuple(_cond)
# if keyword not in prefilled list but value is not dict also, should return error
elif _cond is None:
s_q = self._backtick(upper_key) + ' IS' + (' NOT' if _not else '') + ' NULL'
result['q'].append('(' + s_q + ')')
else:
if upper_key[0] == '#':
item_value = _cond
upper_key = upper_key[1:] # for functions, remove the # symbol and no need to quote the value
else:
item_value = placeholder
result['v'] += (_cond,)
s_q = ' '.join([self._backtick(upper_key), _get_connector(_operator, is_not=_not), item_value])
result['q'].append('(' + s_q + ')')
_combining(where)
return ' WHERE ' + ''.join(result['q']), result['v']
@staticmethod
def _limit_parser(limit=None):
if isinstance(limit, list) and len(limit) == 2:
return ' '.join((' LIMIT', ', '.join(str(l) for l in limit)))
elif str(limit).isdigit():
return ' '.join((' LIMIT', str(limit)))
else:
return ''
def _yield_result(self):
while True:
result = self.cur.fetchone()
if not result:
break
yield result
@staticmethod
def isstr(s):
try:
return isinstance(s, basestring) # Python 2 string
except NameError:
return isinstance(s, str) # Python 3 string
def _by_columns(self, columns):
"""
Allow select.group and select.order accepting string and list
"""
return columns if self.isstr(columns) else self._backtick_columns(columns)
def select(self, table, columns=None, join=None, where=None, group=None, having=None, order=None, limit=None,
iterator=False, fetch=True):
"""
:type table: string
:type columns: list
:type join: dict
:param join: {'[>]table1(t1)': {'user.id': 't1.user_id'}} -> "LEFT JOIN table AS t1 ON user.id = t1.user_id"
:type where: dict
:type group: string|list
:type having: string
:type order: string|list
:type limit: int|list
# TODO: change to offset
:param limit: The max row number for this query.
If it contains offset, limit must be a list like [offset, limit]
:param iterator: Whether to output the result in a generator. It always returns generator if the cursor is
SSCursor or SSDictCursor, no matter iterator is True or False.
:type fetch: bool
"""
if not columns:
columns = ['*']
where_q, _args = self._where_parser(where)
# TODO: support multiple table
_sql = ''.join(['SELECT ', self._backtick_columns(columns),
' FROM ', self._tablename_parser(table)['formatted_tablename'],
self._join_parser(join),
where_q,
(' GROUP BY ' + self._by_columns(group)) if group else '',
(' HAVING ' + having) if having else '',
(' ORDER BY ' + self._by_columns(order)) if order else '',
self._limit_parser(limit), ';'])
if self.debug:
return self.cur.mogrify(_sql, _args)
execute_result = self.cur.execute(_sql, _args)
if not fetch:
return execute_result
if self.cursorclass in (pymysql.cursors.SSCursor, pymysql.cursors.SSDictCursor):
return self.cur
if iterator:
return self._yield_result()
return self.cur.fetchall()
def select_page(self, limit, offset=0, **kwargs):
"""
:type limit: int
:param limit: The max row number for each page
:type offset: int
:param offset: The starting position of the page
:return:
"""
start = offset
while True:
result = self.select(limit=[start, limit], **kwargs)
start += limit
if result:
yield result
else:
break
if self.debug:
break
def get(self, table, column, join=None, where=None, insert=False, ifnone=None):
"""
A simplified method of select, for getting the first result in one column only. A common case of using this
method is getting id.
:type table: string
:type column: str
:type join: dict
:type where: dict
:type insert: bool
:param insert: If insert==True, insert the input condition if there's no result and return the id of new row.
:type ifnone: string
:param ifnone: When ifnone is a non-empty string, raise an error if query returns empty result. insert parameter
would not work in this mode.
"""
select_result = self.select(table=table, columns=[column], join=join, where=where, limit=1)
if self.debug:
return select_result
result = select_result[0] if select_result else None
if result:
return result[0 if self.cursorclass is pymysql.cursors.Cursor else column]
if ifnone:
raise ValueError(ifnone)
if insert:
if any([isinstance(d, dict) for d in where.values()]):
raise ValueError("The where parameter in get() doesn't support nested condition with insert==True.")
return self.insert(table=table, value=where)
return None
def insert(self, table, value, ignore=False, commit=True):
"""
Insert a dict into db.
:type table: string
:type value: dict
:type ignore: bool
:type commit: bool
:return: int. The row id of the insert.
"""
value_q, _args = self._value_parser(value, columnname=False)
_sql = ''.join(['INSERT', ' IGNORE' if ignore else '', ' INTO ', self._backtick(table),
' (', self._backtick_columns(value), ') VALUES (', value_q, ');'])
if self.debug:
return self.cur.mogrify(_sql, _args)
self.cur.execute(_sql, _args)
if commit:
self.conn.commit()
return self.cur.lastrowid
def upsert(self, table, value, update_columns=None, commit=True):
"""
:type table: string
:type value: dict
:type update_columns: list
:param update_columns: specify the columns which will be updated if record exists
:type commit: bool
"""
if not isinstance(value, dict):
raise TypeError('Input value should be a dictionary')
if not update_columns:
update_columns = value.keys()
value_q, _args = self._value_parser(value, columnname=False)
_sql = ''.join(['INSERT INTO ', self._backtick(table), ' (', self._backtick_columns(value), ') VALUES ',
'(', value_q, ') ',
'ON DUPLICATE KEY UPDATE ',
', '.join(['='.join([k, 'VALUES('+k+')']) for k in update_columns]), ';'])
if self.debug:
return self.cur.mogrify(_sql, _args)
self.cur.execute(_sql, _args)
if commit:
self.conn.commit()
return self.cur.lastrowid
def insertmany(self, table, columns, value, ignore=False, commit=True):
"""
Insert multiple records within one query.
:type table: string
:type columns: list
:type value: list|tuple
:param value: Doesn't support MySQL functions
:param value: Example: [(value1_column1, value1_column2,), ]
:type ignore: bool
:type commit: bool
:return: int. The row id of the LAST insert only.
"""
if not isinstance(value, (list, tuple)):
raise TypeError('Input value should be a list or tuple')
# Cannot add semicolon here, otherwise it will not pass the Cursor.executemany validation
_sql = ''.join(['INSERT', ' IGNORE' if ignore else '', ' INTO ', self._backtick(table),
' (', self._backtick_columns(columns), ') VALUES (', ', '.join(['%s'] * len(columns)), ')'])
_args = tuple(value)
# For insertmany, the base queries for executemany and printing are different
_sql_full = ''.join(['INSERT', ' IGNORE' if ignore else '', ' INTO ', self._backtick(table),
' (', self._backtick_columns(columns), ') VALUES ',
', '.join([''.join(['(', ', '.join(['%s'] * len(columns)), ')'])] * len(_args)),
';'])
_args_flattened = [item for sublist in _args for item in sublist]
if self.debug:
return self.cur.mogrify(_sql_full, _args_flattened)
self.cur.executemany(_sql, _args)
if commit:
self.conn.commit()
return self.cur.lastrowid
def update(self, table, value, where, join=None, commit=True):
"""
:type table: string
:type value: dict
:type where: dict
:type join: dict
:type commit: bool
"""
value_q, _value_args = self._value_parser(value, columnname=True)
where_q, _where_args = self._where_parser(where)
_sql = ''.join(['UPDATE ', self._tablename_parser(table)['formatted_tablename'],
self._join_parser(join),
' SET ', value_q, where_q, ';'])
_args = _value_args + _where_args
if self.debug:
return self.cur.mogrify(_sql, _args)
result = self.cur.execute(_sql, _args)
if commit:
self.commit()
return result
def delete(self, table, where=None, commit=True):
"""
:type table: string
:type where: dict
:type commit: bool
"""
where_q, _args = self._where_parser(where)
alias = self._tablename_parser(table)['alias']
_sql = ''.join(['DELETE ',
alias + ' ' if alias else '',
'FROM ', self._tablename_parser(table)['formatted_tablename'], where_q, ';'])
if self.debug:
return self.cur.mogrify(_sql, _args)
result = self.cur.execute(_sql, _args)
if commit:
self.commit()
return result
def column_name(self, table):
_sql = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`=%s AND `TABLE_NAME`=%s;"
_args = (self.db, table)
self.cur.execute(_sql, _args)
return self.cur.fetchall()
def table_name(self):
_sql = "SELECT `table_name` FROM `INFORMATION_SCHEMA`.`TABLES` where `TABLE_SCHEMA`=%s;"
_args = (self.db,)
self.cur.execute(_sql, _args)
return self.cur.fetchall()
def now(self):
query = "SELECT NOW() AS now;"
if self.debug:
return query
self.cur.execute(query)
return self.cur.fetchone()[0 if self.cursorclass is pymysql.cursors.Cursor else 'now'].strftime(
"%Y-%m-%d %H:%M:%S")
def last_insert_id(self):
query = "SELECT LAST_INSERT_ID() AS lid;"
if self.debug:
return query
self.query(query)
return self.cur.fetchone()[0 if self.cursorclass is pymysql.cursors.Cursor else 'lid']
def fetchone(self):
return self.cur.fetchone()
def fetchall(self):
return self.cur.fetchall()
def fetchmany(self, size=None):
return self.cur.fetchmany(size=size)
def lastrowid(self):
return self.cur.lastrowid
def rowcount(self):
return self.cur.rowcount
def commit(self):
self.conn.commit()
def rollback(self):
self.conn.rollback()
def __del__(self):
try:
self.cur.close()
self.conn.close()
except:
pass
def close(self):
self.cur.close()
self.conn.close()
| {
"content_hash": "0ede85f651a1335f2d624bbac75c2c30",
"timestamp": "",
"source": "github",
"line_count": 600,
"max_line_length": 126,
"avg_line_length": 37.58833333333333,
"alnum_prop": 0.4876069702478606,
"repo_name": "ligyxy/DictMySQL",
"id": "ba866c6b65be2bcbb0c3785e8fc1053eae4252cf",
"size": "22595",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dictmysql.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "25441"
}
],
"symlink_target": ""
} |
A Pure-Python library built as a PDF toolkit. It is capable of:
- extracting document information (title, author, ...)
- splitting documents page by page
- merging documents page by page
- cropping pages
- merging multiple pages into a single page
- encrypting and decrypting PDF files
- and more!
By being Pure-Python, it should run on any Python platform without any
dependencies on external libraries. It can also work entirely on StringIO
objects rather than file streams, allowing for PDF manipulation in memory.
It is therefore a useful tool for websites that manage or manipulate PDFs.
| {
"content_hash": "9a4b04d11194862a2a8cd432338b7a10",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 74,
"avg_line_length": 37.4375,
"alnum_prop": 0.7863105175292153,
"repo_name": "piotroxp/scibibscan",
"id": "dc9292c0b89564cd38ee63b5a2216733eeb1001b",
"size": "600",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scib/lib/python3.5/site-packages/PyPDF2-1.25.1.dist-info/DESCRIPTION.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "568253"
},
{
"name": "C++",
"bytes": "8204"
},
{
"name": "CSS",
"bytes": "10578"
},
{
"name": "Fortran",
"bytes": "3707"
},
{
"name": "HTML",
"bytes": "1172"
},
{
"name": "Python",
"bytes": "13727486"
},
{
"name": "Shell",
"bytes": "4887"
},
{
"name": "TeX",
"bytes": "678"
}
],
"symlink_target": ""
} |
@class GCHTTPRequest;
// Cache policies control the behaviour of a cache and how requests use the cache
// When setting a cache policy, you can use a combination of these values as a bitmask
// For example: [request setCachePolicy:GCAskServerIfModifiedCachePolicy|GCFallbackToCacheIfLoadFailsCachePolicy|GCDoNotWriteToCacheCachePolicy];
// Note that some of the behaviours below are mutally exclusive - you cannot combine GCAskServerIfModifiedWhenStaleCachePolicy and GCAskServerIfModifiedCachePolicy, for example.
typedef enum _GCCachePolicy {
// The default cache policy. When you set a request to use this, it will use the cache's defaultCachePolicy
// GCDownloadCache's default cache policy is 'GCAskServerIfModifiedWhenStaleCachePolicy'
GCUseDefaultCachePolicy = 0,
// Tell the request not to read from the cache
GCDoNotReadFromCacheCachePolicy = 1,
// The the request not to write to the cache
GCDoNotWriteToCacheCachePolicy = 2,
// Ask the server if there is an updated version of this resource (using a conditional GET) ONLY when the cached data is stale
GCAskServerIfModifiedWhenStaleCachePolicy = 4,
// Always ask the server if there is an updated version of this resource (using a conditional GET)
GCAskServerIfModifiedCachePolicy = 8,
// If cached data exists, use it even if it is stale. This means requests will not talk to the server unless the resource they are requesting is not in the cache
GCOnlyLoadIfNotCachedCachePolicy = 16,
// If cached data exists, use it even if it is stale. If cached data does not exist, stop (will not set an error on the request)
GCDontLoadCachePolicy = 32,
// Specifies that cached data may be used if the request fails. If cached data is used, the request will succeed without error. Usually used in combination with other options above.
GCFallbackToCacheIfLoadFailsCachePolicy = 64
} GCCachePolicy;
// Cache storage policies control whether cached data persists between application launches (GCCachePermanentlyCacheStoragePolicy) or not (GCCacheForSessionDurationCacheStoragePolicy)
// Calling [GCHTTPRequest clearSession] will remove any data stored using GCCacheForSessionDurationCacheStoragePolicy
typedef enum _GCCacheStoragePolicy {
GCCacheForSessionDurationCacheStoragePolicy = 0,
GCCachePermanentlyCacheStoragePolicy = 1
} GCCacheStoragePolicy;
@protocol GCCacheDelegate <NSObject>
@required
// Should return the cache policy that will be used when requests have their cache policy set to GCUseDefaultCachePolicy
- (GCCachePolicy)defaultCachePolicy;
// Returns the date a cached response should expire on. Pass a non-zero max age to specify a custom date.
- (NSDate *)expiryDateForRequest:(GCHTTPRequest *)request maxAge:(NSTimeInterval)maxAge;
// Updates cached response headers with a new expiry date. Pass a non-zero max age to specify a custom date.
- (void)updateExpiryForRequest:(GCHTTPRequest *)request maxAge:(NSTimeInterval)maxAge;
// Looks at the request's cache policy and any cached headers to determine if the cache data is still valid
- (BOOL)canUseCachedDataForRequest:(GCHTTPRequest *)request;
// Removes cached data for a particular request
- (void)removeCachedDataForRequest:(GCHTTPRequest *)request;
// Should return YES if the cache considers its cached response current for the request
// Should return NO is the data is not cached, or (for example) if the cached headers state the request should have expired
- (BOOL)isCachedDataCurrentForRequest:(GCHTTPRequest *)request;
// Should store the response for the passed request in the cache
// When a non-zero maxAge is passed, it should be used as the expiry time for the cached response
- (void)storeResponseForRequest:(GCHTTPRequest *)request maxAge:(NSTimeInterval)maxAge;
// Removes cached data for a particular url
- (void)removeCachedDataForURL:(NSURL *)url;
// Should return an NSDictionary of cached headers for the passed URL, if it is stored in the cache
- (NSDictionary *)cachedResponseHeadersForURL:(NSURL *)url;
// Should return the cached body of a response for the passed URL, if it is stored in the cache
- (NSData *)cachedResponseDataForURL:(NSURL *)url;
// Returns a path to the cached response data, if it exists
- (NSString *)pathToCachedResponseDataForURL:(NSURL *)url;
// Returns a path to the cached response headers, if they url
- (NSString *)pathToCachedResponseHeadersForURL:(NSURL *)url;
// Returns the location to use to store cached response headers for a particular request
- (NSString *)pathToStoreCachedResponseHeadersForRequest:(GCHTTPRequest *)request;
// Returns the location to use to store a cached response body for a particular request
- (NSString *)pathToStoreCachedResponseDataForRequest:(GCHTTPRequest *)request;
// Clear cached data stored for the passed storage policy
- (void)clearCachedResponsesForStoragePolicy:(GCCacheStoragePolicy)cachePolicy;
@end
| {
"content_hash": "61b2e4913f6cedbdf17fad22f54f6b17",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 183,
"avg_line_length": 51.840425531914896,
"alnum_prop": 0.802585676174841,
"repo_name": "lgcassab/GCKit",
"id": "0adc2fa38489dad6020902cff87646fb36339c25",
"size": "5110",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GCKit/GCHTTPRequest/GCCacheDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "385"
},
{
"name": "Objective-C",
"bytes": "1033983"
},
{
"name": "Ruby",
"bytes": "6079"
}
],
"symlink_target": ""
} |
package citrixadc
import (
"net/url"
"github.com/citrix/adc-nitro-go/resource/config/filter"
"github.com/citrix/adc-nitro-go/service"
"github.com/hashicorp/terraform/helper/schema"
"fmt"
"log"
)
func resourceCitrixAdcFilterglobal_filterpolicy_binding() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
Create: createFilterglobal_filterpolicy_bindingFunc,
Read: readFilterglobal_filterpolicy_bindingFunc,
Delete: deleteFilterglobal_filterpolicy_bindingFunc,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"policyname": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"priority": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Computed: true,
ForceNew: true,
},
"state": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}
func createFilterglobal_filterpolicy_bindingFunc(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] citrixadc-provider: In createFilterglobal_filterpolicy_bindingFunc")
client := meta.(*NetScalerNitroClient).client
policyname := d.Get("policyname").(string)
filterglobal_filterpolicy_binding := filter.Filterglobalfilterpolicybinding{
Policyname: d.Get("policyname").(string),
Priority: d.Get("priority").(int),
State: d.Get("state").(string),
}
err := client.UpdateUnnamedResource(service.Filterglobal_filterpolicy_binding.Type(), &filterglobal_filterpolicy_binding)
if err != nil {
return err
}
d.SetId(policyname)
err = readFilterglobal_filterpolicy_bindingFunc(d, meta)
if err != nil {
log.Printf("[ERROR] netscaler-provider: ?? we just created this filterglobal_filterpolicy_binding but we can't read it ?? %s", policyname)
return nil
}
return nil
}
func readFilterglobal_filterpolicy_bindingFunc(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] citrixadc-provider: In readFilterglobal_filterpolicy_bindingFunc")
client := meta.(*NetScalerNitroClient).client
policyname := d.Id()
log.Printf("[DEBUG] citrixadc-provider: Reading filterglobal_filterpolicy_binding state %s", policyname)
findParams := service.FindParams{
ResourceType: "filterglobal_filterpolicy_binding",
}
dataArr, err := client.FindResourceArrayWithParams(findParams)
// Unexpected error
if err != nil {
log.Printf("[DEBUG] citrixadc-provider: Error during FindResourceArrayWithParams %s", err.Error())
return err
}
// Resource is missing
if len(dataArr) == 0 {
log.Printf("[DEBUG] citrixadc-provider: FindResourceArrayWithParams returned empty array")
log.Printf("[WARN] citrixadc-provider: Clearing filterglobal_filterpolicy_binding state %s", policyname)
d.SetId("")
return nil
}
// Iterate through results to find the one with the right id
foundIndex := -1
for i, v := range dataArr {
if v["policyname"].(string) == policyname {
foundIndex = i
break
}
}
// Resource is missing
if foundIndex == -1 {
log.Printf("[DEBUG] citrixadc-provider: FindResourceArrayWithParams policyname not found in array")
log.Printf("[WARN] citrixadc-provider: Clearing filterglobal_filterpolicy_binding state %s", policyname)
d.SetId("")
return nil
}
// Fallthrough
data := dataArr[foundIndex]
d.Set("policyname", data["policyname"])
d.Set("priority", data["priority"])
d.Set("state", data["state"])
return nil
}
func deleteFilterglobal_filterpolicy_bindingFunc(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] citrixadc-provider: In deleteFilterglobal_filterpolicy_bindingFunc")
client := meta.(*NetScalerNitroClient).client
policyname := d.Id()
args := make([]string, 0)
args = append(args, fmt.Sprintf("policyname:%s", url.QueryEscape(policyname)))
err := client.DeleteResourceWithArgs(service.Filterglobal_filterpolicy_binding.Type(), "", args)
if err != nil {
return err
}
d.SetId("")
return nil
}
| {
"content_hash": "9e3902946f60828d0c30e9c2b69b5fb5",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 140,
"avg_line_length": 28.74468085106383,
"alnum_prop": 0.7211941771527264,
"repo_name": "citrix/terraform-provider-netscaler",
"id": "42fa3cba26c3af30a7f733358137337fce3fa17a",
"size": "4053",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "citrixadc/resource_citrixadc_filterglobal_filterpolicy_binding.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "668722"
},
{
"name": "HCL",
"bytes": "229"
},
{
"name": "Makefile",
"bytes": "3956"
},
{
"name": "Shell",
"bytes": "1269"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Text;
using entCMS.Models;
namespace entCMS.Services
{
public class ModuleService : BaseService<cmsModule>
{
#region 私有构造函数,防止实例化
private ModuleService()
{
}
#endregion
#region 实现单例模式
static ModuleService()
{
if (instance == null)
{
lock (lockObj)
{
instance = new ModuleService();
}
}
}
public static ModuleService GetInstance()
{
return (ModuleService)instance;
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="isEnabled"></param>
/// <returns></returns>
public List<cmsModule> GetList(bool? isEnabled)
{
if (isEnabled.HasValue)
{
return GetList(cmsModule._.IsEnabled == (isEnabled.Value ? 1 : 0), cmsModule._.OrderNo.Asc);
}
else
{
return GetList(null, null);
}
}
}
}
| {
"content_hash": "65faef0fa99a841bfdb9980f9046accd",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 108,
"avg_line_length": 24.02,
"alnum_prop": 0.44712739383846795,
"repo_name": "plz821/entCMS",
"id": "8d75a389ba4b3c23b7dd4a53317d487e9d8b0091",
"size": "1239",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "entCMS.Services/ModuleService.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "1249219"
},
{
"name": "ActionScript",
"bytes": "69146"
},
{
"name": "C#",
"bytes": "880383"
},
{
"name": "CSS",
"bytes": "492379"
},
{
"name": "JavaScript",
"bytes": "2754428"
},
{
"name": "PHP",
"bytes": "9076"
},
{
"name": "Shell",
"bytes": "110"
}
],
"symlink_target": ""
} |
package com.planet_ink.coffee_mud.Abilities.Skills;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.TrackingLibrary;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
@SuppressWarnings({"unchecked","rawtypes"})
public class Skill_RegionalAwareness extends StdSkill
{
@Override public String ID() { return "Skill_RegionalAwareness"; }
private final static String localizedName = CMLib.lang().L("Regional Awareness");
@Override public String name() { return localizedName; }
@Override protected int canAffectCode(){return 0;}
@Override protected int canTargetCode(){return 0;}
@Override public int abstractQuality(){return Ability.QUALITY_INDIFFERENT;}
private static final String[] triggerStrings =I(new String[] {"REGION","REGIONALAWARENESS"});
@Override public String[] triggerStrings(){return triggerStrings;}
@Override public int classificationCode(){return Ability.ACODE_SKILL|Ability.DOMAIN_NATURELORE;}
@Override public int overrideMana(){return 0;}
public char roomColor(Room room)
{
if(room==null)
return ' ';
if(CMath.bset(room.phyStats().sensesMask(),PhyStats.SENSE_ROOMUNMAPPABLE))
return 'w';
switch(room.domainType())
{
case Room.DOMAIN_OUTDOORS_CITY:return 'w';
case Room.DOMAIN_OUTDOORS_WOODS:return 'G';
case Room.DOMAIN_OUTDOORS_ROCKS:return 'W';
case Room.DOMAIN_OUTDOORS_PLAINS:return 'Y';
case Room.DOMAIN_OUTDOORS_UNDERWATER:return 'B';
case Room.DOMAIN_OUTDOORS_AIR:return ' ';
case Room.DOMAIN_OUTDOORS_WATERSURFACE:return 'b';
case Room.DOMAIN_OUTDOORS_JUNGLE:return 'R';
case Room.DOMAIN_OUTDOORS_SEAPORT:return 'y';
case Room.DOMAIN_OUTDOORS_SWAMP:return 'r';
case Room.DOMAIN_OUTDOORS_DESERT:return 'y';
case Room.DOMAIN_OUTDOORS_HILLS:return 'g';
case Room.DOMAIN_OUTDOORS_MOUNTAINS:return 'p';
case Room.DOMAIN_OUTDOORS_SPACEPORT:return 'P';
case Room.DOMAIN_INDOORS_STONE:return 'W';
case Room.DOMAIN_INDOORS_WOOD:return 'y';
case Room.DOMAIN_INDOORS_CAVE:return 'w';
case Room.DOMAIN_INDOORS_MAGIC:return 'r';
case Room.DOMAIN_INDOORS_UNDERWATER:return 'B';
case Room.DOMAIN_INDOORS_AIR:return ' ';
case Room.DOMAIN_INDOORS_WATERSURFACE:return 'b';
case Room.DOMAIN_INDOORS_METAL:return 'P';
default:
return 'k';
}
}
public char roomChar(Room room, boolean amOutdoors)
{
if(room==null)
return ' ';
if(CMath.bset(room.phyStats().sensesMask(),PhyStats.SENSE_ROOMUNMAPPABLE))
return ' ';
switch(room.domainType())
{
case Room.DOMAIN_OUTDOORS_CITY:return '=';
case Room.DOMAIN_OUTDOORS_WOODS:return 'T';
case Room.DOMAIN_OUTDOORS_ROCKS:return ':';
case Room.DOMAIN_OUTDOORS_PLAINS:return '_';
case Room.DOMAIN_OUTDOORS_UNDERWATER:return '~';
case Room.DOMAIN_OUTDOORS_AIR:return ' ';
case Room.DOMAIN_OUTDOORS_WATERSURFACE:return '~';
case Room.DOMAIN_OUTDOORS_JUNGLE:return 'J';
case Room.DOMAIN_OUTDOORS_SEAPORT:return 'P';
case Room.DOMAIN_OUTDOORS_SWAMP:return 'x';
case Room.DOMAIN_OUTDOORS_DESERT:return '.';
case Room.DOMAIN_OUTDOORS_HILLS:return 'h';
case Room.DOMAIN_OUTDOORS_MOUNTAINS:return 'M';
case Room.DOMAIN_OUTDOORS_SPACEPORT:return '@';
case Room.DOMAIN_INDOORS_UNDERWATER:return '~';
case Room.DOMAIN_INDOORS_AIR:return ' ';
case Room.DOMAIN_INDOORS_WATERSURFACE:return '~';
case Room.DOMAIN_INDOORS_STONE:
case Room.DOMAIN_INDOORS_WOOD:
case Room.DOMAIN_INDOORS_CAVE:
case Room.DOMAIN_INDOORS_MAGIC:
case Room.DOMAIN_INDOORS_METAL:return '#';
default:
return '?';
}
}
public String[] getMiniMap(Room room, final int diameter, boolean openOnly)
{
final char[][] map=new char[diameter][diameter];
for(int i=0;i<diameter;i++)
for(int i2=0;i2<diameter;i2++)
map[i][i2]=' ';
final boolean amIndoors=((room.domainType()&Room.INDOORS)==Room.INDOORS);
final Room[][] rmap=new Room[diameter][diameter];
final Vector rooms=new Vector();
final HashSet closedPaths=new HashSet();
TrackingLibrary.TrackingFlags flags;
flags = new TrackingLibrary.TrackingFlags()
.plus(TrackingLibrary.TrackingFlag.NOEMPTYGRIDS)
.plus(TrackingLibrary.TrackingFlag.NOAIR);
if(openOnly)
flags = flags
.plus(TrackingLibrary.TrackingFlag.OPENONLY);
CMLib.tracking().getRadiantRooms(room,rooms,flags,null,diameter,null);
rmap[diameter/2][diameter/2]=room;
map[diameter/2][diameter/2]='*';
for(int i=0;i<rooms.size();i++)
{
final Room R=(Room)rooms.elementAt(i);
if((closedPaths.contains(R))
||(R==room))
continue;
Room parentR=null;
int parentDir=-1;
int[] xy=null;
for(int i2=0;(i2<diameter)&&(parentR==null);i2++)
for(int i3=0;(i3<diameter)&&(parentR==null);i3++)
{
final Room R2=rmap[i2][i3];
if(R2!=null)
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
if((R2.getRoomInDir(d)==R)
&&(!closedPaths.contains(R2))
&&(R2.getExitInDir(d)!=null))
{
parentR=R2;
parentDir=d;
xy=Directions.adjustXYByDirections(i3,i2,d);
break;
}
}
if(xy!=null)
{
if((parentDir<0)
||(xy[0]<0)||(xy[0]>=diameter)||(xy[1]<0)||(xy[1]>=diameter)
||(map[xy[1]][xy[0]]!=' '))
closedPaths.add(R);
else
{
map[xy[1]][xy[0]]=roomChar(R,!amIndoors);
rmap[xy[1]][xy[0]]=R;
if((R.domainType()&Room.INDOORS)==Room.INDOORS)
closedPaths.add(R);
}
}
}
final String[] miniMap=new String[diameter];
final StringBuffer str=new StringBuffer("");
char r=' ';
char c=' ';
for(int i2=0;i2<diameter;i2++)
{
str.setLength(0);
for(int i3=0;i3<diameter;i3++)
{
r=map[i2][i3];
c=roomColor(rmap[i2][i3]);
if(c!=' ')
str.append("^"+c+""+r);
else
str.append(r);
}
miniMap[i2]=str.toString();
}
return miniMap;
}
@Override
public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
{
if(auto && (givenTarget instanceof Room) && (asLevel>0))
{
final String[] miniMap=getMiniMap((Room)givenTarget, asLevel, false);
if(commands!=null)
{
for(final String s : miniMap)
commands.add(s);
}
else
for(final String s : miniMap)
if(mob.session()!=null)
mob.session().colorOnlyPrintln(s);
return true;
}
if((!auto)&&((mob.location().domainType()&Room.INDOORS)==Room.INDOORS))
{
mob.tell(L("This only works outdoors."));
return false;
}
if((!auto)
&&(!CMLib.flags().canBeSeenBy(mob.location(),mob)))
{
mob.tell(L("You need to be able to see your surroundings to do that."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,null,this,CMMsg.MSG_LOOK,auto?"":L("<S-NAME> peer(s) at the horizon with a distant expression."));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
final String[] miniMap=getMiniMap(mob.location(), 2+(adjustedLevel(mob,asLevel)/10), true);
for(final String s : miniMap)
if(mob.session()!=null)
mob.session().colorOnlyPrintln(s+"\n\r");
}
}
else
beneficialVisualFizzle(mob,null,L("<S-NAME> peer(s) around distantly, looking frustrated."));
return success;
}
}
| {
"content_hash": "6c7b3c3be674d4b7883412acb99784a1",
"timestamp": "",
"source": "github",
"line_count": 238,
"max_line_length": 136,
"avg_line_length": 34.28151260504202,
"alnum_prop": 0.6709155533766393,
"repo_name": "MaxRau/CoffeeMud",
"id": "9ce8389ee734de2424c32f76e24c5776bb0ac66b",
"size": "8763",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "com/planet_ink/coffee_mud/Abilities/Skills/Skill_RegionalAwareness.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5359"
},
{
"name": "CSS",
"bytes": "1515"
},
{
"name": "HTML",
"bytes": "9650029"
},
{
"name": "Java",
"bytes": "26062781"
},
{
"name": "JavaScript",
"bytes": "24025"
},
{
"name": "Makefile",
"bytes": "23191"
},
{
"name": "Shell",
"bytes": "8543"
}
],
"symlink_target": ""
} |
typedef std::shared_ptr<MachProcess> MachProcessSP;
typedef std::map<nub_process_t, MachProcessSP> ProcessMap;
typedef ProcessMap::iterator ProcessMapIter;
typedef ProcessMap::const_iterator ProcessMapConstIter;
size_t GetAllInfos(std::vector<struct kinfo_proc> &proc_infos);
static size_t
GetAllInfosMatchingName(const char *process_name,
std::vector<struct kinfo_proc> &matching_proc_infos);
// A Thread safe singleton to get a process map pointer.
//
// Returns a pointer to the existing process map, or a pointer to a
// newly created process map if CAN_CREATE is non-zero.
static ProcessMap *GetProcessMap(bool can_create) {
static ProcessMap *g_process_map_ptr = NULL;
if (can_create && g_process_map_ptr == NULL) {
static pthread_mutex_t g_process_map_mutex = PTHREAD_MUTEX_INITIALIZER;
PTHREAD_MUTEX_LOCKER(locker, &g_process_map_mutex);
if (g_process_map_ptr == NULL)
g_process_map_ptr = new ProcessMap;
}
return g_process_map_ptr;
}
// Add PID to the shared process pointer map.
//
// Return non-zero value if we succeed in adding the process to the map.
// The only time this should fail is if we run out of memory and can't
// allocate a ProcessMap.
static nub_bool_t AddProcessToMap(nub_process_t pid, MachProcessSP &procSP) {
ProcessMap *process_map = GetProcessMap(true);
if (process_map) {
process_map->insert(std::make_pair(pid, procSP));
return true;
}
return false;
}
// Remove the shared pointer for PID from the process map.
//
// Returns the number of items removed from the process map.
// static size_t
// RemoveProcessFromMap (nub_process_t pid)
//{
// ProcessMap* process_map = GetProcessMap(false);
// if (process_map)
// {
// return process_map->erase(pid);
// }
// return 0;
//}
// Get the shared pointer for PID from the existing process map.
//
// Returns true if we successfully find a shared pointer to a
// MachProcess object.
static nub_bool_t GetProcessSP(nub_process_t pid, MachProcessSP &procSP) {
ProcessMap *process_map = GetProcessMap(false);
if (process_map != NULL) {
ProcessMapIter pos = process_map->find(pid);
if (pos != process_map->end()) {
procSP = pos->second;
return true;
}
}
procSP.reset();
return false;
}
#ifdef USE_KQUEUE
void *kqueue_thread(void *arg) {
int kq_id = (int)(intptr_t)arg;
#if defined(__APPLE__)
pthread_setname_np("kqueue thread");
#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
struct sched_param thread_param;
int thread_sched_policy;
if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
&thread_param) == 0) {
thread_param.sched_priority = 47;
pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
}
#endif
#endif
struct kevent death_event;
while (true) {
int n_events = kevent(kq_id, NULL, 0, &death_event, 1, NULL);
if (n_events == -1) {
if (errno == EINTR)
continue;
else {
DNBLogError("kqueue failed with error: (%d): %s", errno,
strerror(errno));
return NULL;
}
} else if (death_event.flags & EV_ERROR) {
int error_no = static_cast<int>(death_event.data);
const char *error_str = strerror(error_no);
if (error_str == NULL)
error_str = "Unknown error";
DNBLogError("Failed to initialize kqueue event: (%d): %s", error_no,
error_str);
return NULL;
} else {
int status;
const pid_t pid = (pid_t)death_event.ident;
const pid_t child_pid = waitpid(pid, &status, 0);
bool exited = false;
int signal = 0;
int exit_status = 0;
if (WIFSTOPPED(status)) {
signal = WSTOPSIG(status);
DNBLogThreadedIf(LOG_PROCESS, "waitpid (%i) -> STOPPED (signal = %i)",
child_pid, signal);
} else if (WIFEXITED(status)) {
exit_status = WEXITSTATUS(status);
exited = true;
DNBLogThreadedIf(LOG_PROCESS, "waitpid (%i) -> EXITED (status = %i)",
child_pid, exit_status);
} else if (WIFSIGNALED(status)) {
signal = WTERMSIG(status);
if (child_pid == abs(pid)) {
DNBLogThreadedIf(LOG_PROCESS,
"waitpid (%i) -> SIGNALED and EXITED (signal = %i)",
child_pid, signal);
char exit_info[64];
::snprintf(exit_info, sizeof(exit_info),
"Terminated due to signal %i", signal);
DNBProcessSetExitInfo(child_pid, exit_info);
exited = true;
exit_status = INT8_MAX;
} else {
DNBLogThreadedIf(LOG_PROCESS,
"waitpid (%i) -> SIGNALED (signal = %i)", child_pid,
signal);
}
}
if (exited) {
if (death_event.data & NOTE_EXIT_MEMORY)
DNBProcessSetExitInfo(child_pid, "Terminated due to memory issue");
else if (death_event.data & NOTE_EXIT_DECRYPTFAIL)
DNBProcessSetExitInfo(child_pid, "Terminated due to decrypt failure");
else if (death_event.data & NOTE_EXIT_CSERROR)
DNBProcessSetExitInfo(child_pid,
"Terminated due to code signing error");
DNBLogThreadedIf(
LOG_PROCESS,
"waitpid_process_thread (): setting exit status for pid = %i to %i",
child_pid, exit_status);
DNBProcessSetExitStatus(child_pid, status);
return NULL;
}
}
}
}
static bool spawn_kqueue_thread(pid_t pid) {
pthread_t thread;
int kq_id;
kq_id = kqueue();
if (kq_id == -1) {
DNBLogError("Could not get kqueue for pid = %i.", pid);
return false;
}
struct kevent reg_event;
EV_SET(®_event, pid, EVFILT_PROC, EV_ADD,
NOTE_EXIT | NOTE_EXITSTATUS | NOTE_EXIT_DETAIL, 0, NULL);
// Register the event:
int result = kevent(kq_id, ®_event, 1, NULL, 0, NULL);
if (result != 0) {
DNBLogError(
"Failed to register kqueue NOTE_EXIT event for pid %i, error: %d.", pid,
result);
return false;
}
int ret =
::pthread_create(&thread, NULL, kqueue_thread, (void *)(intptr_t)kq_id);
// pthread_create returns 0 if successful
if (ret == 0) {
::pthread_detach(thread);
return true;
}
return false;
}
#endif // #if USE_KQUEUE
static void *waitpid_thread(void *arg) {
const pid_t pid = (pid_t)(intptr_t)arg;
int status;
#if defined(__APPLE__)
pthread_setname_np("waitpid thread");
#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
struct sched_param thread_param;
int thread_sched_policy;
if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
&thread_param) == 0) {
thread_param.sched_priority = 47;
pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
}
#endif
#endif
while (true) {
pid_t child_pid = waitpid(pid, &status, 0);
DNBLogThreadedIf(LOG_PROCESS, "waitpid_thread (): waitpid (pid = %i, "
"&status, 0) => %i, status = %i, errno = %i",
pid, child_pid, status, errno);
if (child_pid < 0) {
if (errno == EINTR)
continue;
break;
} else {
if (WIFSTOPPED(status)) {
continue;
} else // if (WIFEXITED(status) || WIFSIGNALED(status))
{
DNBLogThreadedIf(
LOG_PROCESS,
"waitpid_thread (): setting exit status for pid = %i to %i",
child_pid, status);
DNBProcessSetExitStatus(child_pid, status);
return NULL;
}
}
}
// We should never exit as long as our child process is alive, so if we
// do something else went wrong and we should exit...
DNBLogThreadedIf(LOG_PROCESS, "waitpid_thread (): main loop exited, setting "
"exit status to an invalid value (-1) for pid "
"%i",
pid);
DNBProcessSetExitStatus(pid, -1);
return NULL;
}
static bool spawn_waitpid_thread(pid_t pid) {
#ifdef USE_KQUEUE
bool success = spawn_kqueue_thread(pid);
if (success)
return true;
#endif
pthread_t thread;
int ret =
::pthread_create(&thread, NULL, waitpid_thread, (void *)(intptr_t)pid);
// pthread_create returns 0 if successful
if (ret == 0) {
::pthread_detach(thread);
return true;
}
return false;
}
nub_process_t DNBProcessLaunch(
const char *path, char const *argv[], const char *envp[],
const char *working_directory, // NULL => don't change, non-NULL => set
// working directory for inferior to this
const char *stdin_path, const char *stdout_path, const char *stderr_path,
bool no_stdio, nub_launch_flavor_t launch_flavor, int disable_aslr,
const char *event_data, char *err_str, size_t err_len) {
DNBLogThreadedIf(LOG_PROCESS, "%s ( path='%s', argv = %p, envp = %p, "
"working_dir=%s, stdin=%s, stdout=%s, "
"stderr=%s, no-stdio=%i, launch_flavor = %u, "
"disable_aslr = %d, err = %p, err_len = "
"%llu) called...",
__FUNCTION__, path, static_cast<void *>(argv),
static_cast<void *>(envp), working_directory, stdin_path,
stdout_path, stderr_path, no_stdio, launch_flavor,
disable_aslr, static_cast<void *>(err_str),
static_cast<uint64_t>(err_len));
if (err_str && err_len > 0)
err_str[0] = '\0';
struct stat path_stat;
if (::stat(path, &path_stat) == -1) {
char stat_error[256];
::strerror_r(errno, stat_error, sizeof(stat_error));
snprintf(err_str, err_len, "%s (%s)", stat_error, path);
return INVALID_NUB_PROCESS;
}
MachProcessSP processSP(new MachProcess);
if (processSP.get()) {
DNBError launch_err;
pid_t pid = processSP->LaunchForDebug(path, argv, envp, working_directory,
stdin_path, stdout_path, stderr_path,
no_stdio, launch_flavor, disable_aslr,
event_data, launch_err);
if (err_str) {
*err_str = '\0';
if (launch_err.Fail()) {
const char *launch_err_str = launch_err.AsString();
if (launch_err_str) {
strlcpy(err_str, launch_err_str, err_len - 1);
err_str[err_len - 1] =
'\0'; // Make sure the error string is terminated
}
}
}
DNBLogThreadedIf(LOG_PROCESS, "(DebugNub) new pid is %d...", pid);
if (pid != INVALID_NUB_PROCESS) {
// Spawn a thread to reap our child inferior process...
spawn_waitpid_thread(pid);
if (processSP->Task().TaskPortForProcessID(launch_err) == TASK_NULL) {
// We failed to get the task for our process ID which is bad.
// Kill our process otherwise it will be stopped at the entry
// point and get reparented to someone else and never go away.
DNBLog("Could not get task port for process, sending SIGKILL and "
"exiting.");
kill(SIGKILL, pid);
if (err_str && err_len > 0) {
if (launch_err.AsString()) {
::snprintf(err_str, err_len,
"failed to get the task for process %i (%s)", pid,
launch_err.AsString());
} else {
::snprintf(err_str, err_len,
"failed to get the task for process %i", pid);
}
}
} else {
bool res = AddProcessToMap(pid, processSP);
UNUSED_IF_ASSERT_DISABLED(res);
assert(res && "Couldn't add process to map!");
return pid;
}
}
}
return INVALID_NUB_PROCESS;
}
// If there is one process with a given name, return the pid for that process.
nub_process_t DNBProcessGetPIDByName(const char *name) {
std::vector<struct kinfo_proc> matching_proc_infos;
size_t num_matching_proc_infos =
GetAllInfosMatchingName(name, matching_proc_infos);
if (num_matching_proc_infos == 1) {
return matching_proc_infos[0].kp_proc.p_pid;
}
return INVALID_NUB_PROCESS;
}
nub_process_t DNBProcessAttachByName(const char *name, struct timespec *timeout,
char *err_str, size_t err_len) {
if (err_str && err_len > 0)
err_str[0] = '\0';
std::vector<struct kinfo_proc> matching_proc_infos;
size_t num_matching_proc_infos =
GetAllInfosMatchingName(name, matching_proc_infos);
if (num_matching_proc_infos == 0) {
DNBLogError("error: no processes match '%s'\n", name);
return INVALID_NUB_PROCESS;
} else if (num_matching_proc_infos > 1) {
DNBLogError("error: %llu processes match '%s':\n",
(uint64_t)num_matching_proc_infos, name);
size_t i;
for (i = 0; i < num_matching_proc_infos; ++i)
DNBLogError("%6u - %s\n", matching_proc_infos[i].kp_proc.p_pid,
matching_proc_infos[i].kp_proc.p_comm);
return INVALID_NUB_PROCESS;
}
return DNBProcessAttach(matching_proc_infos[0].kp_proc.p_pid, timeout,
err_str, err_len);
}
nub_process_t DNBProcessAttach(nub_process_t attach_pid,
struct timespec *timeout, char *err_str,
size_t err_len) {
if (err_str && err_len > 0)
err_str[0] = '\0';
pid_t pid = INVALID_NUB_PROCESS;
MachProcessSP processSP(new MachProcess);
if (processSP.get()) {
DNBLogThreadedIf(LOG_PROCESS, "(DebugNub) attaching to pid %d...",
attach_pid);
pid = processSP->AttachForDebug(attach_pid, err_str, err_len);
if (pid != INVALID_NUB_PROCESS) {
bool res = AddProcessToMap(pid, processSP);
UNUSED_IF_ASSERT_DISABLED(res);
assert(res && "Couldn't add process to map!");
spawn_waitpid_thread(pid);
}
}
while (pid != INVALID_NUB_PROCESS) {
// Wait for process to start up and hit entry point
DNBLogThreadedIf(LOG_PROCESS, "%s DNBProcessWaitForEvent (%4.4x, "
"eEventProcessRunningStateChanged | "
"eEventProcessStoppedStateChanged, true, "
"INFINITE)...",
__FUNCTION__, pid);
nub_event_t set_events =
DNBProcessWaitForEvents(pid, eEventProcessRunningStateChanged |
eEventProcessStoppedStateChanged,
true, timeout);
DNBLogThreadedIf(LOG_PROCESS, "%s DNBProcessWaitForEvent (%4.4x, "
"eEventProcessRunningStateChanged | "
"eEventProcessStoppedStateChanged, true, "
"INFINITE) => 0x%8.8x",
__FUNCTION__, pid, set_events);
if (set_events == 0) {
if (err_str && err_len > 0)
snprintf(err_str, err_len, "operation timed out");
pid = INVALID_NUB_PROCESS;
} else {
if (set_events & (eEventProcessRunningStateChanged |
eEventProcessStoppedStateChanged)) {
nub_state_t pid_state = DNBProcessGetState(pid);
DNBLogThreadedIf(
LOG_PROCESS,
"%s process %4.4x state changed (eEventProcessStateChanged): %s",
__FUNCTION__, pid, DNBStateAsString(pid_state));
switch (pid_state) {
case eStateInvalid:
case eStateUnloaded:
case eStateAttaching:
case eStateLaunching:
case eStateSuspended:
break; // Ignore
case eStateRunning:
case eStateStepping:
// Still waiting to stop at entry point...
break;
case eStateStopped:
case eStateCrashed:
return pid;
case eStateDetached:
case eStateExited:
if (err_str && err_len > 0)
snprintf(err_str, err_len, "process exited");
return INVALID_NUB_PROCESS;
}
}
DNBProcessResetEvents(pid, set_events);
}
}
return INVALID_NUB_PROCESS;
}
size_t GetAllInfos(std::vector<struct kinfo_proc> &proc_infos) {
size_t size = 0;
int name[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
u_int namelen = sizeof(name) / sizeof(int);
int err;
// Try to find out how many processes are around so we can
// size the buffer appropriately. sysctl's man page specifically suggests
// this approach, and says it returns a bit larger size than needed to
// handle any new processes created between then and now.
err = ::sysctl(name, namelen, NULL, &size, NULL, 0);
if ((err < 0) && (err != ENOMEM)) {
proc_infos.clear();
perror("sysctl (mib, miblen, NULL, &num_processes, NULL, 0)");
return 0;
}
// Increase the size of the buffer by a few processes in case more have
// been spawned
proc_infos.resize(size / sizeof(struct kinfo_proc));
size = proc_infos.size() *
sizeof(struct kinfo_proc); // Make sure we don't exceed our resize...
err = ::sysctl(name, namelen, &proc_infos[0], &size, NULL, 0);
if (err < 0) {
proc_infos.clear();
return 0;
}
// Trim down our array to fit what we actually got back
proc_infos.resize(size / sizeof(struct kinfo_proc));
return proc_infos.size();
}
static size_t
GetAllInfosMatchingName(const char *full_process_name,
std::vector<struct kinfo_proc> &matching_proc_infos) {
matching_proc_infos.clear();
if (full_process_name && full_process_name[0]) {
// We only get the process name, not the full path, from the proc_info. So
// just take the
// base name of the process name...
const char *process_name;
process_name = strrchr(full_process_name, '/');
if (process_name == NULL)
process_name = full_process_name;
else
process_name++;
const size_t process_name_len = strlen(process_name);
std::vector<struct kinfo_proc> proc_infos;
const size_t num_proc_infos = GetAllInfos(proc_infos);
if (num_proc_infos > 0) {
uint32_t i;
for (i = 0; i < num_proc_infos; i++) {
// Skip zombie processes and processes with unset status
if (proc_infos[i].kp_proc.p_stat == 0 ||
proc_infos[i].kp_proc.p_stat == SZOMB)
continue;
// Check for process by name. We only check the first MAXCOMLEN
// chars as that is all that kp_proc.p_comm holds.
if (::strncasecmp(process_name, proc_infos[i].kp_proc.p_comm,
MAXCOMLEN) == 0) {
if (process_name_len > MAXCOMLEN) {
// We found a matching process name whose first MAXCOMLEN
// characters match, but there is more to the name than
// this. We need to get the full process name. Use proc_pidpath,
// which will get
// us the full path to the executed process.
char proc_path_buf[PATH_MAX];
int return_val = proc_pidpath(proc_infos[i].kp_proc.p_pid,
proc_path_buf, PATH_MAX);
if (return_val > 0) {
// Okay, now search backwards from that to see if there is a
// slash in the name. Note, even though we got all the args we
// don't care
// because the list data is just a bunch of concatenated null
// terminated strings
// so strrchr will start from the end of argv0.
const char *argv_basename = strrchr(proc_path_buf, '/');
if (argv_basename) {
// Skip the '/'
++argv_basename;
} else {
// We didn't find a directory delimiter in the process argv[0],
// just use what was in there
argv_basename = proc_path_buf;
}
if (argv_basename) {
if (::strncasecmp(process_name, argv_basename, PATH_MAX) == 0) {
matching_proc_infos.push_back(proc_infos[i]);
}
}
}
} else {
// We found a matching process, add it to our list
matching_proc_infos.push_back(proc_infos[i]);
}
}
}
}
}
// return the newly added matches.
return matching_proc_infos.size();
}
nub_process_t DNBProcessAttachWait(
const char *waitfor_process_name, nub_launch_flavor_t launch_flavor,
bool ignore_existing, struct timespec *timeout_abstime,
useconds_t waitfor_interval, char *err_str, size_t err_len,
DNBShouldCancelCallback should_cancel_callback, void *callback_data) {
DNBError prepare_error;
std::vector<struct kinfo_proc> exclude_proc_infos;
size_t num_exclude_proc_infos;
// If the PrepareForAttach returns a valid token, use MachProcess to check
// for the process, otherwise scan the process table.
const void *attach_token = MachProcess::PrepareForAttach(
waitfor_process_name, launch_flavor, true, prepare_error);
if (prepare_error.Fail()) {
DNBLogError("Error in PrepareForAttach: %s", prepare_error.AsString());
return INVALID_NUB_PROCESS;
}
if (attach_token == NULL) {
if (ignore_existing)
num_exclude_proc_infos =
GetAllInfosMatchingName(waitfor_process_name, exclude_proc_infos);
else
num_exclude_proc_infos = 0;
}
DNBLogThreadedIf(LOG_PROCESS, "Waiting for '%s' to appear...\n",
waitfor_process_name);
// Loop and try to find the process by name
nub_process_t waitfor_pid = INVALID_NUB_PROCESS;
while (waitfor_pid == INVALID_NUB_PROCESS) {
if (attach_token != NULL) {
nub_process_t pid;
pid = MachProcess::CheckForProcess(attach_token, launch_flavor);
if (pid != INVALID_NUB_PROCESS) {
waitfor_pid = pid;
break;
}
} else {
// Get the current process list, and check for matches that
// aren't in our original list. If anyone wants to attach
// to an existing process by name, they should do it with
// --attach=PROCNAME. Else we will wait for the first matching
// process that wasn't in our exclusion list.
std::vector<struct kinfo_proc> proc_infos;
const size_t num_proc_infos =
GetAllInfosMatchingName(waitfor_process_name, proc_infos);
for (size_t i = 0; i < num_proc_infos; i++) {
nub_process_t curr_pid = proc_infos[i].kp_proc.p_pid;
for (size_t j = 0; j < num_exclude_proc_infos; j++) {
if (curr_pid == exclude_proc_infos[j].kp_proc.p_pid) {
// This process was in our exclusion list, don't use it.
curr_pid = INVALID_NUB_PROCESS;
break;
}
}
// If we didn't find CURR_PID in our exclusion list, then use it.
if (curr_pid != INVALID_NUB_PROCESS) {
// We found our process!
waitfor_pid = curr_pid;
break;
}
}
}
// If we haven't found our process yet, check for a timeout
// and then sleep for a bit until we poll again.
if (waitfor_pid == INVALID_NUB_PROCESS) {
if (timeout_abstime != NULL) {
// Check to see if we have a waitfor-duration option that
// has timed out?
if (DNBTimer::TimeOfDayLaterThan(*timeout_abstime)) {
if (err_str && err_len > 0)
snprintf(err_str, err_len, "operation timed out");
DNBLogError("error: waiting for process '%s' timed out.\n",
waitfor_process_name);
return INVALID_NUB_PROCESS;
}
}
// Call the should cancel callback as well...
if (should_cancel_callback != NULL &&
should_cancel_callback(callback_data)) {
DNBLogThreadedIf(
LOG_PROCESS,
"DNBProcessAttachWait cancelled by should_cancel callback.");
waitfor_pid = INVALID_NUB_PROCESS;
break;
}
::usleep(waitfor_interval); // Sleep for WAITFOR_INTERVAL, then poll again
}
}
if (waitfor_pid != INVALID_NUB_PROCESS) {
DNBLogThreadedIf(LOG_PROCESS, "Attaching to %s with pid %i...\n",
waitfor_process_name, waitfor_pid);
waitfor_pid =
DNBProcessAttach(waitfor_pid, timeout_abstime, err_str, err_len);
}
bool success = waitfor_pid != INVALID_NUB_PROCESS;
MachProcess::CleanupAfterAttach(attach_token, launch_flavor, success,
prepare_error);
return waitfor_pid;
}
nub_bool_t DNBProcessDetach(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
const bool remove = true;
DNBLogThreaded(
"Disabling breakpoints and watchpoints, and detaching from %d.", pid);
procSP->DisableAllBreakpoints(remove);
procSP->DisableAllWatchpoints(remove);
return procSP->Detach();
}
return false;
}
nub_bool_t DNBProcessKill(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->Kill();
}
return false;
}
nub_bool_t DNBProcessSignal(nub_process_t pid, int signal) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->Signal(signal);
}
return false;
}
nub_bool_t DNBProcessInterrupt(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->Interrupt();
return false;
}
nub_bool_t DNBProcessSendEvent(nub_process_t pid, const char *event) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
// FIXME: Do something with the error...
DNBError send_error;
return procSP->SendEvent(event, send_error);
}
return false;
}
nub_bool_t DNBProcessIsAlive(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return MachTask::IsValid(procSP->Task().TaskPort());
}
return eStateInvalid;
}
// Process and Thread state information
nub_state_t DNBProcessGetState(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->GetState();
}
return eStateInvalid;
}
// Process and Thread state information
nub_bool_t DNBProcessGetExitStatus(nub_process_t pid, int *status) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->GetExitStatus(status);
}
return false;
}
nub_bool_t DNBProcessSetExitStatus(nub_process_t pid, int status) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
procSP->SetExitStatus(status);
return true;
}
return false;
}
const char *DNBProcessGetExitInfo(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->GetExitInfo();
}
return NULL;
}
nub_bool_t DNBProcessSetExitInfo(nub_process_t pid, const char *info) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
procSP->SetExitInfo(info);
return true;
}
return false;
}
const char *DNBThreadGetName(nub_process_t pid, nub_thread_t tid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->ThreadGetName(tid);
return NULL;
}
nub_bool_t
DNBThreadGetIdentifierInfo(nub_process_t pid, nub_thread_t tid,
thread_identifier_info_data_t *ident_info) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetThreadList().GetIdentifierInfo(tid, ident_info);
return false;
}
nub_state_t DNBThreadGetState(nub_process_t pid, nub_thread_t tid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->ThreadGetState(tid);
}
return eStateInvalid;
}
const char *DNBStateAsString(nub_state_t state) {
switch (state) {
case eStateInvalid:
return "Invalid";
case eStateUnloaded:
return "Unloaded";
case eStateAttaching:
return "Attaching";
case eStateLaunching:
return "Launching";
case eStateStopped:
return "Stopped";
case eStateRunning:
return "Running";
case eStateStepping:
return "Stepping";
case eStateCrashed:
return "Crashed";
case eStateDetached:
return "Detached";
case eStateExited:
return "Exited";
case eStateSuspended:
return "Suspended";
}
return "nub_state_t ???";
}
Genealogy::ThreadActivitySP DNBGetGenealogyInfoForThread(nub_process_t pid,
nub_thread_t tid,
bool &timed_out) {
Genealogy::ThreadActivitySP thread_activity_sp;
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
thread_activity_sp = procSP->GetGenealogyInfoForThread(tid, timed_out);
return thread_activity_sp;
}
Genealogy::ProcessExecutableInfoSP DNBGetGenealogyImageInfo(nub_process_t pid,
size_t idx) {
Genealogy::ProcessExecutableInfoSP image_info_sp;
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
image_info_sp = procSP->GetGenealogyImageInfo(idx);
}
return image_info_sp;
}
ThreadInfo::QoS DNBGetRequestedQoSForThread(nub_process_t pid, nub_thread_t tid,
nub_addr_t tsd,
uint64_t dti_qos_class_index) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->GetRequestedQoS(tid, tsd, dti_qos_class_index);
}
return ThreadInfo::QoS();
}
nub_addr_t DNBGetPThreadT(nub_process_t pid, nub_thread_t tid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->GetPThreadT(tid);
}
return INVALID_NUB_ADDRESS;
}
nub_addr_t DNBGetDispatchQueueT(nub_process_t pid, nub_thread_t tid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->GetDispatchQueueT(tid);
}
return INVALID_NUB_ADDRESS;
}
nub_addr_t
DNBGetTSDAddressForThread(nub_process_t pid, nub_thread_t tid,
uint64_t plo_pthread_tsd_base_address_offset,
uint64_t plo_pthread_tsd_base_offset,
uint64_t plo_pthread_tsd_entry_size) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->GetTSDAddressForThread(
tid, plo_pthread_tsd_base_address_offset, plo_pthread_tsd_base_offset,
plo_pthread_tsd_entry_size);
}
return INVALID_NUB_ADDRESS;
}
JSONGenerator::ObjectSP DNBGetLoadedDynamicLibrariesInfos(
nub_process_t pid, nub_addr_t image_list_address, nub_addr_t image_count) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->GetLoadedDynamicLibrariesInfos(pid, image_list_address,
image_count);
}
return JSONGenerator::ObjectSP();
}
JSONGenerator::ObjectSP DNBGetAllLoadedLibrariesInfos(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->GetAllLoadedLibrariesInfos(pid);
}
return JSONGenerator::ObjectSP();
}
JSONGenerator::ObjectSP
DNBGetLibrariesInfoForAddresses(nub_process_t pid,
std::vector<uint64_t> &macho_addresses) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->GetLibrariesInfoForAddresses(pid, macho_addresses);
}
return JSONGenerator::ObjectSP();
}
JSONGenerator::ObjectSP DNBGetSharedCacheInfo(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->GetSharedCacheInfo(pid);
}
return JSONGenerator::ObjectSP();
}
const char *DNBProcessGetExecutablePath(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->Path();
}
return NULL;
}
nub_size_t DNBProcessGetArgumentCount(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->ArgumentCount();
}
return 0;
}
const char *DNBProcessGetArgumentAtIndex(nub_process_t pid, nub_size_t idx) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->ArgumentAtIndex(idx);
}
return NULL;
}
// Execution control
nub_bool_t DNBProcessResume(nub_process_t pid,
const DNBThreadResumeAction *actions,
size_t num_actions) {
DNBLogThreadedIf(LOG_PROCESS, "%s(pid = %4.4x)", __FUNCTION__, pid);
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
DNBThreadResumeActions thread_actions(actions, num_actions);
// Below we add a default thread plan just in case one wasn't
// provided so all threads always know what they were supposed to do
if (thread_actions.IsEmpty()) {
// No thread plans were given, so the default it to run all threads
thread_actions.SetDefaultThreadActionIfNeeded(eStateRunning, 0);
} else {
// Some thread plans were given which means anything that wasn't
// specified should remain stopped.
thread_actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
}
return procSP->Resume(thread_actions);
}
return false;
}
nub_bool_t DNBProcessHalt(nub_process_t pid) {
DNBLogThreadedIf(LOG_PROCESS, "%s(pid = %4.4x)", __FUNCTION__, pid);
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->Signal(SIGSTOP);
return false;
}
//
// nub_bool_t
// DNBThreadResume (nub_process_t pid, nub_thread_t tid, nub_bool_t step)
//{
// DNBLogThreadedIf(LOG_THREAD, "%s(pid = %4.4x, tid = %4.4x, step = %u)",
// __FUNCTION__, pid, tid, (uint32_t)step);
// MachProcessSP procSP;
// if (GetProcessSP (pid, procSP))
// {
// return procSP->Resume(tid, step, 0);
// }
// return false;
//}
//
// nub_bool_t
// DNBThreadResumeWithSignal (nub_process_t pid, nub_thread_t tid, nub_bool_t
// step, int signal)
//{
// DNBLogThreadedIf(LOG_THREAD, "%s(pid = %4.4x, tid = %4.4x, step = %u,
// signal = %i)", __FUNCTION__, pid, tid, (uint32_t)step, signal);
// MachProcessSP procSP;
// if (GetProcessSP (pid, procSP))
// {
// return procSP->Resume(tid, step, signal);
// }
// return false;
//}
nub_event_t DNBProcessWaitForEvents(nub_process_t pid, nub_event_t event_mask,
bool wait_for_set,
struct timespec *timeout) {
nub_event_t result = 0;
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
if (wait_for_set)
result = procSP->Events().WaitForSetEvents(event_mask, timeout);
else
result = procSP->Events().WaitForEventsToReset(event_mask, timeout);
}
return result;
}
void DNBProcessResetEvents(nub_process_t pid, nub_event_t event_mask) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
procSP->Events().ResetEvents(event_mask);
}
// Breakpoints
nub_bool_t DNBBreakpointSet(nub_process_t pid, nub_addr_t addr, nub_size_t size,
nub_bool_t hardware) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->CreateBreakpoint(addr, size, hardware) != NULL;
return false;
}
nub_bool_t DNBBreakpointClear(nub_process_t pid, nub_addr_t addr) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->DisableBreakpoint(addr, true);
return false; // Failed
}
// Watchpoints
nub_bool_t DNBWatchpointSet(nub_process_t pid, nub_addr_t addr, nub_size_t size,
uint32_t watch_flags, nub_bool_t hardware) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->CreateWatchpoint(addr, size, watch_flags, hardware) != NULL;
return false;
}
nub_bool_t DNBWatchpointClear(nub_process_t pid, nub_addr_t addr) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->DisableWatchpoint(addr, true);
return false; // Failed
}
// Return the number of supported hardware watchpoints.
uint32_t DNBWatchpointGetNumSupportedHWP(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetNumSupportedHardwareWatchpoints();
return 0;
}
// Read memory in the address space of process PID. This call will take
// care of setting and restoring permissions and breaking up the memory
// read into multiple chunks as required.
//
// RETURNS: number of bytes actually read
nub_size_t DNBProcessMemoryRead(nub_process_t pid, nub_addr_t addr,
nub_size_t size, void *buf) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->ReadMemory(addr, size, buf);
return 0;
}
uint64_t DNBProcessMemoryReadInteger(nub_process_t pid, nub_addr_t addr,
nub_size_t integer_size,
uint64_t fail_value) {
union Integers {
uint8_t u8;
uint16_t u16;
uint32_t u32;
uint64_t u64;
};
if (integer_size <= sizeof(uint64_t)) {
Integers ints;
if (DNBProcessMemoryRead(pid, addr, integer_size, &ints) == integer_size) {
switch (integer_size) {
case 1:
return ints.u8;
case 2:
return ints.u16;
case 3:
return ints.u32 & 0xffffffu;
case 4:
return ints.u32;
case 5:
return ints.u32 & 0x000000ffffffffffull;
case 6:
return ints.u32 & 0x0000ffffffffffffull;
case 7:
return ints.u32 & 0x00ffffffffffffffull;
case 8:
return ints.u64;
}
}
}
return fail_value;
}
nub_addr_t DNBProcessMemoryReadPointer(nub_process_t pid, nub_addr_t addr) {
cpu_type_t cputype = DNBProcessGetCPUType(pid);
if (cputype) {
const nub_size_t pointer_size = (cputype & CPU_ARCH_ABI64) ? 8 : 4;
return DNBProcessMemoryReadInteger(pid, addr, pointer_size, 0);
}
return 0;
}
std::string DNBProcessMemoryReadCString(nub_process_t pid, nub_addr_t addr) {
std::string cstr;
char buffer[256];
const nub_size_t max_buffer_cstr_length = sizeof(buffer) - 1;
buffer[max_buffer_cstr_length] = '\0';
nub_size_t length = 0;
nub_addr_t curr_addr = addr;
do {
nub_size_t bytes_read =
DNBProcessMemoryRead(pid, curr_addr, max_buffer_cstr_length, buffer);
if (bytes_read == 0)
break;
length = strlen(buffer);
cstr.append(buffer, length);
curr_addr += length;
} while (length == max_buffer_cstr_length);
return cstr;
}
std::string DNBProcessMemoryReadCStringFixed(nub_process_t pid, nub_addr_t addr,
nub_size_t fixed_length) {
std::string cstr;
char buffer[fixed_length + 1];
buffer[fixed_length] = '\0';
nub_size_t bytes_read = DNBProcessMemoryRead(pid, addr, fixed_length, buffer);
if (bytes_read > 0)
cstr.assign(buffer);
return cstr;
}
// Write memory to the address space of process PID. This call will take
// care of setting and restoring permissions and breaking up the memory
// write into multiple chunks as required.
//
// RETURNS: number of bytes actually written
nub_size_t DNBProcessMemoryWrite(nub_process_t pid, nub_addr_t addr,
nub_size_t size, const void *buf) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->WriteMemory(addr, size, buf);
return 0;
}
nub_addr_t DNBProcessMemoryAllocate(nub_process_t pid, nub_size_t size,
uint32_t permissions) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->Task().AllocateMemory(size, permissions);
return 0;
}
nub_bool_t DNBProcessMemoryDeallocate(nub_process_t pid, nub_addr_t addr) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->Task().DeallocateMemory(addr);
return 0;
}
// Find attributes of the memory region that contains ADDR for process PID,
// if possible, and return a string describing those attributes.
//
// Returns 1 if we could find attributes for this region and OUTBUF can
// be sent to the remote debugger.
//
// Returns 0 if we couldn't find the attributes for a region of memory at
// that address and OUTBUF should not be sent.
//
// Returns -1 if this platform cannot look up information about memory regions
// or if we do not yet have a valid launched process.
//
int DNBProcessMemoryRegionInfo(nub_process_t pid, nub_addr_t addr,
DNBRegionInfo *region_info) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->Task().GetMemoryRegionInfo(addr, region_info);
return -1;
}
std::string DNBProcessGetProfileData(nub_process_t pid,
DNBProfileDataScanType scanType) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->Task().GetProfileData(scanType);
return std::string("");
}
nub_bool_t DNBProcessSetEnableAsyncProfiling(nub_process_t pid,
nub_bool_t enable,
uint64_t interval_usec,
DNBProfileDataScanType scan_type) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
procSP->SetEnableAsyncProfiling(enable, interval_usec, scan_type);
return true;
}
return false;
}
// Get the number of threads for the specified process.
nub_size_t DNBProcessGetNumThreads(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetNumThreads();
return 0;
}
// Get the thread ID of the current thread.
nub_thread_t DNBProcessGetCurrentThread(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetCurrentThread();
return 0;
}
// Get the mach port number of the current thread.
nub_thread_t DNBProcessGetCurrentThreadMachPort(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetCurrentThreadMachPort();
return 0;
}
// Change the current thread.
nub_thread_t DNBProcessSetCurrentThread(nub_process_t pid, nub_thread_t tid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->SetCurrentThread(tid);
return INVALID_NUB_THREAD;
}
// Dump a string describing a thread's stop reason to the specified file
// handle
nub_bool_t DNBThreadGetStopReason(nub_process_t pid, nub_thread_t tid,
struct DNBThreadStopInfo *stop_info) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetThreadStoppedReason(tid, stop_info);
return false;
}
// Return string description for the specified thread.
//
// RETURNS: NULL if the thread isn't valid, else a NULL terminated C
// string from a static buffer that must be copied prior to subsequent
// calls.
const char *DNBThreadGetInfo(nub_process_t pid, nub_thread_t tid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetThreadInfo(tid);
return NULL;
}
// Get the thread ID given a thread index.
nub_thread_t DNBProcessGetThreadAtIndex(nub_process_t pid, size_t thread_idx) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetThreadAtIndex(thread_idx);
return INVALID_NUB_THREAD;
}
// Do whatever is needed to sync the thread's register state with it's kernel
// values.
nub_bool_t DNBProcessSyncThreadState(nub_process_t pid, nub_thread_t tid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->SyncThreadState(tid);
return false;
}
nub_addr_t DNBProcessGetSharedLibraryInfoAddress(nub_process_t pid) {
MachProcessSP procSP;
DNBError err;
if (GetProcessSP(pid, procSP))
return procSP->Task().GetDYLDAllImageInfosAddress(err);
return INVALID_NUB_ADDRESS;
}
nub_bool_t DNBProcessSharedLibrariesUpdated(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
procSP->SharedLibrariesUpdated();
return true;
}
return false;
}
const char *DNBGetDeploymentInfo(nub_process_t pid,
const struct load_command& lc,
uint64_t load_command_address,
uint32_t& major_version,
uint32_t& minor_version,
uint32_t& patch_version) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetDeploymentInfo(lc, load_command_address,
major_version, minor_version,
patch_version);
return nullptr;
}
// Get the current shared library information for a process. Only return
// the shared libraries that have changed since the last shared library
// state changed event if only_changed is non-zero.
nub_size_t
DNBProcessGetSharedLibraryInfo(nub_process_t pid, nub_bool_t only_changed,
struct DNBExecutableImageInfo **image_infos) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->CopyImageInfos(image_infos, only_changed);
// If we have no process, then return NULL for the shared library info
// and zero for shared library count
*image_infos = NULL;
return 0;
}
uint32_t DNBGetRegisterCPUType() {
return DNBArchProtocol::GetRegisterCPUType();
}
// Get the register set information for a specific thread.
const DNBRegisterSetInfo *DNBGetRegisterSetInfo(nub_size_t *num_reg_sets) {
return DNBArchProtocol::GetRegisterSetInfo(num_reg_sets);
}
// Read a register value by register set and register index.
nub_bool_t DNBThreadGetRegisterValueByID(nub_process_t pid, nub_thread_t tid,
uint32_t set, uint32_t reg,
DNBRegisterValue *value) {
MachProcessSP procSP;
::bzero(value, sizeof(DNBRegisterValue));
if (GetProcessSP(pid, procSP)) {
if (tid != INVALID_NUB_THREAD)
return procSP->GetRegisterValue(tid, set, reg, value);
}
return false;
}
nub_bool_t DNBThreadSetRegisterValueByID(nub_process_t pid, nub_thread_t tid,
uint32_t set, uint32_t reg,
const DNBRegisterValue *value) {
if (tid != INVALID_NUB_THREAD) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->SetRegisterValue(tid, set, reg, value);
}
return false;
}
nub_size_t DNBThreadGetRegisterContext(nub_process_t pid, nub_thread_t tid,
void *buf, size_t buf_len) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
if (tid != INVALID_NUB_THREAD)
return procSP->GetThreadList().GetRegisterContext(tid, buf, buf_len);
}
::bzero(buf, buf_len);
return 0;
}
nub_size_t DNBThreadSetRegisterContext(nub_process_t pid, nub_thread_t tid,
const void *buf, size_t buf_len) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
if (tid != INVALID_NUB_THREAD)
return procSP->GetThreadList().SetRegisterContext(tid, buf, buf_len);
}
return 0;
}
uint32_t DNBThreadSaveRegisterState(nub_process_t pid, nub_thread_t tid) {
if (tid != INVALID_NUB_THREAD) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetThreadList().SaveRegisterState(tid);
}
return 0;
}
nub_bool_t DNBThreadRestoreRegisterState(nub_process_t pid, nub_thread_t tid,
uint32_t save_id) {
if (tid != INVALID_NUB_THREAD) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetThreadList().RestoreRegisterState(tid, save_id);
}
return false;
}
// Read a register value by name.
nub_bool_t DNBThreadGetRegisterValueByName(nub_process_t pid, nub_thread_t tid,
uint32_t reg_set,
const char *reg_name,
DNBRegisterValue *value) {
MachProcessSP procSP;
::bzero(value, sizeof(DNBRegisterValue));
if (GetProcessSP(pid, procSP)) {
const struct DNBRegisterSetInfo *set_info;
nub_size_t num_reg_sets = 0;
set_info = DNBGetRegisterSetInfo(&num_reg_sets);
if (set_info) {
uint32_t set = reg_set;
uint32_t reg;
if (set == REGISTER_SET_ALL) {
for (set = 1; set < num_reg_sets; ++set) {
for (reg = 0; reg < set_info[set].num_registers; ++reg) {
if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0)
return procSP->GetRegisterValue(tid, set, reg, value);
}
}
} else {
for (reg = 0; reg < set_info[set].num_registers; ++reg) {
if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0)
return procSP->GetRegisterValue(tid, set, reg, value);
}
}
}
}
return false;
}
// Read a register set and register number from the register name.
nub_bool_t DNBGetRegisterInfoByName(const char *reg_name,
DNBRegisterInfo *info) {
const struct DNBRegisterSetInfo *set_info;
nub_size_t num_reg_sets = 0;
set_info = DNBGetRegisterSetInfo(&num_reg_sets);
if (set_info) {
uint32_t set, reg;
for (set = 1; set < num_reg_sets; ++set) {
for (reg = 0; reg < set_info[set].num_registers; ++reg) {
if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0) {
*info = set_info[set].registers[reg];
return true;
}
}
}
for (set = 1; set < num_reg_sets; ++set) {
uint32_t reg;
for (reg = 0; reg < set_info[set].num_registers; ++reg) {
if (set_info[set].registers[reg].alt == NULL)
continue;
if (strcasecmp(reg_name, set_info[set].registers[reg].alt) == 0) {
*info = set_info[set].registers[reg];
return true;
}
}
}
}
::bzero(info, sizeof(DNBRegisterInfo));
return false;
}
// Set the name to address callback function that this nub can use
// for any name to address lookups that are needed.
nub_bool_t DNBProcessSetNameToAddressCallback(nub_process_t pid,
DNBCallbackNameToAddress callback,
void *baton) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
procSP->SetNameToAddressCallback(callback, baton);
return true;
}
return false;
}
// Set the name to address callback function that this nub can use
// for any name to address lookups that are needed.
nub_bool_t DNBProcessSetSharedLibraryInfoCallback(
nub_process_t pid, DNBCallbackCopyExecutableImageInfos callback,
void *baton) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
procSP->SetSharedLibraryInfoCallback(callback, baton);
return true;
}
return false;
}
nub_addr_t DNBProcessLookupAddress(nub_process_t pid, const char *name,
const char *shlib) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP)) {
return procSP->LookupSymbol(name, shlib);
}
return INVALID_NUB_ADDRESS;
}
nub_size_t DNBProcessGetAvailableSTDOUT(nub_process_t pid, char *buf,
nub_size_t buf_size) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetAvailableSTDOUT(buf, buf_size);
return 0;
}
nub_size_t DNBProcessGetAvailableSTDERR(nub_process_t pid, char *buf,
nub_size_t buf_size) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetAvailableSTDERR(buf, buf_size);
return 0;
}
nub_size_t DNBProcessGetAvailableProfileData(nub_process_t pid, char *buf,
nub_size_t buf_size) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetAsyncProfileData(buf, buf_size);
return 0;
}
DarwinLogEventVector DNBProcessGetAvailableDarwinLogEvents(nub_process_t pid) {
return DarwinLogCollector::GetEventsForProcess(pid);
}
nub_size_t DNBProcessGetStopCount(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->StopCount();
return 0;
}
uint32_t DNBProcessGetCPUType(nub_process_t pid) {
MachProcessSP procSP;
if (GetProcessSP(pid, procSP))
return procSP->GetCPUType();
return 0;
}
nub_bool_t DNBResolveExecutablePath(const char *path, char *resolved_path,
size_t resolved_path_size) {
if (path == NULL || path[0] == '\0')
return false;
char max_path[PATH_MAX];
std::string result;
CFString::GlobPath(path, result);
if (result.empty())
result = path;
struct stat path_stat;
if (::stat(path, &path_stat) == 0) {
if ((path_stat.st_mode & S_IFMT) == S_IFDIR) {
CFBundle bundle(path);
CFReleaser<CFURLRef> url(bundle.CopyExecutableURL());
if (url.get()) {
if (::CFURLGetFileSystemRepresentation(
url.get(), true, (UInt8 *)resolved_path, resolved_path_size))
return true;
}
}
}
if (realpath(path, max_path)) {
// Found the path relatively...
::strlcpy(resolved_path, max_path, resolved_path_size);
return strlen(resolved_path) + 1 < resolved_path_size;
} else {
// Not a relative path, check the PATH environment variable if the
const char *PATH = getenv("PATH");
if (PATH) {
const char *curr_path_start = PATH;
const char *curr_path_end;
while (curr_path_start && *curr_path_start) {
curr_path_end = strchr(curr_path_start, ':');
if (curr_path_end == NULL) {
result.assign(curr_path_start);
curr_path_start = NULL;
} else if (curr_path_end > curr_path_start) {
size_t len = curr_path_end - curr_path_start;
result.assign(curr_path_start, len);
curr_path_start += len + 1;
} else
break;
result += '/';
result += path;
struct stat s;
if (stat(result.c_str(), &s) == 0) {
::strlcpy(resolved_path, result.c_str(), resolved_path_size);
return result.size() + 1 < resolved_path_size;
}
}
}
}
return false;
}
bool DNBGetOSVersionNumbers(uint64_t *major, uint64_t *minor, uint64_t *patch) {
return MachProcess::GetOSVersionNumbers(major, minor, patch);
}
std::string DNBGetMacCatalystVersionString() {
return MachProcess::GetMacCatalystVersionString();
}
void DNBInitialize() {
DNBLogThreadedIf(LOG_PROCESS, "DNBInitialize ()");
#if defined(__i386__) || defined(__x86_64__)
DNBArchImplI386::Initialize();
DNBArchImplX86_64::Initialize();
#elif defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
DNBArchMachARM::Initialize();
DNBArchMachARM64::Initialize();
#endif
}
void DNBTerminate() {}
nub_bool_t DNBSetArchitecture(const char *arch) {
if (arch && arch[0]) {
if (strcasecmp(arch, "i386") == 0)
return DNBArchProtocol::SetArchitecture(CPU_TYPE_I386);
else if ((strcasecmp(arch, "x86_64") == 0) ||
(strcasecmp(arch, "x86_64h") == 0))
return DNBArchProtocol::SetArchitecture(CPU_TYPE_X86_64);
else if (strstr(arch, "arm64_32") == arch ||
strstr(arch, "aarch64_32") == arch)
return DNBArchProtocol::SetArchitecture(CPU_TYPE_ARM64_32);
else if (strstr(arch, "arm64") == arch || strstr(arch, "armv8") == arch ||
strstr(arch, "aarch64") == arch)
return DNBArchProtocol::SetArchitecture(CPU_TYPE_ARM64);
else if (strstr(arch, "arm") == arch)
return DNBArchProtocol::SetArchitecture(CPU_TYPE_ARM);
}
return false;
}
| {
"content_hash": "58562eb80d66788d0beb36ca04af9c7a",
"timestamp": "",
"source": "github",
"line_count": 1678,
"max_line_length": 80,
"avg_line_length": 33.035160905840286,
"alnum_prop": 0.620424656792885,
"repo_name": "llvm-mirror/lldb",
"id": "c9f2e34e2798ca5d9adeaa952ad066492265d437",
"size": "56752",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "tools/debugserver/source/DNB.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "131618"
},
{
"name": "C",
"bytes": "195293"
},
{
"name": "C++",
"bytes": "23346708"
},
{
"name": "CMake",
"bytes": "167302"
},
{
"name": "DTrace",
"bytes": "334"
},
{
"name": "LLVM",
"bytes": "6106"
},
{
"name": "Makefile",
"bytes": "50396"
},
{
"name": "Objective-C",
"bytes": "106956"
},
{
"name": "Objective-C++",
"bytes": "24806"
},
{
"name": "Perl",
"bytes": "72175"
},
{
"name": "Python",
"bytes": "3669886"
},
{
"name": "Shell",
"bytes": "6573"
},
{
"name": "Vim script",
"bytes": "8434"
}
],
"symlink_target": ""
} |
//
// HistoryViewController.m
// YLSY
//
// Created by 工业设计中意(湖南) on 14-4-21.
// Copyright (c) 2014年 中意工业设计(湖南)有限责任公司. All rights reserved.
//
#import "HistoryViewController.h"
@interface HistoryViewController ()
@end
@implementation HistoryViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
| {
"content_hash": "ce15b1e07dcaad93f3bed5bc8f059e19",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 102,
"avg_line_length": 22.020408163265305,
"alnum_prop": 0.7182576459684893,
"repo_name": "zyhndesign/YLSY_IOS",
"id": "c77b91586cec146a92e30e25cb8d8a052e643ce3",
"size": "1133",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "YLSY/YLSY/controllers/HistoryViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "147209"
},
{
"name": "Objective-C",
"bytes": "777769"
}
],
"symlink_target": ""
} |
package com.vl.samples.customcamera;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import com.vl.samples.R;
import com.vl.samples.gpsLocation.GPSLocation;
public class CustomCameraActivity extends Activity implements OnClickListener
{
private static final int CROP_IMAGE = 1;
private static boolean mIsCropLaunched = false;
private Button mSnap = null;
private Button mRetake = null;
private ImageView image = null;
private Camera mCamera = null;
private CameraPreview mPreview;
private int deviceHeight;
private File sdRoot;
private String dir;
private String fileName;
private ExifInterface exif;
private File pictureFile;
private Button mUse;
private GPSLocation mGpsLocation = null;
private Activity mContext ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_activity);
mContext = this;
//Initialize all UI elements
initUI();
}
/**
* Initialize all UI elements
*/
private void initUI()
{
// Setting all the path for the image
sdRoot = Environment.getExternalStorageDirectory();
dir = "/DCIM/Camera/";
mSnap = (Button) findViewById(R.id.buttonSnap);
mRetake = (Button) findViewById(R.id.buttonretake);
mUse = (Button) findViewById(R.id.buttonuse);
image = (ImageView) findViewById(R.id.imageViewSnap);
mSnap . setOnClickListener(this);
mRetake . setOnClickListener(this);
mUse . setOnClickListener(this);
}
private void createCamera() {
// Create an instance of Camera
mCamera = getCameraInstance();
// Setting the right parameters in the camera
Camera.Parameters params = mCamera.getParameters();
// params.setPictureSize(1600, 1200);
params.setPictureFormat(PixelFormat.JPEG);
params.setJpegQuality(100);
mCamera.setParameters(params);
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
// Calculating the width of the preview so it is proportional.
float widthFloat = (float) (deviceHeight) * 4 / 3;
int width = Math.round(widthFloat);
// Resizing the LinearLayout so we can make a proportional preview. This
// approach is not 100% perfect because on devices with a really small
// screen the the image will still be distorted - there is place for
// improvment.
// LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, deviceHeight);
// preview.setLayoutParams(layoutParams);
// Adding the camera preview after the FrameLayout and before the button
// as a separated element.
preview.addView(mPreview, 0);
}
@Override
protected void onResume() {
super.onResume();
// Test if there is a camera on the device and if the SD card is
// mounted.
if (!checkCameraHardware(this)) {
Intent i = new Intent(this, NoCamera.class);
startActivity(i);
finish();
} else if (!checkSDCard()) {
Intent i = new Intent(this, NoSDCard.class);
startActivity(i);
finish();
}
if(mCamera==null){
//Creating the camera
createCamera();
}
// Register this class as a listener for the accelerometer sensor
// sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
// release the camera immediately on pause event
releaseCamera();
// removing the inserted view - so when we come back to the app we
// won't have the views on top of each other.
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.removeViewAt(0);
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
private boolean checkSDCard() {
boolean state = false;
String sd = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(sd)) {
state = true;
}
return state;
}
/**
* A safe way to get an instance of the Camera object.
*/
public static Camera getCameraInstance() {
Camera c = null;
try {
// attempt to get a Camera instance
c = Camera.open();
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
// returns null if camera is unavailable
return c;
}
private PictureCallback mPicture = new PictureCallback() {
@SuppressLint("SdCardPath")
public void onPictureTaken(byte[] data, Camera camera){
mSnap.setVisibility(View.GONE);
mRetake.setVisibility(View.VISIBLE);
image.setVisibility(View.VISIBLE);
// File name of the image that we just took.
fileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()).toString() + ".jpg";
// Creating the directory where to save the image. Sadly in older
// version of Android we can not get the Media catalog name
File mkDir = new File(sdRoot, dir);
mkDir.mkdirs();
// Main file where to save the data that we recive from the camera
pictureFile = new File(sdRoot, dir + fileName);
FileOutputStream purge = null;
try {
purge = new FileOutputStream(pictureFile);
purge.write(data);
} catch (FileNotFoundException e) {
Log.d("DG_DEBUG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("DG_DEBUG", "Error accessing file: " + e.getMessage());
} finally{
if(purge!=null){
try {
purge.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Adding Exif data for the orientation. For some strange reason the
// ExifInterface class takes a string instead of a file.
try {
exif = new ExifInterface("/sdcard/" + dir + fileName);
exif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + ExifInterface.ORIENTATION_NORMAL);
exif.saveAttributes();
} catch (IOException e) {
e.printStackTrace();
}
////////////////////////////////////////////
try{
int angle = 90;
Matrix mat = new Matrix();
mat.postRotate(angle);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
options.inPurgeable = true;
options.inInputShareable = true;
// Bitmap bm = BitmapFactory.decodeFile("/sdcard/" + dir + fileName,options);
Bitmap bm = BitmapFactory.decodeStream(new FileInputStream(pictureFile), null, null);
Log.d("CameraActivity", "camera image dim>>w::"+bm.getWidth()+"//h::"+bm.getHeight());
Bitmap correctBmp = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), mat, true);
try {
FileOutputStream out = new FileOutputStream(pictureFile);
correctBmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
image.setImageBitmap(bm);
}
catch(OutOfMemoryError oom) {
Log.w("TAG", "-- OOM Error in setting image");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonSnap:
mCamera.takePicture(null, null, mPicture);
updateButtonsVisibility(true);
break;
case R.id.buttonretake:
updateButtonsVisibility(false);
// Deleting the image from the SD card/
File discardedPhoto = new File(sdRoot, dir + fileName);
discardedPhoto.delete();
// Restart the camera preview.
mCamera.startPreview();
mSnap.setVisibility(View.VISIBLE);
break;
case R.id.buttonuse:
performCropImage();
break;
default:
break;
}
}
private void updateButtonsVisibility(boolean visible){
mUse.setVisibility(visible?View.VISIBLE:View.INVISIBLE);
mRetake.setVisibility(visible?View.VISIBLE:View.INVISIBLE);
mSnap.setVisibility(visible?View.INVISIBLE:View.VISIBLE);
}
private Uri mCropImagedUri;
private void performCropImage(){
try{
//call the standard crop action intent (the user device may not support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri
cropIntent.setDataAndType(Uri.fromFile(pictureFile), "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 500 );
cropIntent.putExtra("outputY", 500 );
//retrieve data on return
cropIntent.putExtra("return-data", false);
mIsCropLaunched = true;
String cropfileName = "crop_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()).toString() + ".jpg";
File f = new File(sdRoot, dir + cropfileName);
try {
f.createNewFile();
} catch (IOException ex) {
Log.e("io", ex.getMessage());
}
mCropImagedUri = Uri.fromFile(f);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCropImagedUri);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, CROP_IMAGE);
}catch(ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CROP_IMAGE:
mIsCropLaunched = false;
if (resultCode == RESULT_OK) {
updateButtonsVisibility(false);
final Bundle extras = data.getExtras();
if (extras != null) {
// Bitmap photo = extras.getParcelable("data");
// image.setImageBitmap(photo);
//
// //Delete the original file and create new file with the cropped image
// File f = new File(sdRoot, dir + fileName);
// if (f.exists()) {
// f.delete();
// try {
// f.createNewFile();
// //Convert bitmap to byte array
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// photo.compress(CompressFormat.JPEG, 100 /*ignored for PNG*/, bos);
// byte[] bitmapdata = bos.toByteArray();
//
// //write the bytes in file
// FileOutputStream fos=null;
// try{
// fos = new FileOutputStream(f);
// fos.write(bitmapdata);
// }catch (Exception e) {
// e.printStackTrace();
// }finally{
// if(fos!=null){
// fos.close();
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
if(mCropImagedUri!=null)
image.setImageURI(mCropImagedUri);
}
}
break;
}
}
} | {
"content_hash": "10c5e2352922ba1ae176dbc631d270e7",
"timestamp": "",
"source": "github",
"line_count": 444,
"max_line_length": 137,
"avg_line_length": 27.46846846846847,
"alnum_prop": 0.6930141029845851,
"repo_name": "noundla/Sunny_android_samples",
"id": "2a55f52db6b9af9ce40a4fc3b1f5e948c577157e",
"size": "12196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/vl/samples/customcamera/CustomCameraActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "201784"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_60) on Tue Aug 26 20:50:07 PDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.cloud.OverseerCollectionProcessor (Solr 4.10.0 API)</title>
<meta name="date" content="2014-08-26">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.cloud.OverseerCollectionProcessor (Solr 4.10.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/cloud/OverseerCollectionProcessor.html" title="class in org.apache.solr.cloud">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/cloud/class-use/OverseerCollectionProcessor.html" target="_top">Frames</a></li>
<li><a href="OverseerCollectionProcessor.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.cloud.OverseerCollectionProcessor" class="title">Uses of Class<br>org.apache.solr.cloud.OverseerCollectionProcessor</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.cloud.OverseerCollectionProcessor</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/cloud/OverseerCollectionProcessor.html" title="class in org.apache.solr.cloud">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/cloud/class-use/OverseerCollectionProcessor.html" target="_top">Frames</a></li>
<li><a href="OverseerCollectionProcessor.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2014 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| {
"content_hash": "397c6b5f9af351ebecada625362997c5",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 161,
"avg_line_length": 37.343511450381676,
"alnum_prop": 0.6060915780866721,
"repo_name": "Ramzi-Alqrainy/SELK",
"id": "15cc58f496c5ceb9823427df610f1f260fbfb2f9",
"size": "4892",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "solr-4.10.0/docs/solr-core/org/apache/solr/cloud/class-use/OverseerCollectionProcessor.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "666490"
},
{
"name": "Erlang",
"bytes": "5309"
},
{
"name": "JavaScript",
"bytes": "1831427"
},
{
"name": "Ruby",
"bytes": "987996"
},
{
"name": "Shell",
"bytes": "78761"
},
{
"name": "XSLT",
"bytes": "126437"
}
],
"symlink_target": ""
} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dataproc/v1/jobs.proto
package com.google.cloud.dataproc.v1;
public interface DeleteJobRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.cloud.dataproc.v1.DeleteJobRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* [Required] The ID of the Google Cloud Platform project that the job
* belongs to.
* </pre>
*
* <code>optional string project_id = 1;</code>
*/
java.lang.String getProjectId();
/**
* <pre>
* [Required] The ID of the Google Cloud Platform project that the job
* belongs to.
* </pre>
*
* <code>optional string project_id = 1;</code>
*/
com.google.protobuf.ByteString
getProjectIdBytes();
/**
* <pre>
* [Required] The Cloud Dataproc region in which to handle the request.
* </pre>
*
* <code>optional string region = 3;</code>
*/
java.lang.String getRegion();
/**
* <pre>
* [Required] The Cloud Dataproc region in which to handle the request.
* </pre>
*
* <code>optional string region = 3;</code>
*/
com.google.protobuf.ByteString
getRegionBytes();
/**
* <pre>
* [Required] The job ID.
* </pre>
*
* <code>optional string job_id = 2;</code>
*/
java.lang.String getJobId();
/**
* <pre>
* [Required] The job ID.
* </pre>
*
* <code>optional string job_id = 2;</code>
*/
com.google.protobuf.ByteString
getJobIdBytes();
}
| {
"content_hash": "88e5cb6ce4818c660b4f56357c2d90d2",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 92,
"avg_line_length": 23.353846153846153,
"alnum_prop": 0.6212121212121212,
"repo_name": "speedycontrol/googleapis",
"id": "87a09313e1f097c580cd2b93fe9fad76dda834e6",
"size": "1518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "output/com/google/cloud/dataproc/v1/DeleteJobRequestOrBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1569787"
},
{
"name": "Makefile",
"bytes": "1301"
},
{
"name": "Protocol Buffer",
"bytes": "1085800"
}
],
"symlink_target": ""
} |
(function ($) {
$.fn.extend({
notify: function (options) {
var settings = $.extend({ type: 'sticky', speed: 500, onDemandButtonHeight: 35 }, options);
return this.each(function () {
var wrapper = $(this);
var ondemandBtn = $('.ondemand-button');
var dh = -35;
var w = wrapper.outerWidth() - ondemandBtn.outerWidth();
ondemandBtn.css('left', w).css('margin-top', dh + "px" );
var h = -wrapper.outerHeight();
wrapper.addClass(settings.type).css('margin-top', h).addClass('visible').removeClass('hide');
if (settings.type != 'ondemand') {
wrapper.stop(true, false).animate({ marginTop: 0 }, settings.speed);
}
else {
ondemandBtn.stop(true, false).animate({ marginTop: 0 }, settings.speed);
}
var closeBtn = $('.close', wrapper);
closeBtn.click(function () {
if (settings.type == 'ondemand') {
wrapper.stop(true, false).animate({ marginTop: h }, settings.speed, function () {
wrapper.removeClass('visible').addClass('hide');
ondemandBtn.stop(true, false).animate({ marginTop: 0 }, settings.speed);
});
}
else {
wrapper.stop(true, false).animate({ marginTop: h }, settings.speed, function () {
wrapper.removeClass('visible').addClass('hide');
});
}
});
if (settings.type == 'floated') {
$(document).scroll(function (e) {
wrapper.stop(true, false).animate({ top: $(document).scrollTop() }, settings.speed);
}).resize(function (e) {
wrapper.stop(true, false).animate({ top: $(document).scrollTop() }, settings.speed);
});
}
else if (settings.type == 'ondemand') {
ondemandBtn.click(function () {
$(this).animate({ marginTop: dh }, settings.speed, function () {
wrapper.removeClass('hide').addClass('visible').animate({ marginTop: 0 }, settings.speed, function () {
});
})
});
}
});
}
});
})(jQuery);
| {
"content_hash": "6b66d16c3178e1b457cda87db3fefff6",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 131,
"avg_line_length": 47.236363636363635,
"alnum_prop": 0.4380292532717475,
"repo_name": "walkor/web-msg-sender",
"id": "b1228dad7f8bdad23161bfdee8526aae6844907b",
"size": "2598",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "web/notify.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "48"
},
{
"name": "PHP",
"bytes": "18769"
}
],
"symlink_target": ""
} |
/* @flow */
import React, { Component } from 'react';
import { translate } from '../../base/i18n';
/**
* The type of the React {@code Component} props of {@link SpeakerStatsLabels}.
*/
type Props = {
/**
* The function to translate human-readable text.
*/
t: Function
};
/**
* React component for labeling speaker stats column items.
*
* @extends Component
*/
class SpeakerStatsLabels extends Component<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { t } = this.props;
return (
<div className = 'speaker-stats-item__labels'>
<div className = 'speaker-stats-item__status' />
<div className = 'speaker-stats-item__name'>
{ t('speakerStats.name') }
</div>
<div className = 'speaker-stats-item__time'>
{ t('speakerStats.speakerTime') }
</div>
</div>
);
}
}
export default translate(SpeakerStatsLabels);
| {
"content_hash": "d54cd274b99016e528d2b241aa034da8",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 79,
"avg_line_length": 23.680851063829788,
"alnum_prop": 0.5363881401617251,
"repo_name": "bgrozev/jitsi-meet",
"id": "3e2e467b6d3bf5d5fcb85584e870d1c50d774a5f",
"size": "1113",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "react/features/speaker-stats/components/SpeakerStatsLabels.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "160916"
},
{
"name": "HTML",
"bytes": "16058"
},
{
"name": "Java",
"bytes": "226322"
},
{
"name": "JavaScript",
"bytes": "3344142"
},
{
"name": "Lua",
"bytes": "135705"
},
{
"name": "Makefile",
"bytes": "2797"
},
{
"name": "Objective-C",
"bytes": "116779"
},
{
"name": "Ruby",
"bytes": "7967"
},
{
"name": "Shell",
"bytes": "27391"
},
{
"name": "Starlark",
"bytes": "152"
},
{
"name": "Swift",
"bytes": "44491"
}
],
"symlink_target": ""
} |
/* $Id: sslreveal.c,v 1.4 2004/04/27 23:04:39 gerv%gerv.net Exp $ */
#include "cert.h"
#include "ssl.h"
#include "certt.h"
#include "sslimpl.h"
/* given PRFileDesc, returns a copy of certificate associated with the socket
* the caller should delete the cert when done with SSL_DestroyCertificate
*/
CERTCertificate *
SSL_RevealCert(PRFileDesc * fd)
{
CERTCertificate * cert = NULL;
sslSocket * sslsocket = NULL;
sslsocket = ssl_FindSocket(fd);
/* CERT_DupCertificate increases reference count and returns pointer to
* the same cert
*/
if (sslsocket && sslsocket->sec.peerCert)
cert = CERT_DupCertificate(sslsocket->sec.peerCert);
return cert;
}
/* given PRFileDesc, returns a pointer to PinArg associated with the socket
*/
void *
SSL_RevealPinArg(PRFileDesc * fd)
{
sslSocket * sslsocket = NULL;
void * PinArg = NULL;
sslsocket = ssl_FindSocket(fd);
/* is pkcs11PinArg part of the sslSocket or sslSecurityInfo ? */
if (sslsocket)
PinArg = sslsocket->pkcs11PinArg;
return PinArg;
}
/* given PRFileDesc, returns a pointer to the URL associated with the socket
* the caller should free url when done
*/
char *
SSL_RevealURL(PRFileDesc * fd)
{
sslSocket * sslsocket = NULL;
char * url = NULL;
sslsocket = ssl_FindSocket(fd);
if (sslsocket && sslsocket->url)
url = PL_strdup(sslsocket->url);
return url;
}
| {
"content_hash": "bc5da016e2069294f8029651164137a9",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 77,
"avg_line_length": 22.142857142857142,
"alnum_prop": 0.6903225806451613,
"repo_name": "rwatson/chromium-capsicum",
"id": "a981deeb4a3392d07a9cf5db0044cbb92ab45870",
"size": "3173",
"binary": false,
"copies": "2",
"ref": "refs/heads/chromium-capsicum",
"path": "net/third_party/nss/ssl/sslreveal.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package org.bfn.ninetynineprobs
import org.scalatest._
class P36Spec extends UnitSpec {
// TODO
}
| {
"content_hash": "11f1ecc660850117a615bb391ce29388",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 32,
"avg_line_length": 10.5,
"alnum_prop": 0.7333333333333333,
"repo_name": "bfontaine/99Scala",
"id": "876428d6e2a2e9e0731f9fa3c861309be7f45c9e",
"size": "105",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/scala/P36Spec.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Scala",
"bytes": "57613"
}
],
"symlink_target": ""
} |
<?php namespace PCI\Models;
use PCI\Models\Traits\HasIdUID;
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
/**
* PCI\Models\StockDetail
*
* @property integer $id
* @property integer $stock_id
* @property float $quantity
* @property \Carbon\Carbon $due
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
* @property integer $created_by
* @property integer $updated_by
* @property-read Stock $stock
* @method static \Illuminate\Database\Query\Builder|\PCI\Models\StockDetail whereId($value)
* @method static \Illuminate\Database\Query\Builder|\PCI\Models\StockDetail whereStockId($value)
* @method static \Illuminate\Database\Query\Builder|\PCI\Models\StockDetail whereQuantity($value)
* @method static \Illuminate\Database\Query\Builder|\PCI\Models\StockDetail whereDue($value)
* @method static \Illuminate\Database\Query\Builder|\PCI\Models\StockDetail whereCreatedAt($value)
* @method static \Illuminate\Database\Query\Builder|\PCI\Models\StockDetail whereUpdatedAt($value)
* @method static \Illuminate\Database\Query\Builder|\PCI\Models\StockDetail whereCreatedBy($value)
* @method static \Illuminate\Database\Query\Builder|\PCI\Models\StockDetail whereUpdatedBy($value)
*/
class StockDetail extends AbstractBaseModel
{
use HasIdUID;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'due',
'quantity'
];
/**
* Atributos que deben ser mutados a dates.
* dates se refiere a Carbon\Carbon dates.
*
* @var array
*/
protected $dates = ['due'];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo|\Illuminate\Database\Eloquent\Builder
*/
public function stock()
{
return $this->belongsTo(Stock::class);
}
}
| {
"content_hash": "ae3f16ab4eaff9d82090ad12bb41878b",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 102,
"avg_line_length": 31.810344827586206,
"alnum_prop": 0.7078590785907859,
"repo_name": "slayerfat/sistemaPCI",
"id": "e0e0b8a94d6978eb446c088203bd0544530ecb55",
"size": "1845",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/Models/StockDetail.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "412"
},
{
"name": "CSS",
"bytes": "14654"
},
{
"name": "JavaScript",
"bytes": "11249"
},
{
"name": "PHP",
"bytes": "1153128"
},
{
"name": "Shell",
"bytes": "3728"
},
{
"name": "TypeScript",
"bytes": "37265"
}
],
"symlink_target": ""
} |
<component name="ProjectDictionaryState">
<dictionary name="devinstafford" />
</component> | {
"content_hash": "2b86101c71714e53b73a0008a630dd00",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 41,
"avg_line_length": 30.666666666666668,
"alnum_prop": 0.7717391304347826,
"repo_name": "dvsd/Completum",
"id": "0a4f58eae1bf511bcf65eaf5fad27c87cefbf183",
"size": "92",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/dictionaries/devinstafford.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "42790"
}
],
"symlink_target": ""
} |
package org.apache.bookkeeper.client;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.bookkeeper.net.BookieSocketAddress;
import org.apache.bookkeeper.net.NetworkTopology;
import org.apache.bookkeeper.net.NodeBase;
import org.apache.bookkeeper.stats.AlertStatsLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
abstract class TopologyAwareEnsemblePlacementPolicy implements ITopologyAwareEnsemblePlacementPolicy<TopologyAwareEnsemblePlacementPolicy.BookieNode> {
static final Logger LOG = LoggerFactory.getLogger(TopologyAwareEnsemblePlacementPolicy.class);
protected static class TruePredicate implements Predicate<BookieNode> {
public static final TruePredicate instance = new TruePredicate();
@Override
public boolean apply(BookieNode candidate, Ensemble chosenNodes) {
return true;
}
}
protected static class EnsembleForReplacementWithNoConstraints implements Ensemble<BookieNode> {
public static final EnsembleForReplacementWithNoConstraints instance = new EnsembleForReplacementWithNoConstraints();
static final ArrayList<BookieSocketAddress> EMPTY_LIST = new ArrayList<BookieSocketAddress>(0);
@Override
public boolean addNode(BookieNode node) {
// do nothing
return true;
}
@Override
public ArrayList<BookieSocketAddress> toList() {
return EMPTY_LIST;
}
/**
* Validates if an ensemble is valid
*
* @return true if the ensemble is valid; false otherwise
*/
@Override
public boolean validate() {
return true;
}
}
protected static class BookieNode extends NodeBase {
private final BookieSocketAddress addr; // identifier of a bookie node.
BookieNode(BookieSocketAddress addr, String networkLoc) {
super(addr.toString(), networkLoc);
this.addr = addr;
}
public BookieSocketAddress getAddr() {
return addr;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BookieNode)) {
return false;
}
BookieNode other = (BookieNode) obj;
return getName().equals(other.getName());
}
@Override
public String toString() {
return String.format("<Bookie:%s>", name);
}
}
/**
* A predicate checking the rack coverage for write quorum in {@link RoundRobinDistributionSchedule},
* which ensures that a write quorum should be covered by at least two racks.
*/
protected static class RRTopologyAwareCoverageEnsemble implements Predicate<BookieNode>, Ensemble<BookieNode> {
protected interface CoverageSet {
boolean apply(BookieNode candidate);
void addBookie(BookieNode candidate);
public CoverageSet duplicate();
}
protected class RackQuorumCoverageSet implements CoverageSet {
HashSet<String> racksOrRegionsInQuorum = new HashSet<String>();
int seenBookies = 0;
@Override
public boolean apply(BookieNode candidate) {
// If we don't have sufficient members in the write quorum; then we cant enforce
// rack/region diversity
if (writeQuorumSize < 2) {
return true;
}
if (seenBookies + 1 == writeQuorumSize) {
return racksOrRegionsInQuorum.size() > (racksOrRegionsInQuorum.contains(candidate.getNetworkLocation(distanceFromLeaves)) ? 1 : 0);
}
return true;
}
@Override
public void addBookie(BookieNode candidate) {
++seenBookies;
racksOrRegionsInQuorum.add(candidate.getNetworkLocation(distanceFromLeaves));
}
@Override
public RackQuorumCoverageSet duplicate() {
RackQuorumCoverageSet ret = new RackQuorumCoverageSet();
ret.racksOrRegionsInQuorum = Sets.newHashSet(this.racksOrRegionsInQuorum);
ret.seenBookies = this.seenBookies;
return ret;
}
}
protected class RackOrRegionDurabilityCoverageSet implements CoverageSet {
HashMap<String, Integer> allocationToRacksOrRegions = new HashMap<String, Integer>();
RackOrRegionDurabilityCoverageSet() {
for (String rackOrRegion: racksOrRegions) {
allocationToRacksOrRegions.put(rackOrRegion, 0);
}
}
@Override
public RackOrRegionDurabilityCoverageSet duplicate() {
RackOrRegionDurabilityCoverageSet ret = new RackOrRegionDurabilityCoverageSet();
ret.allocationToRacksOrRegions = Maps.newHashMap(this.allocationToRacksOrRegions);
return ret;
}
private boolean checkSumOfSubsetWithinLimit(final Set<String> includedRacksOrRegions,
final Set<String> remainingRacksOrRegions,
int subsetSize,
int maxAllowedSum) {
if (remainingRacksOrRegions.isEmpty() || (subsetSize <= 0)) {
if (maxAllowedSum < 0) {
LOG.trace("CHECK FAILED: RacksOrRegions Included {} Remaining {}, subsetSize {}, maxAllowedSum {}", new Object[]{
includedRacksOrRegions, remainingRacksOrRegions, subsetSize, maxAllowedSum
});
}
return (maxAllowedSum >= 0);
}
for(String rackOrRegion: remainingRacksOrRegions) {
Integer currentAllocation = allocationToRacksOrRegions.get(rackOrRegion);
if (currentAllocation == null) {
allocationToRacksOrRegions.put(rackOrRegion, 0);
currentAllocation = 0;
}
if (currentAllocation > maxAllowedSum) {
LOG.trace("CHECK FAILED: RacksOrRegions Included {} Candidate {}, subsetSize {}, maxAllowedSum {}", new Object[]{
includedRacksOrRegions, rackOrRegion, subsetSize, maxAllowedSum
});
return false;
} else {
Set<String> remainingElements = new HashSet<String>(remainingRacksOrRegions);
Set<String> includedElements = new HashSet<String>(includedRacksOrRegions);
includedElements.add(rackOrRegion);
remainingElements.remove(rackOrRegion);
if (!checkSumOfSubsetWithinLimit(includedElements,
remainingElements,
subsetSize - 1,
maxAllowedSum - currentAllocation)) {
return false;
}
}
}
return true;
}
@Override
public boolean apply(BookieNode candidate) {
if (minRacksOrRegionsForDurability <= 1) {
return true;
}
String candidateRackOrRegion = candidate.getNetworkLocation(distanceFromLeaves);
candidateRackOrRegion = candidateRackOrRegion.startsWith(NodeBase.PATH_SEPARATOR_STR) ? candidateRackOrRegion.substring(1) : candidateRackOrRegion;
final Set<String> remainingRacksOrRegions = new HashSet<String>(racksOrRegions);
remainingRacksOrRegions.remove(candidateRackOrRegion);
final Set<String> includedRacksOrRegions = new HashSet<String>();
includedRacksOrRegions.add(candidateRackOrRegion);
// If minRacksOrRegionsForDurability are required for durability; we must ensure that
// no subset of (minRacksOrRegionsForDurability - 1) regions have ackQuorumSize
// We are only modifying candidateRackOrRegion if we accept this bookie, so lets only
// find sets that contain this candidateRackOrRegion
Integer currentAllocation = allocationToRacksOrRegions.get(candidateRackOrRegion);
if (currentAllocation == null) {
LOG.info("Detected a region that was not initialized {}", candidateRackOrRegion);
if (null != alertStatsLogger) {
if (candidateRackOrRegion.equals(NetworkTopology.DEFAULT_REGION)) {
alertStatsLogger.raise("Failed to resolve network location {}", candidate);
} else if (!racksOrRegions.contains(candidateRackOrRegion)) {
alertStatsLogger.raise("Unknown region detected {}", candidateRackOrRegion);
}
}
allocationToRacksOrRegions.put(candidateRackOrRegion, 0);
currentAllocation = 0;
}
int inclusiveLimit = (ackQuorumSize - 1) - (currentAllocation + 1);
return checkSumOfSubsetWithinLimit(includedRacksOrRegions,
remainingRacksOrRegions, minRacksOrRegionsForDurability - 2, inclusiveLimit);
}
@Override
public void addBookie(BookieNode candidate) {
String candidateRackOrRegion = candidate.getNetworkLocation(distanceFromLeaves);
candidateRackOrRegion = candidateRackOrRegion.startsWith(NodeBase.PATH_SEPARATOR_STR) ? candidateRackOrRegion.substring(1) : candidateRackOrRegion;
int oldCount = 0;
if (null != allocationToRacksOrRegions.get(candidateRackOrRegion)) {
oldCount = allocationToRacksOrRegions.get(candidateRackOrRegion);
}
allocationToRacksOrRegions.put(candidateRackOrRegion, oldCount + 1);
}
}
final int distanceFromLeaves;
final int ensembleSize;
final int writeQuorumSize;
final int ackQuorumSize;
final int minRacksOrRegionsForDurability;
final ArrayList<BookieNode> chosenNodes;
final Set<String> racksOrRegions;
final AlertStatsLogger alertStatsLogger;
private final CoverageSet[] quorums;
final Predicate<BookieNode> parentPredicate;
final Ensemble<BookieNode> parentEnsemble;
protected RRTopologyAwareCoverageEnsemble(RRTopologyAwareCoverageEnsemble that) {
this.distanceFromLeaves = that.distanceFromLeaves;
this.ensembleSize = that.ensembleSize;
this.writeQuorumSize = that.writeQuorumSize;
this.ackQuorumSize = that.ackQuorumSize;
this.alertStatsLogger = that.alertStatsLogger;
this.chosenNodes = Lists.newArrayList(that.chosenNodes);
this.quorums = new CoverageSet[that.quorums.length];
for (int i = 0; i < that.quorums.length; i++) {
if (null != that.quorums[i]) {
this.quorums[i] = that.quorums[i].duplicate();
} else {
this.quorums[i] = null;
}
}
this.parentPredicate = that.parentPredicate;
this.parentEnsemble = that.parentEnsemble;
if (null != that.racksOrRegions) {
this.racksOrRegions = new HashSet<String>(that.racksOrRegions);
} else {
this.racksOrRegions = null;
}
this.minRacksOrRegionsForDurability = that.minRacksOrRegionsForDurability;
}
protected RRTopologyAwareCoverageEnsemble(int ensembleSize,
int writeQuorumSize,
int ackQuorumSize,
int distanceFromLeaves,
Set<String> racksOrRegions,
int minRacksOrRegionsForDurability,
AlertStatsLogger alertStatsLogger) {
this(ensembleSize, writeQuorumSize, ackQuorumSize, distanceFromLeaves, null, null,
racksOrRegions, minRacksOrRegionsForDurability, alertStatsLogger);
}
protected RRTopologyAwareCoverageEnsemble(int ensembleSize,
int writeQuorumSize,
int ackQuorumSize,
int distanceFromLeaves,
Ensemble<BookieNode> parentEnsemble,
Predicate<BookieNode> parentPredicate,
AlertStatsLogger alertStatsLogger) {
this(ensembleSize, writeQuorumSize, ackQuorumSize, distanceFromLeaves, parentEnsemble, parentPredicate,
null, 0, alertStatsLogger);
}
protected RRTopologyAwareCoverageEnsemble(int ensembleSize,
int writeQuorumSize,
int ackQuorumSize,
int distanceFromLeaves,
Ensemble<BookieNode> parentEnsemble,
Predicate<BookieNode> parentPredicate,
Set<String> racksOrRegions,
int minRacksOrRegionsForDurability,
AlertStatsLogger alertStatsLogger) {
this.ensembleSize = ensembleSize;
this.writeQuorumSize = writeQuorumSize;
this.ackQuorumSize = ackQuorumSize;
this.distanceFromLeaves = distanceFromLeaves;
this.alertStatsLogger = alertStatsLogger;
this.chosenNodes = new ArrayList<BookieNode>(ensembleSize);
if (minRacksOrRegionsForDurability > 0) {
this.quorums = new RackOrRegionDurabilityCoverageSet[ensembleSize];
} else {
this.quorums = new RackQuorumCoverageSet[ensembleSize];
}
this.parentEnsemble = parentEnsemble;
this.parentPredicate = parentPredicate;
this.racksOrRegions = racksOrRegions;
this.minRacksOrRegionsForDurability = minRacksOrRegionsForDurability;
}
@Override
public boolean apply(BookieNode candidate, Ensemble<BookieNode> ensemble) {
if (ensemble != this) {
return false;
}
// An ensemble cannot contain the same node twice
if (chosenNodes.contains(candidate)) {
return false;
}
// candidate position
if ((ensembleSize == writeQuorumSize) && (minRacksOrRegionsForDurability > 0)) {
if (null == quorums[0]) {
quorums[0] = new RackOrRegionDurabilityCoverageSet();
}
if (!quorums[0].apply(candidate)) {
return false;
}
} else {
int candidatePos = chosenNodes.size();
int startPos = candidatePos - writeQuorumSize + 1;
for (int i = startPos; i <= candidatePos; i++) {
int idx = (i + ensembleSize) % ensembleSize;
if (null == quorums[idx]) {
if (minRacksOrRegionsForDurability > 0) {
quorums[idx] = new RackOrRegionDurabilityCoverageSet();
} else {
quorums[idx] = new RackQuorumCoverageSet();
}
}
if (!quorums[idx].apply(candidate)) {
return false;
}
}
}
return ((null == parentPredicate) || parentPredicate.apply(candidate, parentEnsemble));
}
@Override
public boolean addNode(BookieNode node) {
// An ensemble cannot contain the same node twice
if (chosenNodes.contains(node)) {
return false;
}
if ((ensembleSize == writeQuorumSize) && (minRacksOrRegionsForDurability > 0)) {
if (null == quorums[0]) {
quorums[0] = new RackOrRegionDurabilityCoverageSet();
}
quorums[0].addBookie(node);
} else {
int candidatePos = chosenNodes.size();
int startPos = candidatePos - writeQuorumSize + 1;
for (int i = startPos; i <= candidatePos; i++) {
int idx = (i + ensembleSize) % ensembleSize;
if (null == quorums[idx]) {
if (minRacksOrRegionsForDurability > 0) {
quorums[idx] = new RackOrRegionDurabilityCoverageSet();
} else {
quorums[idx] = new RackQuorumCoverageSet();
}
}
quorums[idx].addBookie(node);
}
}
chosenNodes.add(node);
return ((null == parentEnsemble) || parentEnsemble.addNode(node));
}
@Override
public ArrayList<BookieSocketAddress> toList() {
ArrayList<BookieSocketAddress> addresses = new ArrayList<BookieSocketAddress>(ensembleSize);
for (BookieNode bn : chosenNodes) {
addresses.add(bn.getAddr());
}
return addresses;
}
/**
* Validates if an ensemble is valid
*
* @return true if the ensemble is valid; false otherwise
*/
@Override
public boolean validate() {
HashSet<BookieSocketAddress> addresses = new HashSet<BookieSocketAddress>(ensembleSize);
HashSet<String> racksOrRegions = new HashSet<String>();
for (BookieNode bn : chosenNodes) {
if (addresses.contains(bn.getAddr())) {
return false;
}
addresses.add(bn.getAddr());
racksOrRegions.add(bn.getNetworkLocation(distanceFromLeaves));
}
return ((minRacksOrRegionsForDurability == 0) ||
(racksOrRegions.size() >= minRacksOrRegionsForDurability));
}
@Override
public String toString() {
return chosenNodes.toString();
}
}
@Override
public List<Integer> reorderReadSequence(ArrayList<BookieSocketAddress> ensemble, List<Integer> writeSet, Map<BookieSocketAddress, Long> bookieFailureHistory) {
return writeSet;
}
@Override
public List<Integer> reorderReadLACSequence(ArrayList<BookieSocketAddress> ensemble, List<Integer> writeSet, Map<BookieSocketAddress, Long> bookieFailureHistory) {
List<Integer> retList = new ArrayList<Integer>(reorderReadSequence(ensemble, writeSet, bookieFailureHistory));
if (retList.size() < ensemble.size()) {
for (int i = 0; i < ensemble.size(); i++) {
if (!retList.contains(i)) {
retList.add(i);
}
}
}
return retList;
}
}
| {
"content_hash": "a4df1f603bb63015a42b581bf59aebb5",
"timestamp": "",
"source": "github",
"line_count": 459,
"max_line_length": 167,
"avg_line_length": 43.830065359477125,
"alnum_prop": 0.5610398647976936,
"repo_name": "arvindkandhare/bookkeeper",
"id": "4558bdf064711995abc9d401f2265659ff2da305",
"size": "20118",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "bookkeeper-server/src/main/java/org/apache/bookkeeper/client/TopologyAwareEnsemblePlacementPolicy.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3546"
},
{
"name": "C++",
"bytes": "323853"
},
{
"name": "CMake",
"bytes": "11444"
},
{
"name": "Java",
"bytes": "4820783"
},
{
"name": "M4",
"bytes": "42120"
},
{
"name": "Makefile",
"bytes": "4852"
},
{
"name": "Protocol Buffer",
"bytes": "15021"
},
{
"name": "Shell",
"bytes": "106302"
}
],
"symlink_target": ""
} |
#ifndef _NET_CONFIG_H
#define _NET_CONFIG_H
//Trace level for TCP/IP stack debugging
#define MEM_TRACE_LEVEL 4
#define NIC_TRACE_LEVEL 4
#define ETH_TRACE_LEVEL 2
#define ARP_TRACE_LEVEL 2
#define IP_TRACE_LEVEL 2
#define IPV4_TRACE_LEVEL 2
#define IPV6_TRACE_LEVEL 2
#define ICMP_TRACE_LEVEL 2
#define IGMP_TRACE_LEVEL 4
#define ICMPV6_TRACE_LEVEL 2
#define MLD_TRACE_LEVEL 4
#define NDP_TRACE_LEVEL 4
#define UDP_TRACE_LEVEL 2
#define TCP_TRACE_LEVEL 2
#define SOCKET_TRACE_LEVEL 2
#define RAW_SOCKET_TRACE_LEVEL 2
#define BSD_SOCKET_TRACE_LEVEL 2
#define SLAAC_TRACE_LEVEL 5
#define DHCP_TRACE_LEVEL 4
#define DHCPV6_TRACE_LEVEL 4
#define DNS_TRACE_LEVEL 4
#define MDNS_TRACE_LEVEL 4
#define NBNS_TRACE_LEVEL 2
#define LLMNR_TRACE_LEVEL 4
#define FTP_TRACE_LEVEL 5
#define HTTP_TRACE_LEVEL 4
#define SMTP_TRACE_LEVEL 5
#define SNTP_TRACE_LEVEL 4
#define STD_SERVICES_TRACE_LEVEL 5
//Number of network adapters
#define NET_INTERFACE_COUNT 1
//Maximum size of the MAC filter table
#define MAC_FILTER_MAX_SIZE 16
//IPv4 support
#define IPV4_SUPPORT ENABLED
//Maximum size of the IPv4 filter table
#define IPV4_FILTER_MAX_SIZE 8
//IPv4 fragmentation support
#define IPV4_FRAG_SUPPORT ENABLED
//Maximum number of fragmented packets the host will accept
//and hold in the reassembly queue simultaneously
#define IPV4_MAX_FRAG_DATAGRAMS 4
//Maximum datagram size the host will accept when reassembling fragments
#define IPV4_MAX_FRAG_DATAGRAM_SIZE 8192
//Size of ARP cache
#define ARP_CACHE_SIZE 8
//Maximum number of packets waiting for address resolution to complete
#define ARP_MAX_PENDING_PACKETS 2
//IGMP support
#define IGMP_SUPPORT ENABLED
//IPv6 support
#define IPV6_SUPPORT ENABLED
//Maximum size of the IPv6 filter table
#define IPV6_FILTER_MAX_SIZE 8
//IPv6 fragmentation support
#define IPV6_FRAG_SUPPORT ENABLED
//Maximum number of fragmented packets the host will accept
//and hold in the reassembly queue simultaneously
#define IPV6_MAX_FRAG_DATAGRAMS 4
//Maximum datagram size the host will accept when reassembling fragments
#define IPV6_MAX_FRAG_DATAGRAM_SIZE 8192
//MLD support
#define MLD_SUPPORT ENABLED
//Neighbor cache size
#define NDP_CACHE_SIZE 8
//Maximum number of packets waiting for address resolution to complete
#define NDP_MAX_PENDING_PACKETS 2
//TCP support
#define TCP_SUPPORT ENABLED
//Default buffer size for transmission
#define TCP_DEFAULT_TX_BUFFER_SIZE (1430*2)
//Default buffer size for reception
#define TCP_DEFAULT_RX_BUFFER_SIZE (1430*2)
//Default SYN queue size for listening sockets
#define TCP_DEFAULT_SYN_QUEUE_SIZE 4
//Maximum number of retransmissions
#define TCP_MAX_RETRIES 5
//Selective acknowledgment support
#define TCP_SACK_SUPPORT DISABLED
//UDP support
#define UDP_SUPPORT ENABLED
//Receive queue depth for connectionless sockets
#define UDP_RX_QUEUE_SIZE 4
//Raw socket support
#define RAW_SOCKET_SUPPORT DISABLED
//Receive queue depth for raw sockets
#define RAW_SOCKET_RX_QUEUE_SIZE 4
//Number of sockets that can be opened simultaneously
#define SOCKET_MAX_COUNT 8
//Server Side Includes support
#define HTTP_SERVER_SSI_SUPPORT ENABLED
#endif
| {
"content_hash": "8bd3c3fa4574b1e20077d68a666fafb6",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 72,
"avg_line_length": 29.263157894736842,
"alnum_prop": 0.7383093525179856,
"repo_name": "miragecentury/M2_SE_RTOS_Project",
"id": "55039c3327e08c66ed9d42b10b8109cf40c6660c",
"size": "4341",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Project/LPC1549_Keil/CycloneTCP_SSL_Crypto_Open_1_6_4/demo/olimex/str_e912/web_server_demo/src/net_config.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3487996"
},
{
"name": "Batchfile",
"bytes": "24092"
},
{
"name": "C",
"bytes": "84242987"
},
{
"name": "C++",
"bytes": "11815227"
},
{
"name": "CSS",
"bytes": "228804"
},
{
"name": "D",
"bytes": "102276"
},
{
"name": "HTML",
"bytes": "97193"
},
{
"name": "JavaScript",
"bytes": "233480"
},
{
"name": "Makefile",
"bytes": "3365112"
},
{
"name": "Objective-C",
"bytes": "46531"
},
{
"name": "Python",
"bytes": "3237"
},
{
"name": "Shell",
"bytes": "13510"
}
],
"symlink_target": ""
} |
<?php if ( !defined( 'HABARI_PATH' ) ) { die('No direct access'); } ?>
<?php include('header.php'); ?>
<div class="comment form">
<?php $form->out(); ?>
</div>
<?php include('footer.php'); ?>
| {
"content_hash": "ed779eb2c2ea170e5cb9717f04263d9c",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 70,
"avg_line_length": 27.714285714285715,
"alnum_prop": 0.5618556701030928,
"repo_name": "nerdfiles/habari_boilerplate",
"id": "49d75440f3826d2c43b6f17f98622754e8dcb583",
"size": "194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "system/admin/comment.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "100257"
},
{
"name": "PHP",
"bytes": "1534650"
},
{
"name": "Ruby",
"bytes": "861"
}
],
"symlink_target": ""
} |
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Filip Konvicka <[email protected]>
* Lubomir Moric <[email protected]>
* Vincent Barichard <[email protected]>
*
* Contributing authors:
* Christian Schulte <[email protected]>
*
* Copyright:
* LOGIS, s.r.o., 2008
* Christian Schulte, 2010
* Vincent Barichard, 2012
*
* Last modified:
* $Date: 2013-02-04 17:54:05 +0100 (må, 04 feb 2013) $ by $Author: schulte $
* $Revision: 13260 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <cmath>
namespace Gecode { namespace Float {
class FloatVarImp;
/// Float delta information for advisors
class FloatDelta : public Delta {
friend class FloatVarImp;
private:
FloatNum _min; ///< Minimum value just pruned
FloatNum _max; ///< Largest value just pruned
public:
/// Create float delta as providing no information
FloatDelta(void);
/// Create float delta with \a min and \a max
FloatDelta(FloatNum min, FloatNum max);
private:
/// Return minimum
FloatNum min(void) const;
/// Return maximum
FloatNum max(void) const;
};
}}
#include <gecode/float/var-imp/delta.hpp>
namespace Gecode { namespace Float {
/**
* \brief Float variable implementation
*
* \ingroup Other
*/
class FloatVarImp : public FloatVarImpBase {
protected:
/// Domain information
FloatVal dom;
/// Constructor for cloning \a x
FloatVarImp(Space& home, bool share, FloatVarImp& x);
public:
/// Initialize with interval \a d
FloatVarImp(Space& home, const FloatVal& d);
/// \name Value access
//@{
/// Return domain
FloatVal domain(void) const;
/// Return minimum of domain
FloatNum min(void) const;
/// Return maximum of domain
FloatNum max(void) const;
/// Return value of domain (only if assigned)
FloatVal val(void) const;
/// Return median of domain (closest representation)
FloatNum med(void) const;
/// Return width of domain (distance between maximum and minimum)
FloatNum size(void) const;
//@}
/// \name Domain tests
//@{
/// Test whether variable is assigned
bool assigned(void) const;
/// Test whether 0 is contained in domain
bool zero_in(void) const;
/// Test whether \a n is contained in domain
bool in(FloatNum n) const;
/// Test whether \a n is contained in domain
bool in(const FloatVal& n) const;
//@}
/// \name Domain update by value
//@{
/// Restrict domain values to be equal to \a n
ModEvent eq(Space& home, FloatNum n);
/// Restrict domain values to be equal to \a n
ModEvent eq(Space& home, const FloatVal& n);
/// Restrict domain values to be less or equal than \a n
ModEvent lq(Space& home, FloatNum n);
/// Restrict domain values to be less or equal than \a n
ModEvent lq(Space& home, const FloatVal& n);
/// Restrict domain values to be greater or equal than \a n
ModEvent gq(Space& home, FloatNum n);
/// Restrict domain values to be greater or equal than \a n
ModEvent gq(Space& home, const FloatVal& n);
//@}
/// \name Dependencies
//@{
/**
* \brief Subscribe propagator \a p with propagation condition \a pc to variable
*
* In case \a schedule is false, the propagator is just subscribed but
* not scheduled for execution (this must be used when creating
* subscriptions during propagation).
*
*/
void subscribe(Space& home, Propagator& p, PropCond pc, bool schedule=true);
/// Cancel subscription of propagator \a p with propagation condition \a pc
void cancel(Space& home, Propagator& p, PropCond pc);
/// Subscribe advisor \a a to variable
void subscribe(Space& home, Advisor& a);
/// Cancel subscription of advisor \a a
void cancel(Space& home, Advisor& a);
//@}
/// \name Variable implementation-dependent propagator support
//@{
/// Translate modification event \a me to modification event delta for view
static ModEventDelta med(ModEvent me);
//@}
private:
/// Return copy of not-yet copied variable
GECODE_FLOAT_EXPORT FloatVarImp* perform_copy(Space& home, bool share);
public:
/// \name Cloning
//@{
/// Return copy of this variable
FloatVarImp* copy(Space& home, bool share);
//@}
/// \name Delta information for advisors
//@{
/// Return minimum value just pruned
static FloatNum min(const Delta& d);
/// Return maximum value just pruned
static FloatNum max(const Delta& d);
//@}
};
}}
#include <gecode/float/var-imp/float.hpp>
// STATISTICS: float-var
| {
"content_hash": "8141ecb3b53f4c58bf32a93f0569e9b1",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 84,
"avg_line_length": 31.725806451612904,
"alnum_prop": 0.6666666666666666,
"repo_name": "PetterS/easy-IP",
"id": "3c7e1b47083b58bf8791299c64c02e60b44f2839",
"size": "5902",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "third-party/gecode/gecode/float/var-imp.hpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C++",
"bytes": "124026"
},
{
"name": "CMake",
"bytes": "7556"
},
{
"name": "Python",
"bytes": "1253"
}
],
"symlink_target": ""
} |
{% if created %}
{% if created.revision.user %}
<p><a href="{% url 'object_changes' created.id %}">Created on {{ created.revision.date_created }}</a> by <a href="{{ created.revision.user.get_absolute_url }}">{{ created.revision.user.get_full_name }}</a>.</p>
{% else %}
<p><a href="{% url 'object_changes' created.id %}">Created on {{ created.revision.date_created }}</a> by unknown user.</p>
{% endif %}
{% else %}
<p>Created on: not available.</p>
{% endif %}
{% if last_modified %}
{% if last_modified.revision.user %}
<p><a href="{% url 'object_changes' last_modified.id %}">Last modified on {{ last_modified.revision.date_created }}</a> by <a href="{{ last_modified.revision.user.get_absolute_url }}">{{ last_modified.revision.user.get_full_name }}</a>.</p>
{% else %}
<p><a href="{% url 'object_changes' last_modified.id %}">Last modified on {{ last_modified.revision.date_created }}</a> by unknown user.</p>
{% endif %}
{% else %}
<p>Last modified on: not available.</p>
{% endif %}
| {
"content_hash": "ded1ba239b17101cc4fc3a4ba46e30be",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 242,
"avg_line_length": 56.333333333333336,
"alnum_prop": 0.6282051282051282,
"repo_name": "vahtras/amy",
"id": "69228a04490dfb7d9dbfc26d9aadfabd591c0072",
"size": "1014",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "workshops/templates/workshops/last_modified.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4505"
},
{
"name": "HTML",
"bytes": "216300"
},
{
"name": "JavaScript",
"bytes": "16883"
},
{
"name": "Makefile",
"bytes": "2167"
},
{
"name": "Python",
"bytes": "1090706"
}
],
"symlink_target": ""
} |
using namespace json_spirit;
using namespace std;
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
static void accountingDeprecationCheck()
{
if (!GetBoolArg("-enableaccounts", false))
throw runtime_error(
"Accounting API is deprecated and will be removed in future.\n"
"It can easily result in negative or odd balances if misused or misunderstood, which has happened in the field.\n"
"If you still want to enable it, add to your config file enableaccounts=1\n");
if (GetBoolArg("-staking", true))
throw runtime_error("If you want to use accounting API, staking must be disabled, add to your config file staking=0\n");
}
std::string HelpRequiringPassphrase()
{
return pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockStakingOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet is unlocked for staking only.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase() || wtx.IsCoinStake())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj, diff;
obj.push_back(Pair("version", FormatFullVersion()));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint())));
obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake())));
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply)));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("ip", addrSeenByPeer.ToStringIP()));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewpubkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewpubkey [account]\n"
"Returns new public key for coinbase generation.");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
vector<unsigned char> vchPubKey = newKey.Raw();
return HexStr(vchPubKey.begin(), vchPubKey.end());
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new Palestinecoin address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current Palestinecoin address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <Palestinecoinaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Palestinecoin address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <Palestinecoinaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Palestinecoin address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <Palestinecoinaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Palestinecoin address");
// Amount
int64_t nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
map<CTxDestination, int64_t> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <Palestinecoinaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <Palestinecoinaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CKey key;
if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
return false;
return (key.GetPubKey().GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <Palestinecoinaddress> [minconf=1]\n"
"Returns the total amount received by <Palestinecoinaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Palestinecoin address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64_t nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
accountingDeprecationCheck();
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64_t nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64_t GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64_t nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal() || wtx.GetDepthInMainChain() < 0)
continue;
int64_t nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64_t GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' 0 should return the same number.
int64_t nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsTrusted())
continue;
int64_t allFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
accountingDeprecationCheck();
string strAccount = AccountFromValue(params[0]);
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
accountingDeprecationCheck();
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64_t nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <toPalestinecoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Palestinecoin address");
int64_t nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64_t> > vecSend;
int64_t totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Palestinecoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64_t nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64_t nFeeRequired = 0;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed");
}
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a Palestinecoin address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
// Construct using pay-to-script-hash:
CScript inner;
inner.SetMultisig(nRequired, pubkeys);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
Value addredeemscript(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
{
string msg = "addredeemscript <redeemScript> [account]\n"
"Add a P2SH address with a specified redeemScript to the wallet.\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Construct using pay-to-script-hash:
vector<unsigned char> innerData = ParseHexV(params[0], "redeemScript");
CScript inner(innerData.begin(), innerData.end());
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem
{
int64_t nAmount;
int nConf;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64_t nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64_t nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
accountingDeprecationCheck();
return ListReceived(params, true);
}
static void MaybePushAddress(Object & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64_t nFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Sent
if ((!wtx.IsCoinStake()) && (!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.first);
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
bool stop = false;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.first);
if (wtx.IsCoinBase() || wtx.IsCoinStake())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
{
entry.push_back(Pair("category", "receive"));
}
if (!wtx.IsCoinStake())
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
else
{
entry.push_back(Pair("amount", ValueFromAmount(-nFee)));
stop = true; // only one coinstake output
}
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
if (stop)
break;
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
accountingDeprecationCheck();
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64_t> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64_t nFee;
string strSentAccount;
list<pair<CTxDestination, int64_t> > listReceived;
list<pair<CTxDestination, int64_t> > listSent;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (nDepth >= nMinDepth && wtx.GetBlocksToMaturity() == 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64_t)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (pwalletMain->mapWallet.count(hash))
{
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
TxToJSON(wtx, 0, entry);
int64_t nCredit = wtx.GetCredit();
int64_t nDebit = wtx.GetDebit();
int64_t nNet = nCredit - nDebit;
int64_t nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);
entry.push_back(Pair("details", details));
}
else
{
CTransaction tx;
uint256 hashBlock = 0;
if (GetTransaction(hash, tx, hashBlock))
{
TxToJSON(tx, 0, entry);
if (hashBlock == 0)
entry.push_back(Pair("confirmations", 0));
else
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
else
entry.push_back(Pair("confirmations", 0));
}
}
}
else
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
}
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"keypoolrefill [new-size]\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
unsigned int nSize = max(GetArg("-keypool", 100), (int64_t)0);
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size");
nSize = (unsigned int) params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(nSize);
if (pwalletMain->GetKeyPoolSize() < nSize)
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
// Make this thread recognisable as the key-topping-up thread
RenameThread("Palestinecoin-key-top");
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
// Make this thread recognisable as the wallet relocking thread
RenameThread("Palestinecoin-lock-wa");
int64_t nMyWakeTime = GetTimeMillis() + *((int64_t*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64_t nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
MilliSleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64_t*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw runtime_error(
"walletpassphrase <passphrase> <timeout> [stakingonly]\n"
"Stores the wallet decryption key in memory for <timeout> seconds.\n"
"if [stakingonly] is true sending functions are disabled.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
NewThread(ThreadTopUpKeyPool, NULL);
int64_t* pnSleepTime = new int64_t(params[1].get_int64());
NewThread(ThreadCleanWalletPassphrase, pnSleepTime);
// ppcoin: if user OS account compromised prevent trivial sendmoney commands
if (params.size() > 2)
fWalletUnlockStakingOnly = params[2].get_bool();
else
fWalletUnlockStakingOnly = false;
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; Palestinecoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw())));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <Palestinecoinaddress>\n"
"Return information about <Palestinecoinaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value validatepubkey(const Array& params, bool fHelp)
{
if (fHelp || !params.size() || params.size() > 2)
throw runtime_error(
"validatepubkey <Palestinecoinpubkey>\n"
"Return information about <Palestinecoinpubkey>.");
std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str());
CPubKey pubKey(vchPubKey);
bool isValid = pubKey.IsValid();
bool isCompressed = pubKey.IsCompressed();
CKeyID keyID = pubKey.GetID();
CBitcoinAddress address;
address.Set(keyID);
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
ret.push_back(Pair("iscompressed", isCompressed));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
// ppcoin: reserve balance from being staked for network protection
Value reservebalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"reservebalance [<reserve> [amount]]\n"
"<reserve> is true or false to turn balance reserve on or off.\n"
"<amount> is a real and rounded to cent.\n"
"Set reserve amount not participating in network protection.\n"
"If no parameters provided current setting is printed.\n");
if (params.size() > 0)
{
bool fReserve = params[0].get_bool();
if (fReserve)
{
if (params.size() == 1)
throw runtime_error("must provide amount to reserve balance.\n");
int64_t nAmount = AmountFromValue(params[1]);
nAmount = (nAmount / CENT) * CENT; // round to cent
if (nAmount < 0)
throw runtime_error("amount cannot be negative.\n");
nReserveBalance = nAmount;
}
else
{
if (params.size() > 1)
throw runtime_error("cannot specify amount to turn off reserve.\n");
nReserveBalance = 0;
}
}
Object result;
result.push_back(Pair("reserve", (nReserveBalance > 0)));
result.push_back(Pair("amount", ValueFromAmount(nReserveBalance)));
return result;
}
// ppcoin: check wallet integrity
Value checkwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"checkwallet\n"
"Check wallet for integrity.\n");
int nMismatchSpent;
int64_t nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// ppcoin: repair wallet
Value repairwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"repairwallet\n"
"Repair wallet if checkwallet reports any problem.\n");
int nMismatchSpent;
int64_t nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// NovaCoin: resend unconfirmed wallet transactions
Value resendtx(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"resendtx\n"
"Re-send unconfirmed transactions.\n"
);
ResendWalletTransactions(true);
return Value::null;
}
// ppcoin: make a public-private key pair
Value makekeypair(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"makekeypair [prefix]\n"
"Make a public/private key pair.\n"
"[prefix] is optional preferred prefix for the public key.\n");
string strPrefix = "";
if (params.size() > 0)
strPrefix = params[0].get_str();
CKey key;
key.MakeNewKey(false);
CPrivKey vchPrivKey = key.GetPrivKey();
Object result;
result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end())));
result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw())));
return result;
}
| {
"content_hash": "bc465c30f856f410205d095888ee8bfe",
"timestamp": "",
"source": "github",
"line_count": 1766,
"max_line_length": 162,
"avg_line_length": 34.88561721404304,
"alnum_prop": 0.6247240618101545,
"repo_name": "PalestineCoin/Palestinecoin",
"id": "143422014d7a423bd6df46529fda3ec0296be2ae",
"size": "61946",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/rpcwallet.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "51312"
},
{
"name": "C",
"bytes": "777925"
},
{
"name": "C++",
"bytes": "2650779"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Objective-C++",
"bytes": "3536"
},
{
"name": "Python",
"bytes": "2819"
},
{
"name": "Shell",
"bytes": "1026"
},
{
"name": "TypeScript",
"bytes": "7751444"
}
],
"symlink_target": ""
} |
<table cellspacing="0" cellpadding="0" style="table-layout:fixed;">
<tr>
<td width="230" style="width:230px;height:1px;padding:0px;margin:0px;line-height:1px;" class="left_column"><img border="0" src="#%site_url%#/images/blank.gif" width="230" height="1"></td>
<td width="770" style="height:1px;padding:0px;margin:0px;line-height:1px;"><img border="0" src="#%site_url%#/images/blank.gif" width="50" height="1"></td>
</tr>
<tr>
<td class="left_column">
#%in1%#
</td>
<td class="cell_middle">
#%in3%#
#%info%#
<div class="common_div_main">
<div class="common_div_title">Edit Your Link</div>
<div class="common_div_content"><table border="0" width="100%" cellpadding="5" cellspacing="0" class="inside_table">
<tr><td align="center">
<form action="#%site_url%#/link_edit.php" method="post" name="edit">
<input type="hidden" name="action" value="link_edit">
<table cellspacing="0" cellpadding="2" width="100%" border="0">
<tr>
<td colspan=3 align="center">Please enter URL of the link which you want to edit<br />or number of the link and your password.</td></tr>
<tr>
<td nowrap align="left">URL: </td>
<td align="left" colspan=2><input maxlength="150" name="url" class="field10" style="width:450px"></td>
</tr>
<tr>
<td nowrap align="left">Number: </td>
<td align="left" colspan=2><input maxlength="15" size="15" name="n" class="field10" value="#%n%#"></td>
</tr>
<tr>
<td nowrap align="left">Password: </td>
<td align="left"><input maxlength="15" size="15" name="password" class="field10"></td>
<td align="right"><input type="submit" value="Submit" name="B1" class="button10"></td></tr>
</form>
<form action="#%site_url%#/link_edit.php" method="get" name="edit">
<input type="hidden" name="action" value="links_list">
<tr><td colspan=3 align="center">Or enter your email address to show list of your links.</td></tr>
<tr><td colspan=3 align="center"><input maxlength="150" name="email" class="field10" style="width:500px"></td></tr>
<tr><td colspan=3 align="center"><input type="submit" value="Show my links" name="B1" class="button10"></td></tr>
</table></form>
</td></tr></table></div>
</div>
</td>
<td class="right_column">
#%in2%#
</td></tr></table>
| {
"content_hash": "e27061dc166f12c98518bc0753f7c693",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 187,
"avg_line_length": 35.57377049180328,
"alnum_prop": 0.6640552995391705,
"repo_name": "vlnpractice/master",
"id": "6a5689095764a60b6e237b194127dd88b715bc12",
"size": "2186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "styles/_common/templates/link_edit_login.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "168407"
},
{
"name": "JavaScript",
"bytes": "1842111"
},
{
"name": "PHP",
"bytes": "12455741"
},
{
"name": "Shell",
"bytes": "94"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/inspector/Inspector_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace Inspector
{
namespace Model
{
class AWS_INSPECTOR_API AttachAssessmentAndRulesPackageResult
{
public:
AttachAssessmentAndRulesPackageResult();
AttachAssessmentAndRulesPackageResult(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
AttachAssessmentAndRulesPackageResult& operator=(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>Confirmation details of the action performed.</p>
*/
inline const Aws::String& GetMessage() const{ return m_message; }
/**
* <p>Confirmation details of the action performed.</p>
*/
inline void SetMessage(const Aws::String& value) { m_message = value; }
/**
* <p>Confirmation details of the action performed.</p>
*/
inline void SetMessage(Aws::String&& value) { m_message = value; }
/**
* <p>Confirmation details of the action performed.</p>
*/
inline void SetMessage(const char* value) { m_message.assign(value); }
/**
* <p>Confirmation details of the action performed.</p>
*/
inline AttachAssessmentAndRulesPackageResult& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}
/**
* <p>Confirmation details of the action performed.</p>
*/
inline AttachAssessmentAndRulesPackageResult& WithMessage(Aws::String&& value) { SetMessage(value); return *this;}
/**
* <p>Confirmation details of the action performed.</p>
*/
inline AttachAssessmentAndRulesPackageResult& WithMessage(const char* value) { SetMessage(value); return *this;}
private:
Aws::String m_message;
};
} // namespace Model
} // namespace Inspector
} // namespace Aws
| {
"content_hash": "48ab8bb577726321f28f296c75c82963",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 123,
"avg_line_length": 28.257142857142856,
"alnum_prop": 0.6971688574317493,
"repo_name": "ambasta/aws-sdk-cpp",
"id": "f775513bfaca8e6c8fdb514f49b4e96554d48028",
"size": "2551",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-inspector/include/aws/inspector/model/AttachAssessmentAndRulesPackageResult.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2305"
},
{
"name": "C++",
"bytes": "74273816"
},
{
"name": "CMake",
"bytes": "412257"
},
{
"name": "Java",
"bytes": "229873"
},
{
"name": "Python",
"bytes": "62933"
}
],
"symlink_target": ""
} |
omprog: Program integration Output module
=========================================
**Module Name: omprog**
**Available since: ** 4.3.0
**Author:**\ Rainer Gerhards <[email protected]>
**Description**:
This module permits to integrate arbitrary external programs into
rsyslog's logging. It is similar to the "execute program (^)" action,
but offers better security and much higher performance. While "execute
program (^)" can be a useful tool for executing programs if rare events
occur, omprog can be used to provide massive amounts of log data to a
program.
Executes the configured program and feeds log messages to that binary
via stdin. The binary is free to do whatever it wants with the supplied
data. If the program terminates, it is re-started. If rsyslog
terminates, the program's stdin will see EOF. The program must then
terminate. The message format passed to the program can, as usual, be
modified by defining rsyslog templates.
Note that each time an omprog action is defined, the corresponding
program is invoked. A single instance is **not** being re-used. There
are arguments pro and con for re-using existing binaries. For the time
being, it simply is not done. In the future, we may add an option for
such pooling, provided that some demand for that is voiced. You can also
mimic the same effect by defining multiple rulesets and including them.
Note that in order to execute the given program, rsyslog needs to have
sufficient permissions on the binary file. This is especially true if
not running as root. Also, keep in mind that default SELinux policies
most probably do not permit rsyslogd to execute arbitrary binaries. As
such, permissions must be appropriately added. Note that SELinux
restrictions also apply if rsyslogd runs under root. To check if a
problem is SELinux-related, you can temporarily disable SELinux and
retry. If it then works, you know for sure you have a SELinux issue.
Starting with 8.4.0, rsyslogd emits an error message via the ``syslog()``
API call when there is a problem executing the binary. This can be
extremely valuable in troubleshooting. For those technically savy:
when we execute a binary, we need to fork, and we do not have
full access to rsyslog's usual error-reporting capabilities after the
fork. As the actual execution must happen after the fork, we cannot
use the default error logger to emit the error message. As such,
we use ``syslog()``. In most cases, there is no real difference
between both methods. However, if you run multiple rsyslog instances,
the messae shows up in that instance that processes the default
log socket, which may be different from the one where the error occured.
Also, if you redirected the log destination, that redirection may
not work as expected.
**Module Parameters**:
- **Template**\ [templateName]
sets a new default template for file actions.
**Action Parameters**:
- **binary**
Mostly equivalent to the "binary" action parameter, but must contain
the binary name only. In legacy config, it is **not possible** to
specify command line parameters.
**Caveats/Known Bugs:**
- None.
**Sample:**
The following command writes all syslog messages into a file.
::
module(load="omprog")
action(type="omprog"
binary="/pathto/omprog.py --parm1=\"value 1\" --parm2=\"value2\"
template="RSYSLOG_TraditionalFileFormat")
**Legacy Configuration Directives**:
- **$ActionOMProgBinary** <binary>
The binary program to be executed.
**Caveats/Known Bugs:**
Currently none known.
This documentation is part of the `rsyslog <http://www.rsyslog.com/>`_
project.
Copyright © 2008-2014 by `Rainer
Gerhards <http://www.gerhards.net/rainer>`_ and
`Adiscon <http://www.adiscon.com/>`_. Released under the GNU GPL version
3 or higher.
| {
"content_hash": "417aee6aba9dab4831383d9a12cd5540",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 73,
"avg_line_length": 37.92,
"alnum_prop": 0.7539556962025317,
"repo_name": "teifler/rsyslog-doc",
"id": "079cfb1861f85870fbfe494d725af477f61f9522",
"size": "3801",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/configuration/modules/omprog.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8459"
},
{
"name": "HTML",
"bytes": "409"
},
{
"name": "JavaScript",
"bytes": "31866"
},
{
"name": "Python",
"bytes": "9346"
},
{
"name": "Shell",
"bytes": "1148"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.monitor.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for KnownExtensionDataSourceStreams. */
public final class KnownExtensionDataSourceStreams extends ExpandableStringEnum<KnownExtensionDataSourceStreams> {
/** Static value Microsoft-Event for KnownExtensionDataSourceStreams. */
public static final KnownExtensionDataSourceStreams MICROSOFT_EVENT = fromString("Microsoft-Event");
/** Static value Microsoft-InsightsMetrics for KnownExtensionDataSourceStreams. */
public static final KnownExtensionDataSourceStreams MICROSOFT_INSIGHTS_METRICS =
fromString("Microsoft-InsightsMetrics");
/** Static value Microsoft-Perf for KnownExtensionDataSourceStreams. */
public static final KnownExtensionDataSourceStreams MICROSOFT_PERF = fromString("Microsoft-Perf");
/** Static value Microsoft-Syslog for KnownExtensionDataSourceStreams. */
public static final KnownExtensionDataSourceStreams MICROSOFT_SYSLOG = fromString("Microsoft-Syslog");
/** Static value Microsoft-WindowsEvent for KnownExtensionDataSourceStreams. */
public static final KnownExtensionDataSourceStreams MICROSOFT_WINDOWS_EVENT = fromString("Microsoft-WindowsEvent");
/**
* Creates or finds a KnownExtensionDataSourceStreams from its string representation.
*
* @param name a name to look for.
* @return the corresponding KnownExtensionDataSourceStreams.
*/
@JsonCreator
public static KnownExtensionDataSourceStreams fromString(String name) {
return fromString(name, KnownExtensionDataSourceStreams.class);
}
/**
* Gets known KnownExtensionDataSourceStreams values.
*
* @return known KnownExtensionDataSourceStreams values.
*/
public static Collection<KnownExtensionDataSourceStreams> values() {
return values(KnownExtensionDataSourceStreams.class);
}
}
| {
"content_hash": "929207c98dc6ae46a170b8ff8401a4e5",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 119,
"avg_line_length": 45.104166666666664,
"alnum_prop": 0.776905311778291,
"repo_name": "Azure/azure-sdk-for-java",
"id": "eb16c2c45a089627620e01c86474bb31221c80a1",
"size": "2165",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/resourcemanager/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/models/KnownExtensionDataSourceStreams.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
<?php
declare (strict_types=1);
namespace PhpParser\ErrorHandler;
use PhpParser\Error;
use PhpParser\ErrorHandler;
/**
* Error handler that collects all errors into an array.
*
* This allows graceful handling of errors.
*/
class Collecting implements \PhpParser\ErrorHandler
{
/** @var Error[] Collected errors */
private $errors = [];
public function handleError(\PhpParser\Error $error)
{
$this->errors[] = $error;
}
/**
* Get collected errors.
*
* @return Error[]
*/
public function getErrors() : array
{
return $this->errors;
}
/**
* Check whether there are any errors.
*
* @return bool
*/
public function hasErrors() : bool
{
return !empty($this->errors);
}
/**
* Reset/clear collected errors.
*/
public function clearErrors()
{
$this->errors = [];
}
}
| {
"content_hash": "57cb471445fd6e800ec3f60b5df58438",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 56,
"avg_line_length": 19.869565217391305,
"alnum_prop": 0.5820568927789934,
"repo_name": "RectorPHP/Rector",
"id": "77cdc669a5c522122cee7ea29e96a91f276e98f1",
"size": "914",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "vendor/nikic/php-parser/lib/PhpParser/ErrorHandler/Collecting.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "503421"
}
],
"symlink_target": ""
} |
layout: page
title: Huynh Youth Entertainment Show
date: 2016-05-24
author: Mary Hanna
tags: weekly links, java
status: published
summary: Cras mattis commodo enim, ac interdum odio viverra.
banner: images/banner/meeting-01.jpg
booking:
startDate: 05/13/2019
endDate: 05/18/2019
ctyhocn: WELMEHX
groupCode: HYES
published: true
---
Fusce mollis ex vel eros fringilla, id ullamcorper augue viverra. Curabitur a sem fringilla, feugiat turpis non, consequat libero. Curabitur ultricies ut tortor at porttitor. Aliquam ultrices nisl sodales diam luctus, at maximus augue ultricies. Praesent ac odio sed nisi suscipit vulputate. Donec congue laoreet ipsum. In hac habitasse platea dictumst. Nunc quis maximus augue. Phasellus a rhoncus ex. Pellentesque id tortor rutrum ligula hendrerit euismod ac a ex.
* Mauris eget nisl tristique sem ultrices iaculis at et est
* Nulla rutrum enim gravida lacinia cursus
* Vivamus eget odio sit amet augue varius ultrices
* Etiam a libero aliquet, auctor nisl id, eleifend arcu.
Fusce mattis lacinia libero et porta. Donec porta, odio et semper dapibus, massa lacus interdum velit, nec ullamcorper turpis ipsum at nisl. Suspendisse volutpat finibus porta. Mauris eu libero sed sapien efficitur ultricies. Aliquam a tortor aliquam, sollicitudin ipsum congue, rutrum ex. Pellentesque dolor felis, tincidunt a massa non, fringilla mattis est. Suspendisse eu mattis ante, eu congue lectus. Vivamus laoreet orci lorem, et placerat erat eleifend non. Nulla ante augue, rhoncus ac fringilla vel, consequat posuere nisl. Donec dignissim cursus metus vel placerat. Curabitur felis turpis, viverra ac tincidunt at, ullamcorper id magna. Nullam gravida porta nunc, non accumsan ligula cursus in. Vestibulum viverra tortor eget tincidunt consectetur. Nullam maximus et lorem id pulvinar. Aenean vehicula dictum volutpat.
| {
"content_hash": "e059d76e767f5875cc8ddc4753e919f4",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 829,
"avg_line_length": 80.43478260869566,
"alnum_prop": 0.8075675675675675,
"repo_name": "KlishGroup/prose-pogs",
"id": "b6187a54dbf3a0ce5f9edfbe1eab8f9b58693667",
"size": "1854",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "pogs/W/WELMEHX/HYES/index.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Monitoring.V3 {
/// <summary>Holder for reflection information generated from google/monitoring/v3/uptime.proto</summary>
public static partial class UptimeReflection {
#region Descriptor
/// <summary>File descriptor for google/monitoring/v3/uptime.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static UptimeReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiFnb29nbGUvbW9uaXRvcmluZy92My91cHRpbWUucHJvdG8SFGdvb2dsZS5t",
"b25pdG9yaW5nLnYzGiNnb29nbGUvYXBpL21vbml0b3JlZF9yZXNvdXJjZS5w",
"cm90bxoeZ29vZ2xlL3Byb3RvYnVmL2R1cmF0aW9uLnByb3RvInIKD0ludGVy",
"bmFsQ2hlY2tlchISCgpwcm9qZWN0X2lkGAEgASgJEg8KB25ldHdvcmsYAiAB",
"KAkSEAoIZ2NwX3pvbmUYAyABKAkSEgoKY2hlY2tlcl9pZBgEIAEoCRIUCgxk",
"aXNwbGF5X25hbWUYBSABKAkiwQkKEVVwdGltZUNoZWNrQ29uZmlnEgwKBG5h",
"bWUYASABKAkSFAoMZGlzcGxheV9uYW1lGAIgASgJEjsKEm1vbml0b3JlZF9y",
"ZXNvdXJjZRgDIAEoCzIdLmdvb2dsZS5hcGkuTW9uaXRvcmVkUmVzb3VyY2VI",
"ABJPCg5yZXNvdXJjZV9ncm91cBgEIAEoCzI1Lmdvb2dsZS5tb25pdG9yaW5n",
"LnYzLlVwdGltZUNoZWNrQ29uZmlnLlJlc291cmNlR3JvdXBIABJHCgpodHRw",
"X2NoZWNrGAUgASgLMjEuZ29vZ2xlLm1vbml0b3JpbmcudjMuVXB0aW1lQ2hl",
"Y2tDb25maWcuSHR0cENoZWNrSAESRQoJdGNwX2NoZWNrGAYgASgLMjAuZ29v",
"Z2xlLm1vbml0b3JpbmcudjMuVXB0aW1lQ2hlY2tDb25maWcuVGNwQ2hlY2tI",
"ARIpCgZwZXJpb2QYByABKAsyGS5nb29nbGUucHJvdG9idWYuRHVyYXRpb24S",
"KgoHdGltZW91dBgIIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbhJQ",
"ChBjb250ZW50X21hdGNoZXJzGAkgAygLMjYuZ29vZ2xlLm1vbml0b3Jpbmcu",
"djMuVXB0aW1lQ2hlY2tDb25maWcuQ29udGVudE1hdGNoZXISQQoQc2VsZWN0",
"ZWRfcmVnaW9ucxgKIAMoDjInLmdvb2dsZS5tb25pdG9yaW5nLnYzLlVwdGlt",
"ZUNoZWNrUmVnaW9uEhMKC2lzX2ludGVybmFsGA8gASgIEkAKEWludGVybmFs",
"X2NoZWNrZXJzGA4gAygLMiUuZ29vZ2xlLm1vbml0b3JpbmcudjMuSW50ZXJu",
"YWxDaGVja2VyGmEKDVJlc291cmNlR3JvdXASEAoIZ3JvdXBfaWQYASABKAkS",
"PgoNcmVzb3VyY2VfdHlwZRgCIAEoDjInLmdvb2dsZS5tb25pdG9yaW5nLnYz",
"Lkdyb3VwUmVzb3VyY2VUeXBlGuQCCglIdHRwQ2hlY2sSDwoHdXNlX3NzbBgB",
"IAEoCBIMCgRwYXRoGAIgASgJEgwKBHBvcnQYAyABKAUSWAoJYXV0aF9pbmZv",
"GAQgASgLMkUuZ29vZ2xlLm1vbml0b3JpbmcudjMuVXB0aW1lQ2hlY2tDb25m",
"aWcuSHR0cENoZWNrLkJhc2ljQXV0aGVudGljYXRpb24SFAoMbWFza19oZWFk",
"ZXJzGAUgASgIEk8KB2hlYWRlcnMYBiADKAsyPi5nb29nbGUubW9uaXRvcmlu",
"Zy52My5VcHRpbWVDaGVja0NvbmZpZy5IdHRwQ2hlY2suSGVhZGVyc0VudHJ5",
"GjkKE0Jhc2ljQXV0aGVudGljYXRpb24SEAoIdXNlcm5hbWUYASABKAkSEAoI",
"cGFzc3dvcmQYAiABKAkaLgoMSGVhZGVyc0VudHJ5EgsKA2tleRgBIAEoCRIN",
"CgV2YWx1ZRgCIAEoCToCOAEaGAoIVGNwQ2hlY2sSDAoEcG9ydBgBIAEoBRoh",
"Cg5Db250ZW50TWF0Y2hlchIPCgdjb250ZW50GAEgASgJQgoKCHJlc291cmNl",
"QhQKEmNoZWNrX3JlcXVlc3RfdHlwZSJuCg1VcHRpbWVDaGVja0lwEjcKBnJl",
"Z2lvbhgBIAEoDjInLmdvb2dsZS5tb25pdG9yaW5nLnYzLlVwdGltZUNoZWNr",
"UmVnaW9uEhAKCGxvY2F0aW9uGAIgASgJEhIKCmlwX2FkZHJlc3MYAyABKAkq",
"ZQoRVXB0aW1lQ2hlY2tSZWdpb24SFgoSUkVHSU9OX1VOU1BFQ0lGSUVEEAAS",
"BwoDVVNBEAESCgoGRVVST1BFEAISEQoNU09VVEhfQU1FUklDQRADEhAKDEFT",
"SUFfUEFDSUZJQxAEKlsKEUdyb3VwUmVzb3VyY2VUeXBlEh0KGVJFU09VUkNF",
"X1RZUEVfVU5TUEVDSUZJRUQQABIMCghJTlNUQU5DRRABEhkKFUFXU19FTEJf",
"TE9BRF9CQUxBTkNFUhACQqMBChhjb20uZ29vZ2xlLm1vbml0b3JpbmcudjNC",
"C1VwdGltZVByb3RvUAFaPmdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dv",
"b2dsZWFwaXMvbW9uaXRvcmluZy92Mzttb25pdG9yaW5nqgIaR29vZ2xlLkNs",
"b3VkLk1vbml0b3JpbmcuVjPKAhpHb29nbGVcQ2xvdWRcTW9uaXRvcmluZ1xW",
"M2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.MonitoredResourceReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Cloud.Monitoring.V3.UptimeCheckRegion), typeof(global::Google.Cloud.Monitoring.V3.GroupResourceType), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.InternalChecker), global::Google.Cloud.Monitoring.V3.InternalChecker.Parser, new[]{ "ProjectId", "Network", "GcpZone", "CheckerId", "DisplayName" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.UptimeCheckConfig), global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Parser, new[]{ "Name", "DisplayName", "MonitoredResource", "ResourceGroup", "HttpCheck", "TcpCheck", "Period", "Timeout", "ContentMatchers", "SelectedRegions", "IsInternal", "InternalCheckers" }, new[]{ "Resource", "CheckRequestType" }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ResourceGroup), global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ResourceGroup.Parser, new[]{ "GroupId", "ResourceType" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck), global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck.Parser, new[]{ "UseSsl", "Path", "Port", "AuthInfo", "MaskHeaders", "Headers" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck.Types.BasicAuthentication), global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck.Types.BasicAuthentication.Parser, new[]{ "Username", "Password" }, null, null, null),
null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.TcpCheck), global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.TcpCheck.Parser, new[]{ "Port" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ContentMatcher), global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ContentMatcher.Parser, new[]{ "Content" }, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.UptimeCheckIp), global::Google.Cloud.Monitoring.V3.UptimeCheckIp.Parser, new[]{ "Region", "Location", "IpAddress" }, null, null, null)
}));
}
#endregion
}
#region Enums
/// <summary>
/// The regions from which an uptime check can be run.
/// </summary>
public enum UptimeCheckRegion {
/// <summary>
/// Default value if no region is specified. Will result in uptime checks
/// running from all regions.
/// </summary>
[pbr::OriginalName("REGION_UNSPECIFIED")] RegionUnspecified = 0,
/// <summary>
/// Allows checks to run from locations within the United States of America.
/// </summary>
[pbr::OriginalName("USA")] Usa = 1,
/// <summary>
/// Allows checks to run from locations within the continent of Europe.
/// </summary>
[pbr::OriginalName("EUROPE")] Europe = 2,
/// <summary>
/// Allows checks to run from locations within the continent of South
/// America.
/// </summary>
[pbr::OriginalName("SOUTH_AMERICA")] SouthAmerica = 3,
/// <summary>
/// Allows checks to run from locations within the Asia Pacific area (ex:
/// Singapore).
/// </summary>
[pbr::OriginalName("ASIA_PACIFIC")] AsiaPacific = 4,
}
/// <summary>
/// The supported resource types that can be used as values of
/// `group_resource.resource_type`.
/// `INSTANCE` includes `gce_instance` and `aws_ec2_instance` resource types.
/// The resource types `gae_app` and `uptime_url` are not valid here because
/// group checks on App Engine modules and URLs are not allowed.
/// </summary>
public enum GroupResourceType {
/// <summary>
/// Default value (not valid).
/// </summary>
[pbr::OriginalName("RESOURCE_TYPE_UNSPECIFIED")] ResourceTypeUnspecified = 0,
/// <summary>
/// A group of instances from Google Cloud Platform (GCP) or
/// Amazon Web Services (AWS).
/// </summary>
[pbr::OriginalName("INSTANCE")] Instance = 1,
/// <summary>
/// A group of Amazon ELB load balancers.
/// </summary>
[pbr::OriginalName("AWS_ELB_LOAD_BALANCER")] AwsElbLoadBalancer = 2,
}
#endregion
#region Messages
/// <summary>
/// Nimbus InternalCheckers.
/// </summary>
public sealed partial class InternalChecker : pb::IMessage<InternalChecker> {
private static readonly pb::MessageParser<InternalChecker> _parser = new pb::MessageParser<InternalChecker>(() => new InternalChecker());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<InternalChecker> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Monitoring.V3.UptimeReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public InternalChecker() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public InternalChecker(InternalChecker other) : this() {
projectId_ = other.projectId_;
network_ = other.network_;
gcpZone_ = other.gcpZone_;
checkerId_ = other.checkerId_;
displayName_ = other.displayName_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public InternalChecker Clone() {
return new InternalChecker(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 1;
private string projectId_ = "";
/// <summary>
/// The GCP project ID. Not necessarily the same as the project_id for the
/// config.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "network" field.</summary>
public const int NetworkFieldNumber = 2;
private string network_ = "";
/// <summary>
/// The internal network to perform this uptime check on.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Network {
get { return network_; }
set {
network_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "gcp_zone" field.</summary>
public const int GcpZoneFieldNumber = 3;
private string gcpZone_ = "";
/// <summary>
/// The GCP zone the uptime check should egress from. Only respected for
/// internal uptime checks, where internal_network is specified.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string GcpZone {
get { return gcpZone_; }
set {
gcpZone_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "checker_id" field.</summary>
public const int CheckerIdFieldNumber = 4;
private string checkerId_ = "";
/// <summary>
/// The checker ID.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string CheckerId {
get { return checkerId_; }
set {
checkerId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "display_name" field.</summary>
public const int DisplayNameFieldNumber = 5;
private string displayName_ = "";
/// <summary>
/// The checker's human-readable name.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DisplayName {
get { return displayName_; }
set {
displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as InternalChecker);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(InternalChecker other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
if (Network != other.Network) return false;
if (GcpZone != other.GcpZone) return false;
if (CheckerId != other.CheckerId) return false;
if (DisplayName != other.DisplayName) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (Network.Length != 0) hash ^= Network.GetHashCode();
if (GcpZone.Length != 0) hash ^= GcpZone.GetHashCode();
if (CheckerId.Length != 0) hash ^= CheckerId.GetHashCode();
if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ProjectId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ProjectId);
}
if (Network.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Network);
}
if (GcpZone.Length != 0) {
output.WriteRawTag(26);
output.WriteString(GcpZone);
}
if (CheckerId.Length != 0) {
output.WriteRawTag(34);
output.WriteString(CheckerId);
}
if (DisplayName.Length != 0) {
output.WriteRawTag(42);
output.WriteString(DisplayName);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (Network.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Network);
}
if (GcpZone.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(GcpZone);
}
if (CheckerId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(CheckerId);
}
if (DisplayName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(InternalChecker other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.Network.Length != 0) {
Network = other.Network;
}
if (other.GcpZone.Length != 0) {
GcpZone = other.GcpZone;
}
if (other.CheckerId.Length != 0) {
CheckerId = other.CheckerId;
}
if (other.DisplayName.Length != 0) {
DisplayName = other.DisplayName;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
ProjectId = input.ReadString();
break;
}
case 18: {
Network = input.ReadString();
break;
}
case 26: {
GcpZone = input.ReadString();
break;
}
case 34: {
CheckerId = input.ReadString();
break;
}
case 42: {
DisplayName = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// This message configures which resources and services to monitor for
/// availability.
/// </summary>
public sealed partial class UptimeCheckConfig : pb::IMessage<UptimeCheckConfig> {
private static readonly pb::MessageParser<UptimeCheckConfig> _parser = new pb::MessageParser<UptimeCheckConfig>(() => new UptimeCheckConfig());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UptimeCheckConfig> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Monitoring.V3.UptimeReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UptimeCheckConfig() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UptimeCheckConfig(UptimeCheckConfig other) : this() {
name_ = other.name_;
displayName_ = other.displayName_;
period_ = other.period_ != null ? other.period_.Clone() : null;
timeout_ = other.timeout_ != null ? other.timeout_.Clone() : null;
contentMatchers_ = other.contentMatchers_.Clone();
selectedRegions_ = other.selectedRegions_.Clone();
isInternal_ = other.isInternal_;
internalCheckers_ = other.internalCheckers_.Clone();
switch (other.ResourceCase) {
case ResourceOneofCase.MonitoredResource:
MonitoredResource = other.MonitoredResource.Clone();
break;
case ResourceOneofCase.ResourceGroup:
ResourceGroup = other.ResourceGroup.Clone();
break;
}
switch (other.CheckRequestTypeCase) {
case CheckRequestTypeOneofCase.HttpCheck:
HttpCheck = other.HttpCheck.Clone();
break;
case CheckRequestTypeOneofCase.TcpCheck:
TcpCheck = other.TcpCheck.Clone();
break;
}
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UptimeCheckConfig Clone() {
return new UptimeCheckConfig(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// A unique resource name for this UptimeCheckConfig. The format is:
///
/// `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`.
///
/// This field should be omitted when creating the uptime check configuration;
/// on create, the resource name is assigned by the server and included in the
/// response.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "display_name" field.</summary>
public const int DisplayNameFieldNumber = 2;
private string displayName_ = "";
/// <summary>
/// A human-friendly name for the uptime check configuration. The display name
/// should be unique within a Stackdriver Account in order to make it easier
/// to identify; however, uniqueness is not enforced. Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DisplayName {
get { return displayName_; }
set {
displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "monitored_resource" field.</summary>
public const int MonitoredResourceFieldNumber = 3;
/// <summary>
/// The [monitored
/// resource](https://cloud.google.com/monitoring/api/resources) associated
/// with the configuration.
/// The following monitored resource types are supported for uptime checks:
/// uptime_url
/// gce_instance
/// gae_app
/// aws_ec2_instance
/// aws_elb_load_balancer
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.MonitoredResource MonitoredResource {
get { return resourceCase_ == ResourceOneofCase.MonitoredResource ? (global::Google.Api.MonitoredResource) resource_ : null; }
set {
resource_ = value;
resourceCase_ = value == null ? ResourceOneofCase.None : ResourceOneofCase.MonitoredResource;
}
}
/// <summary>Field number for the "resource_group" field.</summary>
public const int ResourceGroupFieldNumber = 4;
/// <summary>
/// The group resource associated with the configuration.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ResourceGroup ResourceGroup {
get { return resourceCase_ == ResourceOneofCase.ResourceGroup ? (global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ResourceGroup) resource_ : null; }
set {
resource_ = value;
resourceCase_ = value == null ? ResourceOneofCase.None : ResourceOneofCase.ResourceGroup;
}
}
/// <summary>Field number for the "http_check" field.</summary>
public const int HttpCheckFieldNumber = 5;
/// <summary>
/// Contains information needed to make an HTTP or HTTPS check.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck HttpCheck {
get { return checkRequestTypeCase_ == CheckRequestTypeOneofCase.HttpCheck ? (global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck) checkRequestType_ : null; }
set {
checkRequestType_ = value;
checkRequestTypeCase_ = value == null ? CheckRequestTypeOneofCase.None : CheckRequestTypeOneofCase.HttpCheck;
}
}
/// <summary>Field number for the "tcp_check" field.</summary>
public const int TcpCheckFieldNumber = 6;
/// <summary>
/// Contains information needed to make a TCP check.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.TcpCheck TcpCheck {
get { return checkRequestTypeCase_ == CheckRequestTypeOneofCase.TcpCheck ? (global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.TcpCheck) checkRequestType_ : null; }
set {
checkRequestType_ = value;
checkRequestTypeCase_ = value == null ? CheckRequestTypeOneofCase.None : CheckRequestTypeOneofCase.TcpCheck;
}
}
/// <summary>Field number for the "period" field.</summary>
public const int PeriodFieldNumber = 7;
private global::Google.Protobuf.WellKnownTypes.Duration period_;
/// <summary>
/// How often, in seconds, the uptime check is performed.
/// Currently, the only supported values are `60s` (1 minute), `300s`
/// (5 minutes), `600s` (10 minutes), and `900s` (15 minutes). Optional,
/// defaults to `300s`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Duration Period {
get { return period_; }
set {
period_ = value;
}
}
/// <summary>Field number for the "timeout" field.</summary>
public const int TimeoutFieldNumber = 8;
private global::Google.Protobuf.WellKnownTypes.Duration timeout_;
/// <summary>
/// The maximum amount of time to wait for the request to complete (must be
/// between 1 and 60 seconds). Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Duration Timeout {
get { return timeout_; }
set {
timeout_ = value;
}
}
/// <summary>Field number for the "content_matchers" field.</summary>
public const int ContentMatchersFieldNumber = 9;
private static readonly pb::FieldCodec<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ContentMatcher> _repeated_contentMatchers_codec
= pb::FieldCodec.ForMessage(74, global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ContentMatcher.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ContentMatcher> contentMatchers_ = new pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ContentMatcher>();
/// <summary>
/// The expected content on the page the check is run against.
/// Currently, only the first entry in the list is supported, and other entries
/// will be ignored. The server will look for an exact match of the string in
/// the page response's content. This field is optional and should only be
/// specified if a content match is required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ContentMatcher> ContentMatchers {
get { return contentMatchers_; }
}
/// <summary>Field number for the "selected_regions" field.</summary>
public const int SelectedRegionsFieldNumber = 10;
private static readonly pb::FieldCodec<global::Google.Cloud.Monitoring.V3.UptimeCheckRegion> _repeated_selectedRegions_codec
= pb::FieldCodec.ForEnum(82, x => (int) x, x => (global::Google.Cloud.Monitoring.V3.UptimeCheckRegion) x);
private readonly pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckRegion> selectedRegions_ = new pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckRegion>();
/// <summary>
/// The list of regions from which the check will be run.
/// If this field is specified, enough regions to include a minimum of
/// 3 locations must be provided, or an error message is returned.
/// Not specifying this field will result in uptime checks running from all
/// regions.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.UptimeCheckRegion> SelectedRegions {
get { return selectedRegions_; }
}
/// <summary>Field number for the "is_internal" field.</summary>
public const int IsInternalFieldNumber = 15;
private bool isInternal_;
/// <summary>
/// Denotes whether this is a check that egresses from InternalCheckers.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsInternal {
get { return isInternal_; }
set {
isInternal_ = value;
}
}
/// <summary>Field number for the "internal_checkers" field.</summary>
public const int InternalCheckersFieldNumber = 14;
private static readonly pb::FieldCodec<global::Google.Cloud.Monitoring.V3.InternalChecker> _repeated_internalCheckers_codec
= pb::FieldCodec.ForMessage(114, global::Google.Cloud.Monitoring.V3.InternalChecker.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.InternalChecker> internalCheckers_ = new pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.InternalChecker>();
/// <summary>
/// The internal checkers that this check will egress from. If `is_internal` is
/// true and this list is empty, the check will egress from all
/// InternalCheckers configured for the project that owns this CheckConfig.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Monitoring.V3.InternalChecker> InternalCheckers {
get { return internalCheckers_; }
}
private object resource_;
/// <summary>Enum of possible cases for the "resource" oneof.</summary>
public enum ResourceOneofCase {
None = 0,
MonitoredResource = 3,
ResourceGroup = 4,
}
private ResourceOneofCase resourceCase_ = ResourceOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResourceOneofCase ResourceCase {
get { return resourceCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearResource() {
resourceCase_ = ResourceOneofCase.None;
resource_ = null;
}
private object checkRequestType_;
/// <summary>Enum of possible cases for the "check_request_type" oneof.</summary>
public enum CheckRequestTypeOneofCase {
None = 0,
HttpCheck = 5,
TcpCheck = 6,
}
private CheckRequestTypeOneofCase checkRequestTypeCase_ = CheckRequestTypeOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CheckRequestTypeOneofCase CheckRequestTypeCase {
get { return checkRequestTypeCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearCheckRequestType() {
checkRequestTypeCase_ = CheckRequestTypeOneofCase.None;
checkRequestType_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UptimeCheckConfig);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UptimeCheckConfig other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (DisplayName != other.DisplayName) return false;
if (!object.Equals(MonitoredResource, other.MonitoredResource)) return false;
if (!object.Equals(ResourceGroup, other.ResourceGroup)) return false;
if (!object.Equals(HttpCheck, other.HttpCheck)) return false;
if (!object.Equals(TcpCheck, other.TcpCheck)) return false;
if (!object.Equals(Period, other.Period)) return false;
if (!object.Equals(Timeout, other.Timeout)) return false;
if(!contentMatchers_.Equals(other.contentMatchers_)) return false;
if(!selectedRegions_.Equals(other.selectedRegions_)) return false;
if (IsInternal != other.IsInternal) return false;
if(!internalCheckers_.Equals(other.internalCheckers_)) return false;
if (ResourceCase != other.ResourceCase) return false;
if (CheckRequestTypeCase != other.CheckRequestTypeCase) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode();
if (resourceCase_ == ResourceOneofCase.MonitoredResource) hash ^= MonitoredResource.GetHashCode();
if (resourceCase_ == ResourceOneofCase.ResourceGroup) hash ^= ResourceGroup.GetHashCode();
if (checkRequestTypeCase_ == CheckRequestTypeOneofCase.HttpCheck) hash ^= HttpCheck.GetHashCode();
if (checkRequestTypeCase_ == CheckRequestTypeOneofCase.TcpCheck) hash ^= TcpCheck.GetHashCode();
if (period_ != null) hash ^= Period.GetHashCode();
if (timeout_ != null) hash ^= Timeout.GetHashCode();
hash ^= contentMatchers_.GetHashCode();
hash ^= selectedRegions_.GetHashCode();
if (IsInternal != false) hash ^= IsInternal.GetHashCode();
hash ^= internalCheckers_.GetHashCode();
hash ^= (int) resourceCase_;
hash ^= (int) checkRequestTypeCase_;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (DisplayName.Length != 0) {
output.WriteRawTag(18);
output.WriteString(DisplayName);
}
if (resourceCase_ == ResourceOneofCase.MonitoredResource) {
output.WriteRawTag(26);
output.WriteMessage(MonitoredResource);
}
if (resourceCase_ == ResourceOneofCase.ResourceGroup) {
output.WriteRawTag(34);
output.WriteMessage(ResourceGroup);
}
if (checkRequestTypeCase_ == CheckRequestTypeOneofCase.HttpCheck) {
output.WriteRawTag(42);
output.WriteMessage(HttpCheck);
}
if (checkRequestTypeCase_ == CheckRequestTypeOneofCase.TcpCheck) {
output.WriteRawTag(50);
output.WriteMessage(TcpCheck);
}
if (period_ != null) {
output.WriteRawTag(58);
output.WriteMessage(Period);
}
if (timeout_ != null) {
output.WriteRawTag(66);
output.WriteMessage(Timeout);
}
contentMatchers_.WriteTo(output, _repeated_contentMatchers_codec);
selectedRegions_.WriteTo(output, _repeated_selectedRegions_codec);
internalCheckers_.WriteTo(output, _repeated_internalCheckers_codec);
if (IsInternal != false) {
output.WriteRawTag(120);
output.WriteBool(IsInternal);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (DisplayName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName);
}
if (resourceCase_ == ResourceOneofCase.MonitoredResource) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(MonitoredResource);
}
if (resourceCase_ == ResourceOneofCase.ResourceGroup) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ResourceGroup);
}
if (checkRequestTypeCase_ == CheckRequestTypeOneofCase.HttpCheck) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(HttpCheck);
}
if (checkRequestTypeCase_ == CheckRequestTypeOneofCase.TcpCheck) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TcpCheck);
}
if (period_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Period);
}
if (timeout_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Timeout);
}
size += contentMatchers_.CalculateSize(_repeated_contentMatchers_codec);
size += selectedRegions_.CalculateSize(_repeated_selectedRegions_codec);
if (IsInternal != false) {
size += 1 + 1;
}
size += internalCheckers_.CalculateSize(_repeated_internalCheckers_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UptimeCheckConfig other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.DisplayName.Length != 0) {
DisplayName = other.DisplayName;
}
if (other.period_ != null) {
if (period_ == null) {
period_ = new global::Google.Protobuf.WellKnownTypes.Duration();
}
Period.MergeFrom(other.Period);
}
if (other.timeout_ != null) {
if (timeout_ == null) {
timeout_ = new global::Google.Protobuf.WellKnownTypes.Duration();
}
Timeout.MergeFrom(other.Timeout);
}
contentMatchers_.Add(other.contentMatchers_);
selectedRegions_.Add(other.selectedRegions_);
if (other.IsInternal != false) {
IsInternal = other.IsInternal;
}
internalCheckers_.Add(other.internalCheckers_);
switch (other.ResourceCase) {
case ResourceOneofCase.MonitoredResource:
if (MonitoredResource == null) {
MonitoredResource = new global::Google.Api.MonitoredResource();
}
MonitoredResource.MergeFrom(other.MonitoredResource);
break;
case ResourceOneofCase.ResourceGroup:
if (ResourceGroup == null) {
ResourceGroup = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ResourceGroup();
}
ResourceGroup.MergeFrom(other.ResourceGroup);
break;
}
switch (other.CheckRequestTypeCase) {
case CheckRequestTypeOneofCase.HttpCheck:
if (HttpCheck == null) {
HttpCheck = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck();
}
HttpCheck.MergeFrom(other.HttpCheck);
break;
case CheckRequestTypeOneofCase.TcpCheck:
if (TcpCheck == null) {
TcpCheck = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.TcpCheck();
}
TcpCheck.MergeFrom(other.TcpCheck);
break;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
DisplayName = input.ReadString();
break;
}
case 26: {
global::Google.Api.MonitoredResource subBuilder = new global::Google.Api.MonitoredResource();
if (resourceCase_ == ResourceOneofCase.MonitoredResource) {
subBuilder.MergeFrom(MonitoredResource);
}
input.ReadMessage(subBuilder);
MonitoredResource = subBuilder;
break;
}
case 34: {
global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ResourceGroup subBuilder = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.ResourceGroup();
if (resourceCase_ == ResourceOneofCase.ResourceGroup) {
subBuilder.MergeFrom(ResourceGroup);
}
input.ReadMessage(subBuilder);
ResourceGroup = subBuilder;
break;
}
case 42: {
global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck subBuilder = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck();
if (checkRequestTypeCase_ == CheckRequestTypeOneofCase.HttpCheck) {
subBuilder.MergeFrom(HttpCheck);
}
input.ReadMessage(subBuilder);
HttpCheck = subBuilder;
break;
}
case 50: {
global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.TcpCheck subBuilder = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.TcpCheck();
if (checkRequestTypeCase_ == CheckRequestTypeOneofCase.TcpCheck) {
subBuilder.MergeFrom(TcpCheck);
}
input.ReadMessage(subBuilder);
TcpCheck = subBuilder;
break;
}
case 58: {
if (period_ == null) {
period_ = new global::Google.Protobuf.WellKnownTypes.Duration();
}
input.ReadMessage(period_);
break;
}
case 66: {
if (timeout_ == null) {
timeout_ = new global::Google.Protobuf.WellKnownTypes.Duration();
}
input.ReadMessage(timeout_);
break;
}
case 74: {
contentMatchers_.AddEntriesFrom(input, _repeated_contentMatchers_codec);
break;
}
case 82:
case 80: {
selectedRegions_.AddEntriesFrom(input, _repeated_selectedRegions_codec);
break;
}
case 114: {
internalCheckers_.AddEntriesFrom(input, _repeated_internalCheckers_codec);
break;
}
case 120: {
IsInternal = input.ReadBool();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the UptimeCheckConfig message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The resource submessage for group checks. It can be used instead of a
/// monitored resource, when multiple resources are being monitored.
/// </summary>
public sealed partial class ResourceGroup : pb::IMessage<ResourceGroup> {
private static readonly pb::MessageParser<ResourceGroup> _parser = new pb::MessageParser<ResourceGroup>(() => new ResourceGroup());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ResourceGroup> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResourceGroup() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResourceGroup(ResourceGroup other) : this() {
groupId_ = other.groupId_;
resourceType_ = other.resourceType_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResourceGroup Clone() {
return new ResourceGroup(this);
}
/// <summary>Field number for the "group_id" field.</summary>
public const int GroupIdFieldNumber = 1;
private string groupId_ = "";
/// <summary>
/// The group of resources being monitored. Should be only the
/// group_id, not projects/<project_id>/groups/<group_id>.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string GroupId {
get { return groupId_; }
set {
groupId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "resource_type" field.</summary>
public const int ResourceTypeFieldNumber = 2;
private global::Google.Cloud.Monitoring.V3.GroupResourceType resourceType_ = 0;
/// <summary>
/// The resource type of the group members.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Monitoring.V3.GroupResourceType ResourceType {
get { return resourceType_; }
set {
resourceType_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ResourceGroup);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ResourceGroup other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (GroupId != other.GroupId) return false;
if (ResourceType != other.ResourceType) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (GroupId.Length != 0) hash ^= GroupId.GetHashCode();
if (ResourceType != 0) hash ^= ResourceType.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (GroupId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(GroupId);
}
if (ResourceType != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) ResourceType);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (GroupId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(GroupId);
}
if (ResourceType != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ResourceType);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ResourceGroup other) {
if (other == null) {
return;
}
if (other.GroupId.Length != 0) {
GroupId = other.GroupId;
}
if (other.ResourceType != 0) {
ResourceType = other.ResourceType;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
GroupId = input.ReadString();
break;
}
case 16: {
resourceType_ = (global::Google.Cloud.Monitoring.V3.GroupResourceType) input.ReadEnum();
break;
}
}
}
}
}
/// <summary>
/// Information involved in an HTTP/HTTPS uptime check request.
/// </summary>
public sealed partial class HttpCheck : pb::IMessage<HttpCheck> {
private static readonly pb::MessageParser<HttpCheck> _parser = new pb::MessageParser<HttpCheck>(() => new HttpCheck());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<HttpCheck> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Descriptor.NestedTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HttpCheck() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HttpCheck(HttpCheck other) : this() {
useSsl_ = other.useSsl_;
path_ = other.path_;
port_ = other.port_;
authInfo_ = other.authInfo_ != null ? other.authInfo_.Clone() : null;
maskHeaders_ = other.maskHeaders_;
headers_ = other.headers_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HttpCheck Clone() {
return new HttpCheck(this);
}
/// <summary>Field number for the "use_ssl" field.</summary>
public const int UseSslFieldNumber = 1;
private bool useSsl_;
/// <summary>
/// If true, use HTTPS instead of HTTP to run the check.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool UseSsl {
get { return useSsl_; }
set {
useSsl_ = value;
}
}
/// <summary>Field number for the "path" field.</summary>
public const int PathFieldNumber = 2;
private string path_ = "";
/// <summary>
/// The path to the page to run the check against. Will be combined with the
/// host (specified within the MonitoredResource) and port to construct the
/// full URL. Optional (defaults to "/").
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Path {
get { return path_; }
set {
path_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "port" field.</summary>
public const int PortFieldNumber = 3;
private int port_;
/// <summary>
/// The port to the page to run the check against. Will be combined with host
/// (specified within the MonitoredResource) and path to construct the full
/// URL. Optional (defaults to 80 without SSL, or 443 with SSL).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Port {
get { return port_; }
set {
port_ = value;
}
}
/// <summary>Field number for the "auth_info" field.</summary>
public const int AuthInfoFieldNumber = 4;
private global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck.Types.BasicAuthentication authInfo_;
/// <summary>
/// The authentication information. Optional when creating an HTTP check;
/// defaults to empty.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck.Types.BasicAuthentication AuthInfo {
get { return authInfo_; }
set {
authInfo_ = value;
}
}
/// <summary>Field number for the "mask_headers" field.</summary>
public const int MaskHeadersFieldNumber = 5;
private bool maskHeaders_;
/// <summary>
/// Boolean specifiying whether to encrypt the header information.
/// Encryption should be specified for any headers related to authentication
/// that you do not wish to be seen when retrieving the configuration. The
/// server will be responsible for encrypting the headers.
/// On Get/List calls, if mask_headers is set to True then the headers
/// will be obscured with ******.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool MaskHeaders {
get { return maskHeaders_; }
set {
maskHeaders_ = value;
}
}
/// <summary>Field number for the "headers" field.</summary>
public const int HeadersFieldNumber = 6;
private static readonly pbc::MapField<string, string>.Codec _map_headers_codec
= new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForString(18), 50);
private readonly pbc::MapField<string, string> headers_ = new pbc::MapField<string, string>();
/// <summary>
/// The list of headers to send as part of the uptime check request.
/// If two headers have the same key and different values, they should
/// be entered as a single header, with the value being a comma-separated
/// list of all the desired values as described at
/// https://www.w3.org/Protocols/rfc2616/rfc2616.txt (page 31).
/// Entering two separate headers with the same key in a Create call will
/// cause the first to be overwritten by the second.
/// The maximum number of headers allowed is 100.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, string> Headers {
get { return headers_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as HttpCheck);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(HttpCheck other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (UseSsl != other.UseSsl) return false;
if (Path != other.Path) return false;
if (Port != other.Port) return false;
if (!object.Equals(AuthInfo, other.AuthInfo)) return false;
if (MaskHeaders != other.MaskHeaders) return false;
if (!Headers.Equals(other.Headers)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (UseSsl != false) hash ^= UseSsl.GetHashCode();
if (Path.Length != 0) hash ^= Path.GetHashCode();
if (Port != 0) hash ^= Port.GetHashCode();
if (authInfo_ != null) hash ^= AuthInfo.GetHashCode();
if (MaskHeaders != false) hash ^= MaskHeaders.GetHashCode();
hash ^= Headers.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (UseSsl != false) {
output.WriteRawTag(8);
output.WriteBool(UseSsl);
}
if (Path.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Path);
}
if (Port != 0) {
output.WriteRawTag(24);
output.WriteInt32(Port);
}
if (authInfo_ != null) {
output.WriteRawTag(34);
output.WriteMessage(AuthInfo);
}
if (MaskHeaders != false) {
output.WriteRawTag(40);
output.WriteBool(MaskHeaders);
}
headers_.WriteTo(output, _map_headers_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (UseSsl != false) {
size += 1 + 1;
}
if (Path.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Path);
}
if (Port != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Port);
}
if (authInfo_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(AuthInfo);
}
if (MaskHeaders != false) {
size += 1 + 1;
}
size += headers_.CalculateSize(_map_headers_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(HttpCheck other) {
if (other == null) {
return;
}
if (other.UseSsl != false) {
UseSsl = other.UseSsl;
}
if (other.Path.Length != 0) {
Path = other.Path;
}
if (other.Port != 0) {
Port = other.Port;
}
if (other.authInfo_ != null) {
if (authInfo_ == null) {
authInfo_ = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck.Types.BasicAuthentication();
}
AuthInfo.MergeFrom(other.AuthInfo);
}
if (other.MaskHeaders != false) {
MaskHeaders = other.MaskHeaders;
}
headers_.Add(other.headers_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
UseSsl = input.ReadBool();
break;
}
case 18: {
Path = input.ReadString();
break;
}
case 24: {
Port = input.ReadInt32();
break;
}
case 34: {
if (authInfo_ == null) {
authInfo_ = new global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck.Types.BasicAuthentication();
}
input.ReadMessage(authInfo_);
break;
}
case 40: {
MaskHeaders = input.ReadBool();
break;
}
case 50: {
headers_.AddEntriesFrom(input, _map_headers_codec);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the HttpCheck message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// A type of authentication to perform against the specified resource or URL
/// that uses username and password.
/// Currently, only Basic authentication is supported in Uptime Monitoring.
/// </summary>
public sealed partial class BasicAuthentication : pb::IMessage<BasicAuthentication> {
private static readonly pb::MessageParser<BasicAuthentication> _parser = new pb::MessageParser<BasicAuthentication>(() => new BasicAuthentication());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<BasicAuthentication> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Types.HttpCheck.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BasicAuthentication() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BasicAuthentication(BasicAuthentication other) : this() {
username_ = other.username_;
password_ = other.password_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BasicAuthentication Clone() {
return new BasicAuthentication(this);
}
/// <summary>Field number for the "username" field.</summary>
public const int UsernameFieldNumber = 1;
private string username_ = "";
/// <summary>
/// The username to authenticate.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Username {
get { return username_; }
set {
username_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "password" field.</summary>
public const int PasswordFieldNumber = 2;
private string password_ = "";
/// <summary>
/// The password to authenticate.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Password {
get { return password_; }
set {
password_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as BasicAuthentication);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(BasicAuthentication other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Username != other.Username) return false;
if (Password != other.Password) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Username.Length != 0) hash ^= Username.GetHashCode();
if (Password.Length != 0) hash ^= Password.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Username.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Username);
}
if (Password.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Password);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Username.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Username);
}
if (Password.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Password);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(BasicAuthentication other) {
if (other == null) {
return;
}
if (other.Username.Length != 0) {
Username = other.Username;
}
if (other.Password.Length != 0) {
Password = other.Password;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Username = input.ReadString();
break;
}
case 18: {
Password = input.ReadString();
break;
}
}
}
}
}
}
#endregion
}
/// <summary>
/// Information required for a TCP uptime check request.
/// </summary>
public sealed partial class TcpCheck : pb::IMessage<TcpCheck> {
private static readonly pb::MessageParser<TcpCheck> _parser = new pb::MessageParser<TcpCheck>(() => new TcpCheck());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TcpCheck> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Descriptor.NestedTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TcpCheck() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TcpCheck(TcpCheck other) : this() {
port_ = other.port_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TcpCheck Clone() {
return new TcpCheck(this);
}
/// <summary>Field number for the "port" field.</summary>
public const int PortFieldNumber = 1;
private int port_;
/// <summary>
/// The port to the page to run the check against. Will be combined with host
/// (specified within the MonitoredResource) to construct the full URL.
/// Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Port {
get { return port_; }
set {
port_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TcpCheck);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TcpCheck other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Port != other.Port) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Port != 0) hash ^= Port.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Port != 0) {
output.WriteRawTag(8);
output.WriteInt32(Port);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Port != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Port);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TcpCheck other) {
if (other == null) {
return;
}
if (other.Port != 0) {
Port = other.Port;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Port = input.ReadInt32();
break;
}
}
}
}
}
/// <summary>
/// Used to perform string matching. Currently, this matches on the exact
/// content. In the future, it can be expanded to allow for regular expressions
/// and more complex matching.
/// </summary>
public sealed partial class ContentMatcher : pb::IMessage<ContentMatcher> {
private static readonly pb::MessageParser<ContentMatcher> _parser = new pb::MessageParser<ContentMatcher>(() => new ContentMatcher());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ContentMatcher> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Monitoring.V3.UptimeCheckConfig.Descriptor.NestedTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ContentMatcher() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ContentMatcher(ContentMatcher other) : this() {
content_ = other.content_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ContentMatcher Clone() {
return new ContentMatcher(this);
}
/// <summary>Field number for the "content" field.</summary>
public const int ContentFieldNumber = 1;
private string content_ = "";
/// <summary>
/// String content to match (max 1024 bytes)
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Content {
get { return content_; }
set {
content_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ContentMatcher);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ContentMatcher other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Content != other.Content) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Content.Length != 0) hash ^= Content.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Content.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Content);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Content.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Content);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ContentMatcher other) {
if (other == null) {
return;
}
if (other.Content.Length != 0) {
Content = other.Content;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Content = input.ReadString();
break;
}
}
}
}
}
}
#endregion
}
/// <summary>
/// Contains the region, location, and list of IP
/// addresses where checkers in the location run from.
/// </summary>
public sealed partial class UptimeCheckIp : pb::IMessage<UptimeCheckIp> {
private static readonly pb::MessageParser<UptimeCheckIp> _parser = new pb::MessageParser<UptimeCheckIp>(() => new UptimeCheckIp());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UptimeCheckIp> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Monitoring.V3.UptimeReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UptimeCheckIp() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UptimeCheckIp(UptimeCheckIp other) : this() {
region_ = other.region_;
location_ = other.location_;
ipAddress_ = other.ipAddress_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UptimeCheckIp Clone() {
return new UptimeCheckIp(this);
}
/// <summary>Field number for the "region" field.</summary>
public const int RegionFieldNumber = 1;
private global::Google.Cloud.Monitoring.V3.UptimeCheckRegion region_ = 0;
/// <summary>
/// A broad region category in which the IP address is located.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Monitoring.V3.UptimeCheckRegion Region {
get { return region_; }
set {
region_ = value;
}
}
/// <summary>Field number for the "location" field.</summary>
public const int LocationFieldNumber = 2;
private string location_ = "";
/// <summary>
/// A more specific location within the region that typically encodes
/// a particular city/town/metro (and its containing state/province or country)
/// within the broader umbrella region category.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Location {
get { return location_; }
set {
location_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "ip_address" field.</summary>
public const int IpAddressFieldNumber = 3;
private string ipAddress_ = "";
/// <summary>
/// The IP address from which the uptime check originates. This is a full
/// IP address (not an IP address range). Most IP addresses, as of this
/// publication, are in IPv4 format; however, one should not rely on the
/// IP addresses being in IPv4 format indefinitely and should support
/// interpreting this field in either IPv4 or IPv6 format.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string IpAddress {
get { return ipAddress_; }
set {
ipAddress_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UptimeCheckIp);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UptimeCheckIp other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Region != other.Region) return false;
if (Location != other.Location) return false;
if (IpAddress != other.IpAddress) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Region != 0) hash ^= Region.GetHashCode();
if (Location.Length != 0) hash ^= Location.GetHashCode();
if (IpAddress.Length != 0) hash ^= IpAddress.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Region != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Region);
}
if (Location.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Location);
}
if (IpAddress.Length != 0) {
output.WriteRawTag(26);
output.WriteString(IpAddress);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Region != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Region);
}
if (Location.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Location);
}
if (IpAddress.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(IpAddress);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UptimeCheckIp other) {
if (other == null) {
return;
}
if (other.Region != 0) {
Region = other.Region;
}
if (other.Location.Length != 0) {
Location = other.Location;
}
if (other.IpAddress.Length != 0) {
IpAddress = other.IpAddress;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
region_ = (global::Google.Cloud.Monitoring.V3.UptimeCheckRegion) input.ReadEnum();
break;
}
case 18: {
Location = input.ReadString();
break;
}
case 26: {
IpAddress = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| {
"content_hash": "18a545f645efc773e4c8f6608fa8bbfa",
"timestamp": "",
"source": "github",
"line_count": 2123,
"max_line_length": 681,
"avg_line_length": 39.58078191238813,
"alnum_prop": 0.6255384981554207,
"repo_name": "iantalarico/google-cloud-dotnet",
"id": "9b182ccf097c9b6f1df9d446f0d1b99b75192f75",
"size": "84258",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3/Uptime.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "759"
},
{
"name": "C#",
"bytes": "28164658"
},
{
"name": "PowerShell",
"bytes": "3303"
},
{
"name": "Python",
"bytes": "69507"
},
{
"name": "Shell",
"bytes": "26807"
}
],
"symlink_target": ""
} |
'use strict';
/**
* Properties of a managed identity
*
*/
class IdentityProperties {
/**
* Create a IdentityProperties.
* @property {string} [type] Managed identity.
* @property {string} [principalId] The principal id of resource identity.
* @property {string} [tenantId] The tenant identifier of resource.
* @property {string} [clientSecretUrl] The client secret URL of the
* identity.
*/
constructor() {
}
/**
* Defines the metadata of IdentityProperties
*
* @returns {object} metadata of IdentityProperties
*
*/
mapper() {
return {
required: false,
serializedName: 'IdentityProperties',
type: {
name: 'Composite',
className: 'IdentityProperties',
modelProperties: {
type: {
required: false,
serializedName: 'type',
type: {
name: 'String'
}
},
principalId: {
required: false,
serializedName: 'principalId',
type: {
name: 'String'
}
},
tenantId: {
required: false,
serializedName: 'tenantId',
type: {
name: 'String'
}
},
clientSecretUrl: {
required: false,
serializedName: 'clientSecretUrl',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = IdentityProperties;
| {
"content_hash": "9ae1e3dbd6366b9ed76ec022a974e120",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 76,
"avg_line_length": 21.971014492753625,
"alnum_prop": 0.5032981530343008,
"repo_name": "xingwu1/azure-sdk-for-node",
"id": "ebb6ea256daa9a664791321eab266aeb289fb096",
"size": "1833",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/services/devTestLabs/lib/models/identityProperties.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "661"
},
{
"name": "JavaScript",
"bytes": "122792600"
},
{
"name": "Shell",
"bytes": "437"
},
{
"name": "TypeScript",
"bytes": "2558"
}
],
"symlink_target": ""
} |
<HTML><HEAD>
<TITLE>Review for Iron Giant, The (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0129167">Iron Giant, The (1999)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Shay+Casey">Shay Casey</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>***1/2 out of ****</PRE>
<PRE>Year: 1999.
Starring the voices of Eli Marienthal, Jennifer Aniston, Harry Connick Jr.,
Vin Diesel, Christopher McDonald, Cloris Leachman, John Mahoney, M. Emmett
Walsh.
Screenplay by Tim McCanlies.
Directed by Brad Bird.
Rated PG.</PRE>
<P>Why do so many children's films treat their target audience with utter
contempt? Too many of those who write or direct for children's movies assume
that the kids just can't handle serious, thoughtful discussions on
meaningful issues. "The Iron Giant," which was directed and co-written by
Brad Bird, late of such animated series as "The Simpsons" and "King of the
Hill," assumes that not only can children handle such discussions, but that
they can do so while being entertained at the same time. "The Iron Giant"
holds absolutely no contempt for the young people in the audience, making it
a film that's enjoyable for both children and adults alike.</P>
<P>Hogarth Hughes (voice of Eli Marienthal) is a spirited young lad who lives
with his hard-working single mother, Annie (Jennifer Aniston), in a small
town in Maine. After staying up late and watching scary movies on a night
his mother is away, Hogarth treks out into the forest to investigate what
has stolen his antenna and ruined his TV reception. He comes across a giant
robot (Vin Diesel) from space that eats metal for food. After saving the
robot, nicknamed the Iron Giant, from electric shock, Hogarth befriends the
creature and takes him in as a pet of sorts. Because of damage he suffered
upon landing, the Giant has forgotten what his original mission was, so he
just follows Hogarth around like a lost puppy. Realizing he can't just keep
the Giant in a barn all the time, and that the Giant needs food, he takes
him to a junkyard owned by Dean (Harry Connick Jr.), an eccentric artist who
assembles sculptures out of scrap iron in his spare time. It soon becomes
apparent that Dean and Hogarth can't keep the Giant a secret forever,
because a government spook named Kent Mansley (Christopher McDonald) has
been brought in to investigate mysterious sightings in the surrounding
forest area and considers the Giant a threat to national security. He
suspects Hogarth knows something about the Giant, and takes up residence in
Hogarth's house as a lodger. Meanwhile, the Giant begins to exhibit ominous
behavior that suggests he was built to be a weapon of some kind.</P>
<P>"The Iron Giant" is exactly what family films ought to be, because it doesn'
t talk down to its audience. The story is simple, very simple, about an
alien being that drops out of the sky and befriends a young boy. It's very
similar to the Spielberg classic "E.T.,' and such comparisons are actually
deserved in the case of "The Iron Giant." The film holds many of the better
elements of Spielberg's film, such as the ability to be sentimental without
turning sappy. The film delivers several serious messages, the most
important of which is one's ability to choose one's own fate. Hogarth
teaches the Giant to go against his programming and become what he wants to
be: a hero. The final sequence is touching and appropriate, though I won't
give it away, I will say that very few will be disappointed.</P>
<P>The animation, while not up to Disney standards (what could be, after
"Tarzan"?), is good enough to make you forget you're watching a cartoon. The
Giant is computer-animated, while the human characters are all hand-drawn
the old-fashioned way. The characters' faces are done quite well, drawn
realistically enough to make the personalities credible, but the features
are exaggerated so as to allow for the cartoonish expressions that provide
for comic relief. Fine voice work is turned in by young Eli Marienthal as
Hogarth, and Jennifer Aniston is surprisingly convincing as his waitress
mother. Harry Connick Jr. does a nice characterization as Dean, and I really
enjoyed the voice work of John Mahoney (of TV's "Frasier") as an Army
General called in by Agent Mansley. Unlike several cartoon features, each
character is actually a developed personality, rather than a stereotype, and
is actually integral to the plot, rather than being a superfluous
comic-relief sidekick (a cliché Disney still hasn't ditched). Dean, for
example, could have been a stereotypical beatnik (his character profile
seems to suggest that), but he is presented as a character with real
emotions, thoughts, and motivations. Even the heavy, Agent Mansley, is not a
villain who does bad things simply because he wants to, but out of his own
fear and paranoia. A lesser animated feature would have drawn up paper-thin
stereotypes and figure the kids won't mind, but "The Iron Giant" has clearly
put a little work into making the characters real, and it pays off.</P>
<P>The film isn't only around to deliver heavy-handed messages, though. It's
also very funny, and the humor is of the kind that both children and adults
will enjoy. The scenes in which Hogarth teaches the Giant to do certain
things, such as dive into a pool, are handled well, and director Brad Bird
clearly has a sense of comic timing, having worked on "The Simpsons" for
many years. A sequence where Hogarth and Mansley attempt to "outlast" one
another by trying to stay awake is very nicely timed, and also extremely
clever. The film even takes some jabs at America's nuclear paranoia during
the early stages of the Cold War, satirizing the lame safety films shown to
grade school students that tell them to "duck and cover" in the event of a
nuclear attack. "The Iron Giant" has much more of a satirical edge to it
than most family films, and the edgy humor is actually quite refreshing.
Instead of seeing people get bonked on the head, we get well-timed, clever
gags that seem to have required some imagination to come up with.</P>
<P>When you get right down to it, "The Iron Giant" is no more than the story of
a boy and his robot. The story is so straightforward, so quaint, that it
ultimately becomes charming. Though I enjoy the complex plotting of film
noir as much as the next person, when it comes to family entertainment,
simple is the way to go. It's akin to one of those bedtime stories your
father told that had you hanging on his every word, but it's not the story
that sets the film above others of its kind, but rather the elements that go
into the story, namely real characters and thoughtful dialogue, which "The
Iron Giant" has in spades.</P>
<PRE>-reviewed by Shay Casey</PRE>
<P>For more reviews, go to
<A HREF="http://www.geocities.com/Hollywood/Land/4252/movies.html">http://www.geocities.com/Hollywood/Land/4252/movies.html</A></P>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {
"content_hash": "854a410c5b937ed2aba2f85e19a2e1a1",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 197,
"avg_line_length": 68.06896551724138,
"alnum_prop": 0.7691236068895644,
"repo_name": "xianjunzhengbackup/code",
"id": "dc5fa1fa7740b9a70c266e0f97f1998a94c27687",
"size": "7896",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data science/machine_learning_for_the_web/chapter_4/movie/23115.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "BitBake",
"bytes": "113"
},
{
"name": "BlitzBasic",
"bytes": "256"
},
{
"name": "CSS",
"bytes": "49827"
},
{
"name": "HTML",
"bytes": "157006325"
},
{
"name": "JavaScript",
"bytes": "14029"
},
{
"name": "Jupyter Notebook",
"bytes": "4875399"
},
{
"name": "Mako",
"bytes": "2060"
},
{
"name": "Perl",
"bytes": "716"
},
{
"name": "Python",
"bytes": "874414"
},
{
"name": "R",
"bytes": "454"
},
{
"name": "Shell",
"bytes": "3984"
}
],
"symlink_target": ""
} |
package org.hisp.dhis.analytics.event.data;
import static org.hisp.dhis.analytics.event.EventAnalyticsService.ITEM_CREATED_BY_DISPLAY_NAME;
import static org.hisp.dhis.analytics.event.EventAnalyticsService.ITEM_ENROLLMENT_DATE;
import static org.hisp.dhis.analytics.event.EventAnalyticsService.ITEM_EVENT_DATE;
import static org.hisp.dhis.analytics.event.EventAnalyticsService.ITEM_EVENT_STATUS;
import static org.hisp.dhis.analytics.event.EventAnalyticsService.ITEM_INCIDENT_DATE;
import static org.hisp.dhis.analytics.event.EventAnalyticsService.ITEM_LAST_UPDATED;
import static org.hisp.dhis.analytics.event.EventAnalyticsService.ITEM_LAST_UPDATED_BY_DISPLAY_NAME;
import static org.hisp.dhis.analytics.event.EventAnalyticsService.ITEM_ORG_UNIT_CODE;
import static org.hisp.dhis.analytics.event.EventAnalyticsService.ITEM_ORG_UNIT_NAME;
import static org.hisp.dhis.analytics.event.EventAnalyticsService.ITEM_PROGRAM_STATUS;
import static org.hisp.dhis.analytics.event.EventAnalyticsService.ITEM_SCHEDULED_DATE;
import static org.hisp.dhis.analytics.event.data.DefaultEventCoordinateService.COL_NAME_GEOMETRY_LIST;
import static org.hisp.dhis.analytics.event.data.DefaultEventCoordinateService.COL_NAME_PI_GEOMETRY;
import static org.hisp.dhis.analytics.event.data.DefaultEventCoordinateService.COL_NAME_PSI_GEOMETRY;
import static org.hisp.dhis.analytics.event.data.DefaultEventCoordinateService.COL_NAME_TEI_GEOMETRY;
import static org.hisp.dhis.analytics.event.data.DefaultEventDataQueryService.SortableItems.isSortable;
import static org.hisp.dhis.analytics.event.data.DefaultEventDataQueryService.SortableItems.translateItemIfNecessary;
import static org.hisp.dhis.analytics.util.AnalyticsUtils.throwIllegalQueryEx;
import static org.hisp.dhis.common.DimensionalObject.DIMENSION_NAME_SEP;
import static org.hisp.dhis.common.DimensionalObject.PERIOD_DIM_ID;
import static org.hisp.dhis.common.DimensionalObjectUtils.getDimensionFromParam;
import static org.hisp.dhis.common.DimensionalObjectUtils.getDimensionItemsFromParam;
import static org.hisp.dhis.common.DimensionalObjectUtils.getDimensionalItemIds;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.analytics.AnalyticsAggregationType;
import org.hisp.dhis.analytics.DataQueryService;
import org.hisp.dhis.analytics.EventOutputType;
import org.hisp.dhis.analytics.OrgUnitField;
import org.hisp.dhis.analytics.event.EventDataQueryService;
import org.hisp.dhis.analytics.event.EventQueryParams;
import org.hisp.dhis.analytics.event.QueryItemLocator;
import org.hisp.dhis.common.BaseDimensionalItemObject;
import org.hisp.dhis.common.DimensionalItemObject;
import org.hisp.dhis.common.DimensionalObject;
import org.hisp.dhis.common.EventAnalyticalObject;
import org.hisp.dhis.common.EventDataQueryRequest;
import org.hisp.dhis.common.GroupableItem;
import org.hisp.dhis.common.IdScheme;
import org.hisp.dhis.common.IllegalQueryException;
import org.hisp.dhis.common.QueryFilter;
import org.hisp.dhis.common.QueryItem;
import org.hisp.dhis.common.QueryOperator;
import org.hisp.dhis.common.RequestTypeAware;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.commons.collection.ListUtils;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementService;
import org.hisp.dhis.feedback.ErrorCode;
import org.hisp.dhis.feedback.ErrorMessage;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramService;
import org.hisp.dhis.program.ProgramStage;
import org.hisp.dhis.program.ProgramStageService;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.hisp.dhis.trackedentity.TrackedEntityAttributeService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import com.google.common.base.MoreObjects;
/**
* @author Lars Helge Overland
*/
@Service( "org.hisp.dhis.analytics.event.EventDataQueryService" )
@RequiredArgsConstructor
public class DefaultEventDataQueryService
implements EventDataQueryService
{
private static final String COL_NAME_PROGRAM_STATUS_EVENTS = "pistatus";
private static final String COL_NAME_PROGRAM_STATUS_ENROLLMENTS = "enrollmentstatus";
private static final String COL_NAME_EVENT_STATUS = "psistatus";
private static final String COL_NAME_EVENTDATE = "executiondate";
private static final String COL_NAME_ENROLLMENTDATE = "enrollmentdate";
private static final String COL_NAME_INCIDENTDATE = "incidentdate";
private static final String COL_NAME_DUEDATE = "duedate";
private final ProgramService programService;
private final ProgramStageService programStageService;
private final DataElementService dataElementService;
private final EventCoordinateService eventCoordinateService;
private final QueryItemLocator queryItemLocator;
private final TrackedEntityAttributeService attributeService;
private final DataQueryService dataQueryService;
@Override
public EventQueryParams getFromRequest( EventDataQueryRequest request )
{
return getFromRequest( request, false );
}
@Override
public EventQueryParams getFromRequest( EventDataQueryRequest request, boolean analyzeOnly )
{
EventQueryParams.Builder params = new EventQueryParams.Builder();
IdScheme idScheme = IdScheme.UID;
List<OrganisationUnit> userOrgUnits = dataQueryService.getUserOrgUnits( null, request.getUserOrgUnit() );
Program pr = programService.getProgram( request.getProgram() );
if ( pr == null )
{
throwIllegalQueryEx( ErrorCode.E7129, request.getProgram() );
}
ProgramStage ps = programStageService.getProgramStage( request.getStage() );
if ( StringUtils.isNotEmpty( request.getStage() ) && ps == null )
{
throwIllegalQueryEx( ErrorCode.E7130, request.getStage() );
}
addDimensionsIntoParams( params, request, userOrgUnits, pr, idScheme );
addFiltersIntoParams( params, request, userOrgUnits, pr, idScheme );
addSortIntoParams( params, request, pr );
if ( request.getAggregationType() != null )
{
params.withAggregationType( AnalyticsAggregationType.fromAggregationType( request.getAggregationType() ) );
}
EventQueryParams.Builder builder = params
.withValue( getValueDimension( request.getValue() ) )
.withSkipRounding( request.isSkipRounding() )
.withShowHierarchy( request.isShowHierarchy() )
.withSortOrder( request.getSortOrder() )
.withLimit( request.getLimit() )
.withOutputType( MoreObjects.firstNonNull( request.getOutputType(), EventOutputType.EVENT ) )
.withCollapseDataDimensions( request.isCollapseDataDimensions() )
.withAggregateData( request.isAggregateData() )
.withProgram( pr )
.withProgramStage( ps )
.withStartDate( request.getStartDate() )
.withEndDate( request.getEndDate() )
.withOrganisationUnitMode( request.getOuMode() )
.withSkipMeta( request.isSkipMeta() )
.withSkipData( request.isSkipData() )
.withCompletedOnly( request.isCompletedOnly() )
.withHierarchyMeta( request.isHierarchyMeta() )
.withCoordinatesOnly( request.isCoordinatesOnly() )
.withIncludeMetadataDetails( request.isIncludeMetadataDetails() )
.withDataIdScheme( request.getDataIdScheme() )
.withOutputIdScheme( request.getOutputIdScheme() )
.withEventStatuses( request.getEventStatus() )
.withDisplayProperty( request.getDisplayProperty() )
.withTimeField( request.getTimeField() )
.withOrgUnitField( new OrgUnitField( request.getOrgUnitField() ) )
.withCoordinateFields( getCoordinateFields( request.getProgram(), request.getCoordinateField(),
request.getFallbackCoordinateField(), request.isDefaultCoordinateFallback() ) )
.withHeaders( request.getHeaders() )
.withPage( request.getPage() )
.withPageSize( request.getPageSize() )
.withPaging( request.isPaging() )
.withTotalPages( request.isTotalPages() )
.withProgramStatuses( request.getProgramStatus() )
.withApiVersion( request.getApiVersion() )
.withEnhancedConditions( request.isEnhancedConditions() )
.withEndpointItem( request.getEndpointItem() );
if ( analyzeOnly )
{
builder = builder
.withSkipData( true )
.withAnalyzeOrderId();
}
EventQueryParams eventQueryParams = builder.build();
// partitioning can be used only when default period is specified.
// empty period dimension means default period.
if ( hasPeriodDimension( eventQueryParams ) && hasNotDefaultPeriod( eventQueryParams ) )
{
builder.withSkipPartitioning( true );
eventQueryParams = builder.build();
}
return eventQueryParams;
}
private boolean hasPeriodDimension( EventQueryParams eventQueryParams )
{
return Objects.nonNull( getPeriodDimension( eventQueryParams ) );
}
private boolean hasNotDefaultPeriod( EventQueryParams eventQueryParams )
{
return Optional.ofNullable( getPeriodDimension( eventQueryParams ) )
.map( DimensionalObject::getItems )
.orElse( Collections.emptyList() )
.stream()
.noneMatch( this::isDefaultPeriod );
}
private DimensionalObject getPeriodDimension( EventQueryParams eventQueryParams )
{
return eventQueryParams.getDimension( PERIOD_DIM_ID );
}
private boolean isDefaultPeriod( DimensionalItemObject dimensionalItemObject )
{
return ((Period) dimensionalItemObject).isDefault();
}
private void addSortIntoParams( EventQueryParams.Builder params, EventDataQueryRequest request, Program pr )
{
if ( request.getAsc() != null )
{
for ( String sort : request.getAsc() )
{
params.addAscSortItem( getSortItem( sort, pr, request.getOutputType(), request.getEndpointItem() ) );
}
}
if ( request.getDesc() != null )
{
for ( String sort : request.getDesc() )
{
params.addDescSortItem( getSortItem( sort, pr, request.getOutputType(), request.getEndpointItem() ) );
}
}
}
private void addFiltersIntoParams( EventQueryParams.Builder params, EventDataQueryRequest request,
List<OrganisationUnit> userOrgUnits, Program pr, IdScheme idScheme )
{
if ( request.getFilter() != null )
{
for ( Set<String> filterGroup : request.getFilter() )
{
UUID groupUUID = UUID.randomUUID();
for ( String dim : filterGroup )
{
String dimensionId = getDimensionFromParam( dim );
List<String> items = getDimensionItemsFromParam( dim );
GroupableItem groupableItem = dataQueryService.getDimension( dimensionId,
items, request.getRelativePeriodDate(), userOrgUnits, true, idScheme );
if ( groupableItem != null )
{
params.addFilter( (DimensionalObject) groupableItem );
}
else
{
groupableItem = getQueryItem( dim, pr, request.getOutputType() );
params.addItemFilter( (QueryItem) groupableItem );
}
groupableItem.setGroupUUID( groupUUID );
}
}
}
}
private void addDimensionsIntoParams( EventQueryParams.Builder params, EventDataQueryRequest request,
List<OrganisationUnit> userOrgUnits, Program pr, IdScheme idScheme )
{
if ( request.getDimension() != null )
{
for ( Set<String> dimensionGroup : request.getDimension() )
{
UUID groupUUID = UUID.randomUUID();
for ( String dim : dimensionGroup )
{
String dimensionId = getDimensionFromParam( dim );
List<String> items = getDimensionItemsFromParam( dim );
GroupableItem groupableItem = dataQueryService.getDimension( dimensionId,
items, request, userOrgUnits, true, idScheme );
if ( groupableItem != null )
{
params.addDimension( (DimensionalObject) groupableItem );
}
else
{
groupableItem = getQueryItem( dim, pr, request.getOutputType() );
params.addItem( (QueryItem) groupableItem );
}
groupableItem.setGroupUUID( groupUUID );
}
}
}
}
@Override
public EventQueryParams getFromAnalyticalObject( EventAnalyticalObject object )
{
Assert.notNull( object, "Event analytical object cannot be null" );
Assert.notNull( object.getProgram(), "Event analytical object must specify a program" );
EventQueryParams.Builder params = new EventQueryParams.Builder();
IdScheme idScheme = IdScheme.UID;
Date date = object.getRelativePeriodDate();
object.populateAnalyticalProperties();
for ( DimensionalObject dimension : ListUtils.union( object.getColumns(), object.getRows() ) )
{
DimensionalObject dimObj = dataQueryService.getDimension( dimension.getDimension(),
getDimensionalItemIds( dimension.getItems() ), date, null, true, idScheme );
if ( dimObj != null )
{
params.addDimension( dimObj );
}
else
{
params.addItem( getQueryItem( dimension.getDimension(), dimension.getFilter(), object.getProgram(),
object.getOutputType() ) );
}
}
for ( DimensionalObject filter : object.getFilters() )
{
DimensionalObject dimObj = dataQueryService.getDimension( filter.getDimension(),
getDimensionalItemIds( filter.getItems() ), date, null, true, idScheme );
if ( dimObj != null )
{
params.addFilter( dimObj );
}
else
{
params.addItemFilter( getQueryItem( filter.getDimension(), filter.getFilter(), object.getProgram(),
object.getOutputType() ) );
}
}
return params
.withProgram( object.getProgram() )
.withProgramStage( object.getProgramStage() )
.withStartDate( object.getStartDate() )
.withEndDate( object.getEndDate() )
.withValue( object.getValue() )
.withOutputType( object.getOutputType() )
.build();
}
/**
* Returns list of coordinateFields.
*
* All possible coordinate fields are collected. The order defines the
* priority of geometries and is used as a paramaters in sql coalesce
* function
*
* @param program dhis program instance.
* @param coordinateField the coordinate field.
* @param fallbackCoordinateField the fallback coordinate field applied if
* coordinate field in result set is null.
* @param defaultCoordinateFallback flag for cascade fallback, first not
* null geometry (coalesce) will be applied.
* @return the coordinate column list.
*/
@Override
public List<String> getCoordinateFields( String program, String coordinateField,
String fallbackCoordinateField, boolean defaultCoordinateFallback )
{
// despite the fact it is nice to have no duplications, it can't be Set
// cause the order inside the collection (set add existing value and
// remove the old one)
List<String> coordinateFields = new ArrayList<>();
if ( coordinateField == null )
{
coordinateFields.add( StringUtils.EMPTY );
}
else if ( COL_NAME_GEOMETRY_LIST.contains( coordinateField ) )
{
coordinateFields
.add( eventCoordinateService.getCoordinateFieldOrFail( program, coordinateField, ErrorCode.E7221 ) );
}
else if ( EventQueryParams.EVENT_COORDINATE_FIELD.equals( coordinateField ) )
{
coordinateFields.add(
eventCoordinateService.getCoordinateFieldOrFail( program, COL_NAME_PSI_GEOMETRY, ErrorCode.E7221 ) );
}
else if ( EventQueryParams.ENROLLMENT_COORDINATE_FIELD.equals( coordinateField ) )
{
coordinateFields.add(
eventCoordinateService.getCoordinateFieldOrFail( program, COL_NAME_PI_GEOMETRY, ErrorCode.E7221 ) );
}
else if ( EventQueryParams.TRACKER_COORDINATE_FIELD.equals( coordinateField ) )
{
coordinateFields.add(
eventCoordinateService.getCoordinateFieldOrFail( program, COL_NAME_TEI_GEOMETRY, ErrorCode.E7221 ) );
}
DataElement dataElement = dataElementService.getDataElement( coordinateField );
if ( dataElement != null )
{
coordinateFields
.add( eventCoordinateService.getCoordinateFieldOrFail( dataElement.getValueType(), coordinateField,
ErrorCode.E7219 ) );
}
TrackedEntityAttribute attribute = attributeService.getTrackedEntityAttribute( coordinateField );
if ( attribute != null )
{
coordinateFields
.add( eventCoordinateService.getCoordinateFieldOrFail( attribute.getValueType(), coordinateField,
ErrorCode.E7220 ) );
}
if ( coordinateFields.isEmpty() )
{
throw new IllegalQueryException( new ErrorMessage( ErrorCode.E7221, coordinateField ) );
}
coordinateFields.remove( StringUtils.EMPTY );
coordinateFields
.addAll( eventCoordinateService.getFallbackCoordinateFields( program, fallbackCoordinateField,
defaultCoordinateFallback ) );
return coordinateFields.stream().distinct().collect( Collectors.toList() );
}
// -------------------------------------------------------------------------
// Supportive methods
// -------------------------------------------------------------------------
private QueryItem getQueryItem( String dimension, String filter, Program program, EventOutputType type )
{
if ( filter != null )
{
dimension += DIMENSION_NAME_SEP + filter;
}
return getQueryItem( dimension, program, type );
}
@Override
public QueryItem getQueryItem( String dimensionString, Program program, EventOutputType type )
{
String[] split = dimensionString.split( DIMENSION_NAME_SEP );
if ( split.length % 2 != 1 )
{
throwIllegalQueryEx( ErrorCode.E7222, dimensionString );
}
QueryItem queryItem = queryItemLocator.getQueryItemFromDimension( split[0], program, type );
if ( split.length > 1 ) // Filters specified
{
for ( int i = 1; i < split.length; i += 2 )
{
QueryOperator operator = QueryOperator.fromString( split[i] );
QueryFilter filter = new QueryFilter( operator, split[i + 1] );
// FE uses HH.MM time format instead of HH:MM. This is not
// compatible with db table/cell values
modifyFilterWhenTimeQueryItem( queryItem, filter );
queryItem.addFilter( filter );
}
}
return queryItem;
}
private static void modifyFilterWhenTimeQueryItem( QueryItem queryItem, QueryFilter filter )
{
if ( queryItem.getItem() instanceof DataElement
&& ((DataElement) queryItem.getItem()).getValueType() == ValueType.TIME )
{
filter.setFilter( filter.getFilter().replace( ".", ":" ) );
}
}
private QueryItem getSortItem( String item, Program program, EventOutputType type,
RequestTypeAware.EndpointItem endpointItem )
{
if ( isSortable( item ) )
{
return new QueryItem( new BaseDimensionalItemObject( translateItemIfNecessary( item, endpointItem ) ) );
}
return getQueryItem( item, program, type );
}
private DimensionalItemObject getValueDimension( String value )
{
if ( value == null )
{
return null;
}
DataElement de = dataElementService.getDataElement( value );
if ( de != null && de.isNumericType() )
{
return de;
}
TrackedEntityAttribute at = attributeService.getTrackedEntityAttribute( value );
if ( at != null && at.isNumericType() )
{
return at;
}
throw new IllegalQueryException( new ErrorMessage( ErrorCode.E7223, value ) );
}
@Getter
@RequiredArgsConstructor
enum SortableItems
{
ENROLLMENT_DATE( ITEM_ENROLLMENT_DATE, COL_NAME_ENROLLMENTDATE ),
INCIDENT_DATE( ITEM_INCIDENT_DATE, COL_NAME_INCIDENTDATE ),
EVENT_DATE( ITEM_EVENT_DATE, COL_NAME_EVENTDATE ),
SCHEDULED_DATE( ITEM_SCHEDULED_DATE, COL_NAME_DUEDATE ),
ORG_UNIT_NAME( ITEM_ORG_UNIT_NAME ),
ORG_UNIT_CODE( ITEM_ORG_UNIT_CODE ),
PROGRAM_STATUS( ITEM_PROGRAM_STATUS, COL_NAME_PROGRAM_STATUS_EVENTS, COL_NAME_PROGRAM_STATUS_ENROLLMENTS ),
EVENT_STATUS( ITEM_EVENT_STATUS, COL_NAME_EVENT_STATUS ),
CREATED_BY_DISPLAY_NAME( ITEM_CREATED_BY_DISPLAY_NAME ),
LAST_UPDATED_BY_DISPLAY_NAME( ITEM_LAST_UPDATED_BY_DISPLAY_NAME ),
LAST_UPDATED( ITEM_LAST_UPDATED );
private final String itemName;
private final String eventColumnName;
private final String enrollmentColumnName;
SortableItems( String itemName )
{
this.itemName = itemName;
this.eventColumnName = null;
this.enrollmentColumnName = null;
}
SortableItems( String itemName, String columnName )
{
this.itemName = itemName;
this.eventColumnName = columnName;
this.enrollmentColumnName = columnName;
}
static boolean isSortable( String itemName )
{
return Arrays.stream( values() )
.map( SortableItems::getItemName )
.anyMatch( itemName::equals );
}
static String translateItemIfNecessary( String item, RequestTypeAware.EndpointItem type )
{
return Arrays.stream( values() )
.filter( sortableItems -> sortableItems.getItemName().equals( item ) )
.findFirst()
.map( sortableItems -> sortableItems.getColumnName( type ) )
.orElse( item );
}
private String getColumnName( RequestTypeAware.EndpointItem type )
{
return type == RequestTypeAware.EndpointItem.EVENT ? eventColumnName : enrollmentColumnName;
}
}
}
| {
"content_hash": "b051f70625363aa0121e503ff02ab51c",
"timestamp": "",
"source": "github",
"line_count": 605,
"max_line_length": 119,
"avg_line_length": 39.62479338842975,
"alnum_prop": 0.6520669086055145,
"repo_name": "dhis2/dhis2-core",
"id": "308e01377465ff293d252d59f63a5cb8cc50c052",
"size": "25529",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/event/data/DefaultEventDataQueryService.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "186517"
},
{
"name": "Dockerfile",
"bytes": "107"
},
{
"name": "Groovy",
"bytes": "19847"
},
{
"name": "HTML",
"bytes": "69119"
},
{
"name": "Java",
"bytes": "31743715"
},
{
"name": "JavaScript",
"bytes": "958802"
},
{
"name": "PLpgSQL",
"bytes": "60867"
},
{
"name": "Ruby",
"bytes": "1011"
},
{
"name": "SCSS",
"bytes": "4229"
},
{
"name": "Shell",
"bytes": "9089"
},
{
"name": "XSLT",
"bytes": "8451"
}
],
"symlink_target": ""
} |
// Copyright 2015 The Bazel Authors. 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.
package com.google.testing.junit.runner.model;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import org.joda.time.Interval;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map.Entry;
import javax.inject.Inject;
/**
* Writes the JUnit test nodes and their results into Ant-JUnit XML. Ant-JUnit XML is not a
* standardized format. For this implementation the
* <a href="http://windyroad.com.au/dl/Open%20Source/JUnit.xsd">XML schema</a> that is generally
* referred to as the best available source was used as a reference.
*/
public final class AntXmlResultWriter implements XmlResultWriter {
private static final String JUNIT_ELEMENT_TESTSUITES = "testsuites";
private static final String JUNIT_ELEMENT_TESTSUITE = "testsuite";
private static final String JUNIT_ATTR_TESTSUITE_ERRORS = "errors";
private static final String JUNIT_ATTR_TESTSUITE_FAILURES = "failures";
private static final String JUNIT_ATTR_TESTSUITE_HOSTNAME = "hostname";
private static final String JUNIT_ATTR_TESTSUITE_NAME = "name";
private static final String JUNIT_ATTR_TESTSUITE_TESTS = "tests";
private static final String JUNIT_ATTR_TESTSUITE_TIME = "time";
private static final String JUNIT_ATTR_TESTSUITE_TIMESTAMP = "timestamp";
private static final String JUNIT_ATTR_TESTSUITE_ID = "id";
private static final String JUNIT_ATTR_TESTSUITE_PACKAGE = "package";
private static final String JUNIT_ATTR_TESTSUITE_PROPERTIES = "properties";
private static final String JUNIT_ATTR_TESTSUITE_SYSTEM_OUT = "system-out";
private static final String JUNIT_ATTR_TESTSUITE_SYSTEM_ERR = "system-err";
private static final String JUNIT_ELEMENT_PROPERTY = "property";
private static final String JUNIT_ATTR_PROPERTY_NAME = "name";
private static final String JUNIT_ATTR_PROPERTY_VALUE = "value";
private static final String JUNIT_ELEMENT_TESTCASE = "testcase";
private static final String JUNIT_ELEMENT_FAILURE = "failure";
private static final String JUNIT_ATTR_FAILURE_MESSAGE = "message";
private static final String JUNIT_ATTR_FAILURE_TYPE = "type";
private static final String JUNIT_ATTR_TESTCASE_NAME = "name";
private static final String JUNIT_ATTR_TESTCASE_CLASSNAME = "classname";
private static final String JUNIT_ATTR_TESTCASE_TIME = "time";
private int testSuiteId;
@Inject
public AntXmlResultWriter() {}
@Override
public void writeTestSuites(XmlWriter writer, TestResult result) throws IOException {
testSuiteId = 0;
writer.startDocument();
writer.startElement(JUNIT_ELEMENT_TESTSUITES);
for (TestResult child : result.getChildResults()) {
writeTestSuite(writer, child, result.getFailures());
}
writer.endElement();
writer.close();
}
private void writeTestSuite(XmlWriter writer, TestResult result,
Iterable<Throwable> parentFailures)
throws IOException {
parentFailures = Iterables.concat(parentFailures, result.getFailures());
writer.startElement(JUNIT_ELEMENT_TESTSUITE);
writeTestSuiteAttributes(writer, result);
writeTestSuiteProperties(writer, result);
writeTestCases(writer, result, parentFailures);
writeTestSuiteOutput(writer);
writer.endElement();
for (TestResult child : result.getChildResults()) {
if (!child.getChildResults().isEmpty()) {
writeTestSuite(writer, child, parentFailures);
}
}
}
private void writeTestSuiteProperties(XmlWriter writer, TestResult result) throws IOException {
writer.startElement(JUNIT_ATTR_TESTSUITE_PROPERTIES);
for (Entry<String, String> entry : result.getProperties().entrySet()) {
writer.startElement(JUNIT_ELEMENT_PROPERTY);
writer.writeAttribute(JUNIT_ATTR_PROPERTY_NAME, entry.getKey());
writer.writeAttribute(JUNIT_ATTR_PROPERTY_VALUE, entry.getValue());
writer.endElement();
}
writer.endElement();
}
private void writeTestCases(XmlWriter writer, TestResult result,
Iterable<Throwable> parentFailures) throws IOException {
for (TestResult child : result.getChildResults()) {
if (child.getChildResults().isEmpty()) {
writeTestCase(writer, child, parentFailures);
}
}
}
private void writeTestSuiteOutput(XmlWriter writer) throws IOException {
writer.startElement(JUNIT_ATTR_TESTSUITE_SYSTEM_OUT);
// TODO(bazel-team) - where to get this from?
writer.endElement();
writer.startElement(JUNIT_ATTR_TESTSUITE_SYSTEM_ERR);
// TODO(bazel-team) - where to get this from?
writer.endElement();
}
private void writeTestSuiteAttributes(XmlWriter writer, TestResult result) throws IOException {
writer.writeAttribute(JUNIT_ATTR_TESTSUITE_NAME, result.getName());
writer.writeAttribute(JUNIT_ATTR_TESTSUITE_TIMESTAMP, getFormattedTimestamp(
result.getRunTimeInterval()));
writer.writeAttribute(JUNIT_ATTR_TESTSUITE_HOSTNAME, "localhost");
writer.writeAttribute(JUNIT_ATTR_TESTSUITE_TESTS, result.getNumTests());
writer.writeAttribute(JUNIT_ATTR_TESTSUITE_FAILURES, result.getNumFailures());
// JUnit 4.x no longer distinguishes between errors and failures, so it should be safe to just
// report errors as 0 and put everything into failures.
writer.writeAttribute(JUNIT_ATTR_TESTSUITE_ERRORS, 0);
writer.writeAttribute(JUNIT_ATTR_TESTSUITE_TIME, getFormattedRunTime(
result.getRunTimeInterval()));
// TODO(bazel-team) - do we want to report the package name here? Could we simply get it from
// result.getClassName() by stripping the last element of the class name?
writer.writeAttribute(JUNIT_ATTR_TESTSUITE_PACKAGE, "");
writer.writeAttribute(JUNIT_ATTR_TESTSUITE_ID, this.testSuiteId++);
}
private static String getFormattedRunTime(Optional<Interval> runTimeInterval) {
return !runTimeInterval.isPresent() ? "0.0"
: String.valueOf(runTimeInterval.get().toDurationMillis() / 1000.0D);
}
private static String getFormattedTimestamp(Optional<Interval> runTimeInterval) {
return !runTimeInterval.isPresent() ? "" : runTimeInterval.get().getStart().toString();
}
private void writeTestCase(XmlWriter writer, TestResult result,
Iterable<Throwable> parentFailures)
throws IOException {
writer.startElement(JUNIT_ELEMENT_TESTCASE);
writer.writeAttribute(JUNIT_ATTR_TESTCASE_NAME, result.getName());
writer.writeAttribute(JUNIT_ATTR_TESTCASE_CLASSNAME, result.getClassName());
writer.writeAttribute(JUNIT_ATTR_TESTCASE_TIME, getFormattedRunTime(
result.getRunTimeInterval()));
for (Throwable failure : Iterables.concat(parentFailures, result.getFailures())) {
writer.startElement(JUNIT_ELEMENT_FAILURE);
writer.writeAttribute(JUNIT_ATTR_FAILURE_MESSAGE, Strings.nullToEmpty(failure.getMessage()));
writer.writeAttribute(JUNIT_ATTR_FAILURE_TYPE, failure.getClass().getName());
writer.writeCharacters(formatStackTrace(failure));
writer.endElement();
}
writer.endElement();
}
private static String formatStackTrace(Throwable throwable) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
throwable.printStackTrace(writer);
return stringWriter.getBuffer().toString();
}
}
| {
"content_hash": "c3c1b60669300e90bff3bd834b0cb95c",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 99,
"avg_line_length": 43.81868131868132,
"alnum_prop": 0.7459561128526646,
"repo_name": "mikelalcon/bazel",
"id": "29d983ac4ab23ba77de5acc3a423667386b3f92e",
"size": "7975",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/java_tools/junitrunner/java/com/google/testing/junit/runner/model/AntXmlResultWriter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "78"
},
{
"name": "C",
"bytes": "50369"
},
{
"name": "C++",
"bytes": "457803"
},
{
"name": "HTML",
"bytes": "17135"
},
{
"name": "Java",
"bytes": "17885235"
},
{
"name": "Protocol Buffer",
"bytes": "94411"
},
{
"name": "Python",
"bytes": "242749"
},
{
"name": "Shell",
"bytes": "493380"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>datetime.time</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="couchdbkit-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<th class="navbar" width="100%"></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
datetime ::
time ::
Class time
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="datetime.time-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class time</h1><p class="nomargin-top"></p>
<pre class="base-tree">
object --+
|
<strong class="uidshort">time</strong>
</pre>
<hr />
<p>time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a
time object</p>
<p>All arguments are optional. tzinfo may be None, or an instance of a
tzinfo subclass. The remaining arguments may be ints or longs.</p>
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__eq__"></a><span class="summary-sig-name">__eq__</span>(<span class="summary-sig-arg">x</span>,
<span class="summary-sig-arg">y</span>)</span><br />
x==y</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="datetime.time-class.html#__format__" class="summary-sig-name">__format__</a>(<span class="summary-sig-arg">...</span>)</span><br />
Formats self with strftime.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__ge__"></a><span class="summary-sig-name">__ge__</span>(<span class="summary-sig-arg">x</span>,
<span class="summary-sig-arg">y</span>)</span><br />
x>=y</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="datetime.time-class.html#__getattribute__" class="summary-sig-name">__getattribute__</a>(<span class="summary-sig-arg">...</span>)</span><br />
x.__getattribute__('name') <==> x.name</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__gt__"></a><span class="summary-sig-name">__gt__</span>(<span class="summary-sig-arg">x</span>,
<span class="summary-sig-arg">y</span>)</span><br />
x>y</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="datetime.time-class.html#__hash__" class="summary-sig-name">__hash__</a>(<span class="summary-sig-arg">x</span>)</span><br />
hash(x)</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__le__"></a><span class="summary-sig-name">__le__</span>(<span class="summary-sig-arg">x</span>,
<span class="summary-sig-arg">y</span>)</span><br />
x<=y</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__lt__"></a><span class="summary-sig-name">__lt__</span>(<span class="summary-sig-arg">x</span>,
<span class="summary-sig-arg">y</span>)</span><br />
x<y</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__ne__"></a><span class="summary-sig-name">__ne__</span>(<span class="summary-sig-arg">x</span>,
<span class="summary-sig-arg">y</span>)</span><br />
x!=y</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type">a new object with type S, a subtype of T</span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="datetime.time-class.html#__new__" class="summary-sig-name">__new__</a>(<span class="summary-sig-arg">T</span>,
<span class="summary-sig-arg">S</span>,
<span class="summary-sig-arg">...</span>)</span></td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__nonzero__"></a><span class="summary-sig-name">__nonzero__</span>(<span class="summary-sig-arg">x</span>)</span><br />
x != 0</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type">(cls, state)</span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="datetime.time-class.html#__reduce__" class="summary-sig-name">__reduce__</a>()</span><br />
helper for pickle</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="datetime.time-class.html#__repr__" class="summary-sig-name">__repr__</a>(<span class="summary-sig-arg">x</span>)</span><br />
repr(x)</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="datetime.time-class.html#__str__" class="summary-sig-name">__str__</a>(<span class="summary-sig-arg">x</span>)</span><br />
str(x)</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="dst"></a><span class="summary-sig-name">dst</span>(<span class="summary-sig-arg">...</span>)</span><br />
Return self.tzinfo.dst(self).</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="isoformat"></a><span class="summary-sig-name">isoformat</span>(<span class="summary-sig-arg">...</span>)</span><br />
Return string in ISO 8601 format, HH:MM:SS[.mmmmmm][+HH:MM].</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="replace"></a><span class="summary-sig-name">replace</span>(<span class="summary-sig-arg">...</span>)</span><br />
Return time with new specified fields.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="strftime"></a><span class="summary-sig-name">strftime</span>(<span class="summary-sig-arg">...</span>)</span><br />
format -> strftime() style string.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="tzname"></a><span class="summary-sig-name">tzname</span>(<span class="summary-sig-arg">...</span>)</span><br />
Return self.tzinfo.tzname(self).</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="utcoffset"></a><span class="summary-sig-name">utcoffset</span>(<span class="summary-sig-arg">...</span>)</span><br />
Return self.tzinfo.utcoffset(self).</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__delattr__</code>,
<code>__init__</code>,
<code>__reduce_ex__</code>,
<code>__setattr__</code>,
<code>__sizeof__</code>,
<code>__subclasshook__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== CLASS VARIABLES ==================== -->
<a name="section-ClassVariables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Class Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-ClassVariables"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="max"></a><span class="summary-name">max</span> = <code title="datetime.time(23, 59, 59, 999999)">datetime.time(23, 59, 59, 999999)</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="min"></a><span class="summary-name">min</span> = <code title="datetime.time(0, 0)">datetime.time(0, 0)</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="resolution"></a><span class="summary-name">resolution</span> = <code title="datetime.timedelta(0, 0, 1)">datetime.timedelta(0, 0, 1)</code>
</td>
</tr>
</table>
<!-- ==================== PROPERTIES ==================== -->
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="hour"></a><span class="summary-name">hour</span>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="microsecond"></a><span class="summary-name">microsecond</span>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="minute"></a><span class="summary-name">minute</span>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="second"></a><span class="summary-name">second</span>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="tzinfo"></a><span class="summary-name">tzinfo</span>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__class__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== METHOD DETAILS ==================== -->
<a name="section-MethodDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Method Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-MethodDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="__format__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__format__</span>(<span class="sig-arg">...</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Formats self with strftime.</p>
<dl class="fields">
<dt>Overrides:
object.__format__
</dt>
</dl>
</td></tr></table>
</div>
<a name="__getattribute__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__getattribute__</span>(<span class="sig-arg">...</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>x.__getattribute__('name') <==> x.name</p>
<dl class="fields">
<dt>Overrides:
object.__getattribute__
</dt>
</dl>
</td></tr></table>
</div>
<a name="__hash__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__hash__</span>(<span class="sig-arg">x</span>)</span>
<br /><em class="fname">(Hashing function)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>hash(x)</p>
<dl class="fields">
<dt>Overrides:
object.__hash__
</dt>
</dl>
</td></tr></table>
</div>
<a name="__new__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__new__</span>(<span class="sig-arg">T</span>,
<span class="sig-arg">S</span>,
<span class="sig-arg">...</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<dl class="fields">
<dt>Returns: a new object with type S, a subtype of T</dt>
<dt>Overrides:
object.__new__
</dt>
</dl>
</td></tr></table>
</div>
<a name="__reduce__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__reduce__</span>()</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>helper for pickle</p>
<dl class="fields">
<dt>Returns: (cls, state)</dt>
<dt>Overrides:
object.__reduce__
</dt>
</dl>
</td></tr></table>
</div>
<a name="__repr__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__repr__</span>(<span class="sig-arg">x</span>)</span>
<br /><em class="fname">(Representation operator)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>repr(x)</p>
<dl class="fields">
<dt>Overrides:
object.__repr__
</dt>
</dl>
</td></tr></table>
</div>
<a name="__str__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__str__</span>(<span class="sig-arg">x</span>)</span>
<br /><em class="fname">(Informal representation operator)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>str(x)</p>
<dl class="fields">
<dt>Overrides:
object.__str__
</dt>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="couchdbkit-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<th class="navbar" width="100%"></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Fri Feb 18 10:31:29 2011
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| {
"content_hash": "1b86c2519f21a41f842e0344d90c4a4d",
"timestamp": "",
"source": "github",
"line_count": 773,
"max_line_length": 192,
"avg_line_length": 32.78783958602846,
"alnum_prop": 0.5347800355099626,
"repo_name": "sirex/couchdbkit",
"id": "938d690fa4e24a0c0fe046d7abc0e4408ad99e70",
"size": "25345",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/couchdbkit.org/htdocs/docs/api/datetime.time-class.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "13423"
},
{
"name": "Python",
"bytes": "367102"
}
],
"symlink_target": ""
} |
function reject=is_art(label)
% isart() - Function for evaluating whether or not the text label of an
% independent component (IC) corresponds to an EEG artifact or not.
%
% Usage:
% >> reject=isart(label)
%
% Required Inputs:
% label - a string label for an IC.
%
% Output:
% reject - 1 if "label" is a type of IC artifact, 0 otherwise. The
% possible values of label recognized as IC artifacts are:
% 'blink' -Eye blink IC
% 'HE' -Horizontal eye movement IC
% 'EOG' -Generic eye movment IC
% 'EMG' -Muscle noise IC
% 'heart' -Heartbeat artifact IC
% 'drift' -Drift artifact IC
% 'bad_chan' -Bad channel (i.e., sensor problems) IC
% '60HZ' -60 Hz line noise IC
% 'art' -Generic artifact IC
% 'blink (objective)' -Eye blink IC (according to objective test)
% 'heart (objective)' -Heart blink IC (according to objective
% test)
% 'HE (objective)' -Horizontal eye movement IC (according to objective
% test)
% 'EMG (objective)' -Muscle noise IC (according to objective
% test)
% 'bad_chan (objective)' -Bad channel (i.e., sensor problems)
% IC (according to objective test)
% 'xtrm_activity (objective)' -Extreme activations (most likely
% due to movement of some sort)
% 'EOG (objective)' -Eye movement IC (according to objective
% test)
%
% Notes:
% -The evaluation of "label" is NOT case sensitive. For example,
% 'blink','Blink','BLINK', and 'bLiNK' would all be recognized as an
% artifact.
%
% Author:
% David Groppe
% Kutaslab, 11/2009
%
art_labels{1}='blink';
art_labels{2}='HE';
art_labels{3}='EOG';
art_labels{4}='NZ'; %left in for backwards compatibility
art_labels{5}='heart';
art_labels{6}='drift';
art_labels{7}='bad_chan';
art_labels{8}='60HZ';
art_labels{9}='art';
art_labels{10}='EMG';
art_labels{11}='blink (objective)';
art_labels{12}='heart (objective)';
art_labels{13}='HE (objective)';
art_labels{14}='EMG (objective)';
art_labels{15}='bad_chan (objective)';
art_labels{16}='xtrm_activity (objective)';
art_labels{17}='EOG (objective)';
reject=0;
if ~isempty(label)
for a=1:length(art_labels),
if strcmpi(label,art_labels{a})
reject=1;
return;
end
end
end
| {
"content_hash": "85adca3c013b89b4a4f86fd1e3bef860",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 86,
"avg_line_length": 35.06666666666667,
"alnum_prop": 0.5524714828897338,
"repo_name": "dmgroppe/Mass_Univariate_ERP_Toolbox",
"id": "b2bf008de02b7da7effc3d3fa99d48c3f73be170",
"size": "2630",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "is_art.m",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Matlab",
"bytes": "1222411"
}
],
"symlink_target": ""
} |
namespace atom {
namespace internal {
namespace {
// The callback which is passed to |handler|.
void HandlerCallback(const BeforeStartCallback& before_start,
const ResponseCallback& callback,
mate::Arguments* args) {
// If there is no argument passed then we failed.
v8::Local<v8::Value> value;
if (!args->GetNext(&value)) {
content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::Bind(callback, false, nullptr));
return;
}
// Give the job a chance to parse V8 value.
before_start.Run(args->isolate(), value);
// Pass whatever user passed to the actaul request job.
V8ValueConverter converter;
v8::Local<v8::Context> context = args->isolate()->GetCurrentContext();
std::unique_ptr<base::Value> options(converter.FromV8Value(value, context));
content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::Bind(callback, true, base::Passed(&options)));
}
} // namespace
void AskForOptions(v8::Isolate* isolate,
const JavaScriptHandler& handler,
std::unique_ptr<base::DictionaryValue> request_details,
const BeforeStartCallback& before_start,
const ResponseCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
v8::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Context::Scope context_scope(context);
handler.Run(
*(request_details.get()),
mate::ConvertToV8(isolate,
base::Bind(&HandlerCallback, before_start, callback)));
}
bool IsErrorOptions(base::Value* value, int* error) {
if (value->is_dict()) {
base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(value);
if (dict->GetInteger("error", error))
return true;
} else if (value->is_int()) {
if (value->GetAsInteger(error))
return true;
}
return false;
}
} // namespace internal
} // namespace atom
| {
"content_hash": "a7ef3423ed71f636eebdbf79334ea3da",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 79,
"avg_line_length": 32.359375,
"alnum_prop": 0.6528247223563496,
"repo_name": "brave/electron",
"id": "55983b831cf2e0f1cbb181cef5efe93c85dbc10b",
"size": "2391",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "atom/browser/net/js_asker.cc",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5248"
},
{
"name": "C++",
"bytes": "2194043"
},
{
"name": "HTML",
"bytes": "15853"
},
{
"name": "JavaScript",
"bytes": "483834"
},
{
"name": "Objective-C",
"bytes": "12503"
},
{
"name": "Objective-C++",
"bytes": "134374"
},
{
"name": "Python",
"bytes": "63800"
},
{
"name": "Shell",
"bytes": "2593"
}
],
"symlink_target": ""
} |
numpy.core.records.fromarrays
=============================
.. currentmodule:: numpy.core.records
.. autofunction:: fromarrays
| {
"content_hash": "f95a88d54a43d4725ee7a01015db2bf1",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 37,
"avg_line_length": 21.5,
"alnum_prop": 0.5968992248062015,
"repo_name": "qpython-android/QPypi-numpy",
"id": "c1f91d4411ebaa4d08d522330c87653b91fddd75",
"size": "129",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/source/reference/generated/numpy.core.records.fromarrays.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "3832435"
},
{
"name": "C++",
"bytes": "73392"
},
{
"name": "FORTRAN",
"bytes": "4872"
},
{
"name": "Objective-C",
"bytes": "135"
},
{
"name": "Python",
"bytes": "3402698"
}
],
"symlink_target": ""
} |
This app is a port from https://github.com/blockcypher/explorer
This folder contains a backup of that projects templates at the moment this project was started.
They should be delete as there are ported to Twig. | {
"content_hash": "8af9536d5aa85f9ce3bd0992d60abee0",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 96,
"avg_line_length": 70.33333333333333,
"alnum_prop": 0.8104265402843602,
"repo_name": "blockcypher/php-wallet-sample",
"id": "9f09c9e43a7277eaa7facabbc910524dfebb3f7a",
"size": "211",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/BlockCypher/AppCommon/Infrastructure/LayoutBundle/Resources/django_templates/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8971"
},
{
"name": "HTML",
"bytes": "218778"
},
{
"name": "JavaScript",
"bytes": "6326"
},
{
"name": "PHP",
"bytes": "400629"
}
],
"symlink_target": ""
} |
package com.linkedin.android.litr.filter.video.gl;
import androidx.annotation.Nullable;
import com.linkedin.android.litr.filter.Transform;
import com.linkedin.android.litr.filter.video.gl.parameter.ShaderParameter;
import com.linkedin.android.litr.filter.video.gl.parameter.Uniform1f;
import com.linkedin.android.litr.filter.video.gl.shader.VertexShader;
/**
* Frame render filter that applies cartoon-like effect
*/
public class ToonFilter extends VideoFrameRenderFilter {
private static final String FRAGMENT_SHADER =
"#extension GL_OES_EGL_image_external : require\n" +
"precision highp float;\n" +
"uniform samplerExternalOES sTexture;\n" +
"varying vec2 textureCoordinate;\n" +
"varying vec2 leftTextureCoordinate;\n" +
"varying vec2 rightTextureCoordinate;\n" +
"varying vec2 topTextureCoordinate;\n" +
"varying vec2 topLeftTextureCoordinate;\n" +
"varying vec2 topRightTextureCoordinate;\n" +
"varying vec2 bottomTextureCoordinate;\n" +
"varying vec2 bottomLeftTextureCoordinate;\n" +
"varying vec2 bottomRightTextureCoordinate;\n" +
"uniform highp float threshold;\n" +
"uniform highp float quantizationLevels;\n" +
"const highp vec3 W = vec3(0.2125, 0.7154, 0.0721);\n" +
"void main()\n" +
"{\n" +
"vec4 textureColor = texture2D(sTexture, textureCoordinate);\n" +
"float bottomLeftIntensity = texture2D(sTexture, bottomLeftTextureCoordinate).r;\n" +
"float topRightIntensity = texture2D(sTexture, topRightTextureCoordinate).r;\n" +
"float topLeftIntensity = texture2D(sTexture, topLeftTextureCoordinate).r;\n" +
"float bottomRightIntensity = texture2D(sTexture, bottomRightTextureCoordinate).r;\n" +
"float leftIntensity = texture2D(sTexture, leftTextureCoordinate).r;\n" +
"float rightIntensity = texture2D(sTexture, rightTextureCoordinate).r;\n" +
"float bottomIntensity = texture2D(sTexture, bottomTextureCoordinate).r;\n" +
"float topIntensity = texture2D(sTexture, topTextureCoordinate).r;\n" +
"float h = -topLeftIntensity - 2.0 * topIntensity - topRightIntensity + bottomLeftIntensity + 2.0 * bottomIntensity + bottomRightIntensity;\n" +
"float v = -bottomLeftIntensity - 2.0 * leftIntensity - topLeftIntensity + bottomRightIntensity + 2.0 * rightIntensity + topRightIntensity;\n" +
"float mag = length(vec2(h, v));\n" +
"vec3 posterizedImageColor = floor((textureColor.rgb * quantizationLevels) + 0.5) / quantizationLevels;\n" +
"float thresholdTest = 1.0 - step(threshold, mag);\n" +
"gl_FragColor = vec4(posterizedImageColor * thresholdTest, textureColor.a);\n" +
"}";
/**
* Create the instance of frame render filter
* @param texelWidth relative width of a texel
* @param texelHeight relative height of a texel
* @param threshold edge detection threshold
* @param quantizationLevels number of color quantization levels
*/
public ToonFilter(float texelWidth, float texelHeight, float threshold, float quantizationLevels) {
this(texelWidth, texelHeight, threshold, quantizationLevels, null);
}
/**
* Create frame render filter with source video frame, then scale, then position and then rotate the bitmap around its center as specified.
* @param texelWidth relative width of a texel
* @param texelHeight relative height of a texel
* @param threshold edge detection threshold
* @param quantizationLevels number of color quantization levels
* @param transform {@link Transform} that defines positioning of source video frame within target video frame
*/
public ToonFilter(float texelWidth, float texelHeight, float threshold, float quantizationLevels, @Nullable Transform transform) {
super(VertexShader.THREE_X_THREE_TEXTURE_SAMPLING_VERTEX_SHADER,
FRAGMENT_SHADER,
new ShaderParameter[] {
new Uniform1f("texelWidth", texelWidth),
new Uniform1f("texelHeight", texelHeight),
new Uniform1f("threshold", threshold),
new Uniform1f("quantizationLevels", quantizationLevels)
},
transform);
}
}
| {
"content_hash": "683149ac857869278319e960c19e97d7",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 160,
"avg_line_length": 49.989010989010985,
"alnum_prop": 0.6561881732248845,
"repo_name": "linkedin/LiTr",
"id": "c475617f2d1123d4cfacc3086828ee56810be41e",
"size": "5675",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "litr-filters/src/main/java/com/linkedin/android/litr/filter/video/gl/ToonFilter.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C++",
"bytes": "48531"
},
{
"name": "CMake",
"bytes": "604"
},
{
"name": "Java",
"bytes": "720959"
},
{
"name": "Kotlin",
"bytes": "127248"
}
],
"symlink_target": ""
} |
package com.rackspacecloud.blueflood.io.astyanax;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.ColumnFamily;
import com.rackspacecloud.blueflood.io.AbstractMetricsRW;
import com.rackspacecloud.blueflood.io.CassandraModel;
import com.rackspacecloud.blueflood.io.PreaggregatedRW;
import com.rackspacecloud.blueflood.outputs.formats.MetricData;
import com.rackspacecloud.blueflood.rollup.Granularity;
import com.rackspacecloud.blueflood.service.SingleRollupWriteContext;
import com.rackspacecloud.blueflood.types.*;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* This class deals with reading/writing metrics to the metrics_preaggregated_* column families
* using Astyanax driver
*/
public class APreaggregatedMetricsRW extends AbstractMetricsRW implements PreaggregatedRW{
/**
* Inserts a collection of metrics to the metrics_preaggregated_full column family
*
* @param metrics
* @throws IOException
*/
@Override
public void insertMetrics(Collection<IMetric> metrics) throws IOException {
insertMetrics(metrics, Granularity.FULL);
}
/**
* Inserts a collection of metrics to the correct column family based on
* the specified granularity
*
* @param metrics
* @param granularity
* @throws IOException
*/
@Override
public void insertMetrics(Collection<IMetric> metrics, Granularity granularity) throws IOException {
try {
AstyanaxWriter.getInstance().insertMetrics(metrics, CassandraModel.getPreaggregatedColumnFamily(granularity));
} catch (ConnectionException ex) {
throw new IOException(ex);
}
}
@Override
public void insertRollups(List<SingleRollupWriteContext> writeContexts) throws IOException {
try {
AstyanaxWriter.getInstance().insertRollups(writeContexts);
} catch (ConnectionException ex) {
throw new IOException(ex);
}
}
/**
* Fetches {@link com.rackspacecloud.blueflood.outputs.formats.MetricData} objects for the
* specified {@link com.rackspacecloud.blueflood.types.Locator} and
* {@link com.rackspacecloud.blueflood.types.Range} from the specified column family
*
* @param locator
* @param range
* @param gran
* @return
*/
@Override
public MetricData getDatapointsForRange(final Locator locator,
Range range,
Granularity gran) throws IOException {
return AstyanaxReader.getInstance().getDatapointsForRange(locator, range, gran);
}
/**
* Fetches {@link com.rackspacecloud.blueflood.outputs.formats.MetricData} objects for the
* specified list of {@link com.rackspacecloud.blueflood.types.Locator} and
* {@link com.rackspacecloud.blueflood.types.Range} from the specified column family
*
* @param locators
* @param range
* @param gran
* @return
*/
@Override
public Map<Locator, MetricData> getDatapointsForRange(List<Locator> locators,
Range range,
Granularity gran) throws IOException {
return AstyanaxReader.getInstance().getDatapointsForRange(locators, range, gran);
}
/**
* Fetches a {@link com.rackspacecloud.blueflood.types.Points} object for a
* particular locator and rollupType from the specified column family and
* range
*
* @param locator
* @param rollupType
* @param range
* @param columnFamilyName
* @param <T> the type of Rollup object
* @return
*/
@Override
public <T extends Rollup> Points<T> getDataToRollup(final Locator locator,
RollupType rollupType,
Range range,
String columnFamilyName) throws IOException {
ColumnFamily cf = CassandraModel.getColumnFamily(columnFamilyName);
// a quick n dirty hack, this code will go away someday
Granularity granularity = CassandraModel.getGranularity(cf);
Class<? extends Rollup> rollupClass = RollupType.classOf(rollupType, granularity);
return AstyanaxReader.getInstance().getDataToRoll(rollupClass, locator, range, cf);
}
}
| {
"content_hash": "c5e19f8f248c829e15a64c3a1ed65fc9",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 122,
"avg_line_length": 38.03333333333333,
"alnum_prop": 0.6577563540753725,
"repo_name": "goru97/blueflood",
"id": "0ad9c8784c7ae283df68b6b396235fb08f290836",
"size": "5158",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blueflood-core/src/main/java/com/rackspacecloud/blueflood/io/astyanax/APreaggregatedMetricsRW.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "193"
},
{
"name": "Java",
"bytes": "2321692"
},
{
"name": "JavaScript",
"bytes": "16131"
},
{
"name": "Python",
"bytes": "157213"
},
{
"name": "Ruby",
"bytes": "7961"
},
{
"name": "Shell",
"bytes": "38062"
}
],
"symlink_target": ""
} |
set -eux
export GO_FAILPOINTS='github.com/pingcap/tidb/br/pkg/lightning/restore/SlowDownWriteRows=sleep(100);github.com/pingcap/tidb/br/pkg/lightning/restore/SetMinDeliverBytes=return(1)'
for CFG in chunk engine; do
rm -f "$TEST_DIR/lightning-tidb.log"
run_sql 'DROP DATABASE IF EXISTS fail_fast;'
! run_lightning --backend tidb --enable-checkpoint=0 --log-file "$TEST_DIR/lightning-tidb.log" --config "tests/$TEST_NAME/$CFG.toml"
[ $? -eq 0 ]
tail -n 10 $TEST_DIR/lightning-tidb.log | grep "ERROR" | tail -n 1 | grep -Fq "Error 1062: Duplicate entry '1-1' for key 'tb.uq'"
! grep -Fq "restore file completed" $TEST_DIR/lightning-tidb.log
[ $? -eq 0 ]
! grep -Fq "restore engine completed" $TEST_DIR/lightning-tidb.log
[ $? -eq 0 ]
done
| {
"content_hash": "c069f47866a36184dd013fa4c0fdc59e",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 178,
"avg_line_length": 40.05263157894737,
"alnum_prop": 0.6990801576872536,
"repo_name": "pingcap/tidb",
"id": "7e057e3ee999c58b32e2bdb941214c81df9c3a50",
"size": "1351",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "br/tests/lightning_fail_fast/run.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1854"
},
{
"name": "Go",
"bytes": "34056451"
},
{
"name": "HTML",
"bytes": "420"
},
{
"name": "Java",
"bytes": "3694"
},
{
"name": "JavaScript",
"bytes": "900"
},
{
"name": "Jsonnet",
"bytes": "15129"
},
{
"name": "Makefile",
"bytes": "22240"
},
{
"name": "Ragel",
"bytes": "3678"
},
{
"name": "Shell",
"bytes": "439400"
},
{
"name": "Starlark",
"bytes": "574240"
},
{
"name": "TypeScript",
"bytes": "61875"
},
{
"name": "Yacc",
"bytes": "353301"
}
],
"symlink_target": ""
} |
#ifndef WINPR_SSPI_PRIVATE_H
#define WINPR_SSPI_PRIVATE_H
#include <winpr/sspi.h>
struct _CREDENTIALS
{
SEC_WINNT_AUTH_IDENTITY identity;
};
typedef struct _CREDENTIALS CREDENTIALS;
CREDENTIALS* sspi_CredentialsNew();
void sspi_CredentialsFree(CREDENTIALS* credentials);
SecHandle* sspi_SecureHandleAlloc();
void sspi_SecureHandleInit(SecHandle* handle);
void sspi_SecureHandleInvalidate(SecHandle* handle);
void* sspi_SecureHandleGetLowerPointer(SecHandle* handle);
void sspi_SecureHandleSetLowerPointer(SecHandle* handle, void* pointer);
void* sspi_SecureHandleGetUpperPointer(SecHandle* handle);
void sspi_SecureHandleSetUpperPointer(SecHandle* handle, void* pointer);
void sspi_SecureHandleFree(SecHandle* handle);
enum SecurityFunctionTableIndex
{
EnumerateSecurityPackagesIndex = 1,
Reserved1Index = 2,
QueryCredentialsAttributesIndex = 3,
AcquireCredentialsHandleIndex = 4,
FreeCredentialsHandleIndex = 5,
Reserved2Index = 6,
InitializeSecurityContextIndex = 7,
AcceptSecurityContextIndex = 8,
CompleteAuthTokenIndex = 9,
DeleteSecurityContextIndex = 10,
ApplyControlTokenIndex = 11,
QueryContextAttributesIndex = 12,
ImpersonateSecurityContextIndex = 13,
RevertSecurityContextIndex = 14,
MakeSignatureIndex = 15,
VerifySignatureIndex = 16,
FreeContextBufferIndex = 17,
QuerySecurityPackageInfoIndex = 18,
Reserved3Index = 19,
Reserved4Index = 20,
ExportSecurityContextIndex = 21,
ImportSecurityContextIndex = 22,
AddCredentialsIndex = 23,
Reserved8Index = 24,
QuerySecurityContextTokenIndex = 25,
EncryptMessageIndex = 26,
DecryptMessageIndex = 27,
SetContextAttributesIndex = 28
};
#endif /* WINPR_SSPI_PRIVATE_H */
| {
"content_hash": "c673c442efd698b2954c258d5cda9c41",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 72,
"avg_line_length": 28.655172413793103,
"alnum_prop": 0.8062575210589651,
"repo_name": "awakecoding/WinPR-msasn1",
"id": "b51f72398e7c59c4276fff7f79eecf7aecf00df6",
"size": "2376",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "winpr/libwinpr/sspi/sspi.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "4402850"
},
{
"name": "C#",
"bytes": "12431"
},
{
"name": "C++",
"bytes": "657133"
},
{
"name": "Objective-C",
"bytes": "126180"
},
{
"name": "Perl",
"bytes": "8037"
},
{
"name": "Python",
"bytes": "1430"
},
{
"name": "Shell",
"bytes": "1686"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "c082eae76e4adf3fa935fe548d09b165",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "0ad7e1fa733061de6848b71f695eb845db065bf0",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Lasianthus/Lasianthus japonicus/ Syn. Lasianthus nebulosa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="cn">
<head>
<meta name="generator" content="AWStats 7.2 (build 1.992) from config file awstats.mirror.bistu.edu.cn.conf (http://www.awstats.org)">
<meta name="robots" content="noindex,nofollow">
<meta http-equiv="content-type" content="text/html; charset=GBK">
<meta http-equiv="description" content="Awstats - Advanced Web Statistics for mirror.bistu.edu.cn (2014-02) - refererse">
<title>ͳ¼ÆÍøÕ¾ mirror.bistu.edu.cn (2014-02) - refererse</title>
<style type="text/css">
body { font: 11px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; margin-top: 0; margin-bottom: 0; }
.aws_bodyl { }
.aws_border { border-collapse: collapse; background-color: #CCCCDD; padding: 1px 1px 1px 1px; margin-top: 0px; margin-bottom: 0px; }
.aws_title { font: 13px verdana, arial, helvetica, sans-serif; font-weight: bold; background-color: #CCCCDD; text-align: center; margin-top: 0; margin-bottom: 0; padding: 1px 1px 1px 1px; color: #000000; }
.aws_blank { font: 13px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; text-align: center; margin-bottom: 0; padding: 1px 1px 1px 1px; }
.aws_data {
background-color: #FFFFFF;
border-top-width: 1px;
border-left-width: 0px;
border-right-width: 0px;
border-bottom-width: 0px;
}
.aws_formfield { font: 13px verdana, arial, helvetica; }
.aws_button {
font-family: arial,verdana,helvetica, sans-serif;
font-size: 12px;
border: 1px solid #ccd7e0;
background-image : url(/icon/other/button.gif);
}
th { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; }
th.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font-size: 13px; font-weight: bold; }
td { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; }
td.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px;}
td.awsm { border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px; }
b { font-weight: bold; }
a { font: 11px verdana, arial, helvetica, sans-serif; }
a:link { color: #0011BB; text-decoration: none; }
a:visited { color: #0011BB; text-decoration: none; }
a:hover { color: #605040; text-decoration: underline; }
.currentday { font-weight: bold; }
</style>
</head>
<body style="margin-top: 0px">
<a name="top"></a>
<a name="menu"> </a>
<form name="FormDateFilter" action="/cgi-bin/awstats.pl?config=mirror.bistu.edu.cn&staticlinks&lang=cn&output=refererse" style="padding: 0px 0px 0px 0px; margin-top: 0">
<table class="aws_border" border="0" cellpadding="2" cellspacing="0" width="100%">
<tr><td>
<table class="aws_data sortable" border="0" cellpadding="1" cellspacing="0" width="100%">
<tr><td class="aws" valign="middle"><b>ͳ¼ÆÍøÕ¾:</b> </td><td class="aws" valign="middle"><span style="font-size: 14px;">mirror.bistu.edu.cn</span></td><td align="right" rowspan="3"><a href="http://www.awstats.org" target="awstatshome"><img src="/icon/other/awstats_logo6.png" border="0" alt='Awstats Web Site' title='Awstats Web Site' /></a></td></tr>
<tr valign="middle"><td class="aws" valign="middle" width="150"><b>×î½ü¸üÐÂ:</b> </td><td class="aws" valign="middle"><span style="font-size: 12px;"><span style="color: #880000">´Óδ¸üУ¨Çë²Î¿¼ awstats_setup.htmlÉ쵀 'Build/Update'£©</span></span></td></tr>
<tr><td class="aws" valign="middle"><b>±¨±íÈÕÆÚ:</b></td><td class="aws" valign="middle"><span style="font-size: 14px;">Ô 02Ô 2014</span></td></tr>
</table>
</td></tr></table>
</form><br />
<table>
<tr><td class="aws"><a href="javascript:parent.window.close();">¹Ø±Õ´Ë´°¿Ú</a></td></tr>
</table>
<a name="refererse"> </a><br />
<table class="aws_border sortable" border="0" cellpadding="2" cellspacing="0" width="100%">
<tr><td class="aws_title" width="70%">À´×ÔËÑË÷ÒýÇæ </td><td class="aws_blank"> </td></tr>
<tr><td colspan="2">
<table class="aws_data" border="1" cellpadding="2" cellspacing="0" width="100%">
<tr bgcolor="#ECECEC"><th>0 ¸ö²»Í¬µÄËÑË÷ÒýÇæ×ª½é²Î¹ÛÕßµ½ÕâÕ¾</th><th bgcolor="#4477DD" width="80">ÍøÒ³Êý</th><th bgcolor="#4477DD" width="80">°Ù·Ö±È</th><th bgcolor="#66DDEE" width="80">ÎļþÊý</th><th bgcolor="#66DDEE" width="80">°Ù·Ö±È</th></tr>
</table></td></tr></table><br />
<br /><br />
<span dir="ltr" style="font: 11px verdana, arial, helvetica; color: #000000;"><b>Advanced Web Statistics 7.2 (build 1.992)</b> - <a href="http://www.awstats.org" target="awstatshome">´´½¨Õß awstats</a></span><br />
<br />
</body>
</html>
| {
"content_hash": "7d28b2522ef95fd9ea3595e21ce4bd37",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 357,
"avg_line_length": 67.45454545454545,
"alnum_prop": 0.6911821332306507,
"repo_name": "c0710204/mirrorsBistu",
"id": "5a8cf1fe5d40a20f197a8f29f8ce0cc2e91a6f55",
"size": "5194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "log/awstats/awstats.mirror.bistu.edu.cn.refererse.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4451282"
},
{
"name": "C++",
"bytes": "85589"
},
{
"name": "CSS",
"bytes": "13627"
},
{
"name": "Erlang",
"bytes": "2018"
},
{
"name": "JavaScript",
"bytes": "169379"
},
{
"name": "PHP",
"bytes": "1856746"
},
{
"name": "Perl",
"bytes": "804269"
},
{
"name": "Python",
"bytes": "5211268"
},
{
"name": "Shell",
"bytes": "497398"
},
{
"name": "TeX",
"bytes": "322428"
}
],
"symlink_target": ""
} |
title: "Output"
date: 2021-11-02T08:39:47-05:00
draft: false
---
This page is under construction!
To help move things along, use the "Edit" button on the right side of this page. | {
"content_hash": "72c9926970796febd8a82ebdcc327499",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 80,
"avg_line_length": 22.5,
"alnum_prop": 0.7333333333333333,
"repo_name": "probr/probr-core",
"id": "24165d45e38f6f1f2520738f37b11a254e426e83",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "site/content/en/docs/guides/output.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4513"
},
{
"name": "Go",
"bytes": "12526"
},
{
"name": "HTML",
"bytes": "73767"
},
{
"name": "JavaScript",
"bytes": "80907"
},
{
"name": "Makefile",
"bytes": "1903"
},
{
"name": "SCSS",
"bytes": "37004"
}
],
"symlink_target": ""
} |
//******************************************************************************
//! COMPB - CB Interrupt, Input compared against 1.5V Internal Reference
//!
//! Use CompB and internal reference to determine if input 'Vcompare' is high
//! of low. For the first time, when Vcompare exceeds the 1.5V internal
//! reference, CBIFG is set and device enters the CompB ISR. In the ISR CBIES
//! is toggled such that when Vcompare is less than 1.5V internal reference,
//! CBIFG is set. LED is toggled inside the CompB ISR
//!
//! MSP430x552x
//! ------------------
//! /|\| |
//! | | |
//! --|RST P6.0/CB0|<- Vcompare
//! | P1.0|-> LED 'ON'(Vcompare>1.5V); 'OFF'(Vcompare<1.5V)
//! | |
//!
//!
//! This example uses the following peripherals and I/O signals. You must
//! review these and change as needed for your own board:
//! - COMPB peripheral
//! - GPIO Port peripheral
//!
//! This example uses the following interrupt handlers. To use this example
//! in your own application you must add these interrupt handlers to your
//! vector table.
//! - COMP_B_B_VECTOR
//!
//******************************************************************************
#include "driverlib.h"
void main(void)
{
//Stop WDT
WDT_A_hold(WDT_A_BASE);
//Set P1.0 to output direction
GPIO_setAsOutputPin(
GPIO_PORT_P1,
GPIO_PIN0
);
//Initialize the Comparator B module
/*
* Base Address of Comparator B,
* Pin CB0 to Positive(+) Terminal
* Reference Voltage to Negative(-) Terminal
* Normal Power Mode
* Output Filter On with minimal delay
* Non-Inverted Output Polarity
*/
COMP_B_init(COMP_B_BASE,
COMP_B_INPUT0,
COMP_B_VREF,
COMP_B_POWERMODE_NORMALMODE,
COMP_B_FILTEROUTPUT_DLYLVL1,
COMP_B_NORMALOUTPUTPOLARITY
);
//Set the reference voltage that is being supplied to the (-) terminal
/*
* Base Address of Comparator B,
* Reference Voltage of 1.5 V,
* Lower Limit of 1.5*(32/32) = 1.5V,
* Upper Limit of 1.5*(32/32) = 1.5V,
* Static Mode Accuracy
*/
COMP_B_setReferenceVoltage(COMP_B_BASE,
COMP_B_VREFBASE1_5V,
32,
32,
COMP_B_ACCURACY_STATIC);
//Enable Interrupts
/*
* Base Address of Comparator B,
* Enable CompB Interrupt on default rising edge for CBIFG
*/
COMP_B_clearInterrupt(COMP_B_BASE,
CBIFG);
COMP_B_enableInterrupt(COMP_B_BASE,
CBIE);
//Allow power to Comparator module
COMP_B_enable(COMP_B_BASE);
//Enter LPM4 with inetrrupts enabled
__bis_SR_register(LPM4_bits + GIE);
//For debug
__no_operation();
}
//******************************************************************************
//
//This is the COMP_B_VECTOR interrupt vector service routine.
//
//******************************************************************************
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=COMP_B_VECTOR
__interrupt
#elif defined(__GNUC__)
__attribute__((interrupt(COMP_B_VECTOR)))
#endif
void COMP_B_ISR(void)
{
//Toggle the edge at which an interrupt is generated
COMP_B_interruptToggleEdgeDirection(COMP_B_BASE);
//Clear Interrupt flag
COMP_B_clearInterrupt(COMP_B_BASE, CBIFG);
//Toggle P1.0
GPIO_toggleOutputOnPin(
GPIO_PORT_P1,
GPIO_PIN0
);
}
| {
"content_hash": "477efc0f45d4f650b3d5f379f38f0ee7",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 83,
"avg_line_length": 34.049586776859506,
"alnum_prop": 0.47184466019417476,
"repo_name": "ekawahyu/MSP430Ware",
"id": "ab9582b5e959b6ad7c58c8a03f0306b896dd10cb",
"size": "5797",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/MSP430F5xx_6xx/comp_b/comp_b_ex2_1V5RefInt.c",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "18028147"
},
{
"name": "C++",
"bytes": "3057647"
},
{
"name": "CSS",
"bytes": "110450"
},
{
"name": "Java",
"bytes": "18394"
},
{
"name": "JavaScript",
"bytes": "14484"
},
{
"name": "XSLT",
"bytes": "3447"
}
],
"symlink_target": ""
} |
/**
* FavoriteDao
* @flow
*/
'use strict';
import {
AsyncStorage,
} from 'react-native';
const FAVORITE_KEY_PREFIX='favorite_'
export default class FavoriteDao{
constructor(flag) {
this.flag = flag;
this.favoriteKey=FAVORITE_KEY_PREFIX+flag;
}
saveFavoriteItem(key,vaule,callback) {
AsyncStorage.setItem(key,vaule,(error,result)=>{
if (!error) {//更新Favorite的key
this.updateFavoriteKeys(key,true);
}
});
}
/**
* 更新Favorite key集合
* @param isAdd true 添加,false 删除
* **/
updateFavoriteKeys(key,isAdd){
AsyncStorage.getItem(this.favoriteKey,(error,result)=>{
if (!error) {
var favoriteKeys=[];
if (result) {
favoriteKeys=JSON.parse(result);
}
var index=favoriteKeys.indexOf(key);
if(isAdd){
if (index===-1)favoriteKeys.push(key);
}else {
if (index!==-1)favoriteKeys.splice(index, 1);
}
AsyncStorage.setItem(this.favoriteKey,JSON.stringify(favoriteKeys));
}
});
}
getFavoriteKeys(){//获取收藏的Respository对应的key
return new Promise((resolve,reject)=>{
AsyncStorage.getItem(this.favoriteKey,(error,result)=>{
if (!error) {
try {
resolve(JSON.parse(result));
} catch (e) {
reject(error);
}
}else {
reject(error);
}
});
});
}
removeFavoriteItem(key) {
AsyncStorage.removeItem(key,(error,result)=>{
if (!error) {
this.updateFavoriteKeys(key,false);
}
});
}
getAllItems() {
return new Promise((resolve,reject)=> {
this.getFavoriteKeys().then((keys)=> {
var items = [];
if (keys) {
AsyncStorage.multiGet(keys, (err, stores) => {
try {
stores.map((result, i, store) => {
// get at each store's key/value so you can work with it
let key = store[i][0];
let value = store[i][1];
if (value)items.push(JSON.parse(value));
});
resolve(items);
} catch (e) {
reject(e);
}
});
} else {
resolve(items);
}
}).catch((e)=> {
reject(e);
})
})
}
}
| {
"content_hash": "abccec409cdb7ccef77abea4d64dd43f",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 76,
"avg_line_length": 23.448979591836736,
"alnum_prop": 0.515230635335074,
"repo_name": "KissLuckystar/HotelMarketingApp",
"id": "24f39dcf9548649cb46d903e3bf0581ea4afba82",
"size": "2336",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/expand/dao/FavoriteDao.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1519"
},
{
"name": "JavaScript",
"bytes": "169288"
},
{
"name": "Objective-C",
"bytes": "4449"
},
{
"name": "Python",
"bytes": "1659"
}
],
"symlink_target": ""
} |
package vg.civcraft.mc.namelayer.misc.v1_9_R1;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.logging.Logger;
import com.mojang.authlib.GameProfile;
import net.minecraft.server.v1_9_R1.EntityHuman;
import net.minecraft.server.v1_9_R1.MinecraftServer;
import org.bukkit.craftbukkit.v1_9_R1.entity.CraftHumanEntity;
import org.bukkit.entity.Player;
import vg.civcraft.mc.namelayer.misc.ProfileInterface;
// meh package change, when i get rid of 1.7 compatibility come here
public class ProfileModifier implements ProfileInterface {
private static final Logger log = Logger.getLogger(ProfileModifier.class.getSimpleName());
public void setPlayerProfle(Player player, String name) {
String oldName = player.getName();
if (name.length() > 16) {
log.info(String.format("The player %s (%s) was kicked from the server due to his "
+ "name already existing but now becoming over 16 characters.",
name, player.getUniqueId().toString()));
}
try {
// start of getting the GameProfile
CraftHumanEntity craftHuman = (CraftHumanEntity) player;
EntityHuman human = craftHuman.getHandle();
Field fieldName = EntityHuman.class.getDeclaredField("bR");
fieldName.setAccessible(true);
GameProfile prof = (GameProfile) fieldName.get(human);
// End
// Start of adding a new name
Field nameUpdate = prof.getClass().getDeclaredField("name");
setFinalStatic(nameUpdate, name, prof);
MinecraftServer.getServer().getUserCache().a(prof);
// end
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.setDisplayName(name);
player.setPlayerListName(name);
player.setCustomName(name);
log.info(String.format("The player %s has had his name changed to %s.", oldName, name));
}
public void setFinalStatic(Field field, Object newValue, Object profile) {
GameProfile prof = (GameProfile) profile;
try {
field.setAccessible(true);
// remove final modifier from field
Field modifiersField;
modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField
.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(prof, newValue);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| {
"content_hash": "e44effdb1b1d7b06d08536e3a76bc56a",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 91,
"avg_line_length": 33.61363636363637,
"alnum_prop": 0.7305611899932387,
"repo_name": "suirad/NameLayer",
"id": "542d0142a29587c9092d681e69c17a97074cc459",
"size": "2958",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "nms/v1_9_R1/src/main/java/vg/civcraft/mc/namelayer/misc/v1_9_R1/ProfileModifier.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "376008"
}
],
"symlink_target": ""
} |
package autorest
import (
"fmt"
"log"
"net/http"
"os"
"reflect"
"testing"
"time"
"github.com/azure/go-autorest/autorest/mocks"
)
func ExampleSendWithSender() {
client := mocks.NewSender()
client.EmitStatus("202 Accepted", http.StatusAccepted)
logger := log.New(os.Stdout, "autorest: ", 0)
na := NullAuthorizer{}
req, _ := Prepare(&http.Request{},
AsGet(),
WithBaseURL("https://microsoft.com/a/b/c/"),
na.WithAuthorization())
r, _ := SendWithSender(client, req,
WithLogging(logger),
DoErrorIfStatusCode(http.StatusAccepted),
DoCloseIfError(),
DoRetryForAttempts(5, time.Duration(0)))
Respond(r,
ByClosing())
// Output:
// autorest: Sending GET https://microsoft.com/a/b/c/
// autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted
// autorest: Sending GET https://microsoft.com/a/b/c/
// autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted
// autorest: Sending GET https://microsoft.com/a/b/c/
// autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted
// autorest: Sending GET https://microsoft.com/a/b/c/
// autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted
// autorest: Sending GET https://microsoft.com/a/b/c/
// autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted
}
func ExampleDoRetryForAttempts() {
client := mocks.NewSender()
client.EmitErrors(10)
// Retry with backoff -- ensure returned Bodies are closed
r, _ := SendWithSender(client, mocks.NewRequest(),
DoCloseIfError(),
DoRetryForAttempts(5, time.Duration(0)))
Respond(r,
ByClosing())
fmt.Printf("Retry stopped after %d attempts", client.Attempts())
// Output: Retry stopped after 5 attempts
}
func ExampleDoErrorIfStatusCode() {
client := mocks.NewSender()
client.EmitStatus("204 NoContent", http.StatusNoContent)
// Chain decorators to retry the request, up to five times, if the status code is 204
r, _ := SendWithSender(client, mocks.NewRequest(),
DoErrorIfStatusCode(http.StatusNoContent),
DoCloseIfError(),
DoRetryForAttempts(5, time.Duration(0)))
Respond(r,
ByClosing())
fmt.Printf("Retry stopped after %d attempts with code %s", client.Attempts(), r.Status)
// Output: Retry stopped after 5 attempts with code 204 NoContent
}
func TestSendWithSenderRunsDecoratorsInOrder(t *testing.T) {
client := mocks.NewSender()
s := ""
r, err := SendWithSender(client, mocks.NewRequest(),
withMessage(&s, "a"),
withMessage(&s, "b"),
withMessage(&s, "c"))
if err != nil {
t.Errorf("autorest: SendWithSender returned an error (%v)", err)
}
Respond(r,
ByClosing())
if s != "abc" {
t.Errorf("autorest: SendWithSender invoke decorators out of order; expected 'abc', received '%s'", s)
}
}
func TestCreateSender(t *testing.T) {
f := false
s := CreateSender(
(func() SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
f = true
return nil, nil
})
}
})())
s.Do(&http.Request{})
if !f {
t.Error("autorest: CreateSender failed to apply supplied decorator")
}
}
func TestSend(t *testing.T) {
f := false
Send(&http.Request{},
(func() SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
f = true
return nil, nil
})
}
})())
if !f {
t.Error("autorest: Send failed to apply supplied decorator")
}
}
func TestAfterDelayWaits(t *testing.T) {
client := mocks.NewSender()
d := 10 * time.Millisecond
tt := time.Now()
r, _ := SendWithSender(client, mocks.NewRequest(),
AfterDelay(d))
s := time.Since(tt)
if s < d {
t.Error("autorest: AfterDelay failed to wait for at least the specified duration")
}
Respond(r,
ByClosing())
}
func TestAfterRetryDelayWaits(t *testing.T) {
client := mocks.NewSender()
client.EmitErrors(-1)
d := 10 * time.Millisecond
resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted)
setAcceptedHeaders(resp)
setRetryHeader(resp, d)
client.SetResponse(resp)
client.ReuseResponse(true)
tt := time.Now()
r, _ := SendWithSender(client, mocks.NewRequest(),
AfterRetryDelay(d),
DoRetryForAttempts(2, time.Duration(0)))
s := time.Since(tt)
if s < d {
t.Error("autorest: AfterRetryDelay failed to wait for at least the specified duration")
}
Respond(r,
ByClosing())
}
// Disable test for TravisCI
// func TestAfterDelayDoesNotWaitTooLong(t *testing.T) {
// client := mocks.NewSender()
// // Establish a baseline and then set the wait to 10x that amount
// // -- Waiting 10x the baseline should be long enough for a real test while not slowing the
// // tests down too much
// tt := time.Now()
// SendWithSender(client, mocks.NewRequest())
// d := 10 * time.Since(tt)
// tt = time.Now()
// r, _ := SendWithSender(client, mocks.NewRequest(),
// AfterDelay(d))
// s := time.Since(tt)
// if s > 5*d {
// t.Error("autorest: AfterDelay waited too long (more than five times the specified duration")
// }
// Respond(r,
// ByClosing())
// }
func TestAsIs(t *testing.T) {
client := mocks.NewSender()
r1 := mocks.NewResponse()
r2, err := SendWithSender(client, mocks.NewRequest(),
(func() SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
return r1, nil
})
}
})(),
AsIs())
if err != nil {
t.Errorf("autorest: AsIs returned an unexpected error (%v)", err)
} else if !reflect.DeepEqual(r1, r2) {
t.Errorf("autorest: AsIs modified the response -- received %v, expected %v", r2, r1)
}
Respond(r1,
ByClosing())
Respond(r2,
ByClosing())
}
func TestDoCloseIfError(t *testing.T) {
client := mocks.NewSender()
client.EmitStatus("400 BadRequest", http.StatusBadRequest)
r, _ := SendWithSender(client, mocks.NewRequest(),
DoErrorIfStatusCode(http.StatusBadRequest),
DoCloseIfError())
if r.Body.(*mocks.Body).IsOpen() {
t.Error("autorest: Expected DoCloseIfError to close response body -- it was left open")
}
Respond(r,
ByClosing())
}
func TestDoCloseIfErrorAcceptsNilResponse(t *testing.T) {
client := mocks.NewSender()
SendWithSender(client, mocks.NewRequest(),
(func() SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
resp, err := s.Do(r)
if err != nil {
resp.Body.Close()
}
return nil, fmt.Errorf("Faux Error")
})
}
})(),
DoCloseIfError())
}
func TestDoCloseIfErrorAcceptsNilBody(t *testing.T) {
client := mocks.NewSender()
SendWithSender(client, mocks.NewRequest(),
(func() SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
resp, err := s.Do(r)
if err != nil {
resp.Body.Close()
}
resp.Body = nil
return resp, fmt.Errorf("Faux Error")
})
}
})(),
DoCloseIfError())
}
func TestDoErrorIfStatusCode(t *testing.T) {
client := mocks.NewSender()
client.EmitStatus("400 BadRequest", http.StatusBadRequest)
r, err := SendWithSender(client, mocks.NewRequest(),
DoErrorIfStatusCode(http.StatusBadRequest),
DoCloseIfError())
if err == nil {
t.Error("autorest: DoErrorIfStatusCode failed to emit an error for passed code")
}
Respond(r,
ByClosing())
}
func TestDoErrorIfStatusCodeIgnoresStatusCodes(t *testing.T) {
client := mocks.NewSender()
client.EmitStatus("202 Accepted", http.StatusAccepted)
r, err := SendWithSender(client, mocks.NewRequest(),
DoErrorIfStatusCode(http.StatusBadRequest),
DoCloseIfError())
if err != nil {
t.Error("autorest: DoErrorIfStatusCode failed to ignore a status code")
}
Respond(r,
ByClosing())
}
func TestDoErrorUnlessStatusCode(t *testing.T) {
client := mocks.NewSender()
client.EmitStatus("400 BadRequest", http.StatusBadRequest)
r, err := SendWithSender(client, mocks.NewRequest(),
DoErrorUnlessStatusCode(http.StatusAccepted),
DoCloseIfError())
if err == nil {
t.Error("autorest: DoErrorUnlessStatusCode failed to emit an error for an unknown status code")
}
Respond(r,
ByClosing())
}
func TestDoErrorUnlessStatusCodeIgnoresStatusCodes(t *testing.T) {
client := mocks.NewSender()
client.EmitStatus("202 Accepted", http.StatusAccepted)
r, err := SendWithSender(client, mocks.NewRequest(),
DoErrorUnlessStatusCode(http.StatusAccepted),
DoCloseIfError())
if err != nil {
t.Error("autorest: DoErrorUnlessStatusCode emitted an error for a knonwn status code")
}
Respond(r,
ByClosing())
}
func TestDoRetryForAttemptsStopsAfterSuccess(t *testing.T) {
client := mocks.NewSender()
r, err := SendWithSender(client, mocks.NewRequest(),
DoRetryForAttempts(5, time.Duration(0)))
if client.Attempts() != 1 {
t.Errorf("autorest: DoRetryForAttempts failed to stop after success -- expected attempts %v, actual %v",
1, client.Attempts())
}
if err != nil {
t.Errorf("autorest: DoRetryForAttempts returned an unexpected error (%v)", err)
}
Respond(r,
ByClosing())
}
func TestDoRetryForAttemptsStopsAfterAttempts(t *testing.T) {
client := mocks.NewSender()
client.EmitErrors(10)
r, err := SendWithSender(client, mocks.NewRequest(),
DoRetryForAttempts(5, time.Duration(0)),
DoCloseIfError())
if err == nil {
t.Error("autorest: Mock client failed to emit errors")
}
Respond(r,
ByClosing())
if client.Attempts() != 5 {
t.Error("autorest: DoRetryForAttempts failed to stop after specified number of attempts")
}
}
func TestDoRetryForAttemptsReturnsResponse(t *testing.T) {
client := mocks.NewSender()
client.EmitErrors(1)
r, err := SendWithSender(client, mocks.NewRequest(),
DoRetryForAttempts(1, time.Duration(0)))
if err == nil {
t.Error("autorest: Mock client failed to emit errors")
}
if r == nil {
t.Error("autorest: DoRetryForAttempts failed to return the underlying response")
}
Respond(r,
ByClosing())
}
func TestDoRetryForDurationStopsAfterSuccess(t *testing.T) {
client := mocks.NewSender()
r, err := SendWithSender(client, mocks.NewRequest(),
DoRetryForDuration(10*time.Millisecond, time.Duration(0)))
if client.Attempts() != 1 {
t.Errorf("autorest: DoRetryForDuration failed to stop after success -- expected attempts %v, actual %v",
1, client.Attempts())
}
if err != nil {
t.Errorf("autorest: DoRetryForDuration returned an unexpected error (%v)", err)
}
Respond(r,
ByClosing())
}
func TestDoRetryForDurationStopsAfterDuration(t *testing.T) {
client := mocks.NewSender()
client.EmitErrors(-1)
d := 10 * time.Millisecond
start := time.Now()
r, err := SendWithSender(client, mocks.NewRequest(),
DoRetryForDuration(d, time.Duration(0)),
DoCloseIfError())
if err == nil {
t.Error("autorest: Mock client failed to emit errors")
}
Respond(r,
ByClosing())
if time.Now().Sub(start) < d {
t.Error("autorest: DoRetryForDuration failed stopped too soon")
}
}
func TestDoRetryForDurationStopsWithinReason(t *testing.T) {
client := mocks.NewSender()
client.EmitErrors(-1)
d := 10 * time.Millisecond
start := time.Now()
r, err := SendWithSender(client, mocks.NewRequest(),
DoRetryForDuration(d, time.Duration(0)),
DoCloseIfError())
if err == nil {
t.Error("autorest: Mock client failed to emit errors")
}
Respond(r,
ByClosing())
if time.Now().Sub(start) > (5 * d) {
t.Error("autorest: DoRetryForDuration failed stopped soon enough (exceeded 5 times specified duration)")
}
}
func TestDoRetryForDurationReturnsResponse(t *testing.T) {
client := mocks.NewSender()
client.EmitErrors(-1)
r, err := SendWithSender(client, mocks.NewRequest(),
DoRetryForDuration(10*time.Millisecond, time.Duration(0)),
DoCloseIfError())
if err == nil {
t.Error("autorest: Mock client failed to emit errors")
}
if r == nil {
t.Error("autorest: DoRetryForDuration failed to return the underlying response")
}
Respond(r,
ByClosing())
}
func TestDelayForBackoff(t *testing.T) {
// Establish a baseline and then set the wait to 10x that amount
// -- Waiting 10x the baseline should be long enough for a real test while not slowing the
// tests down too much
tt := time.Now()
DelayForBackoff(time.Millisecond, 0)
d := 10 * time.Since(tt)
start := time.Now()
DelayForBackoff(d, 1)
if time.Now().Sub(start) < d {
t.Error("autorest: DelayForBackoff did not delay as long as expected")
}
}
// Disable test for TravisCI
// func TestDelayForBackoffWithinReason(t *testing.T) {
// // Establish a baseline and then set the wait to 10x that amount
// // -- Waiting 10x the baseline should be long enough for a real test while not slowing the
// // tests down too much
// tt := time.Now()
// DelayForBackoff(time.Millisecond, 0)
// d := 10 * time.Since(tt)
// start := time.Now()
// DelayForBackoff(d, 1)
// if time.Now().Sub(start) > (time.Duration(5.0) * d) {
// t.Error("autorest: DelayForBackoff delayed too long (exceeded 5 times the specified duration)")
// }
// }
| {
"content_hash": "4ba74ac857f8e3013567bc76504fc50e",
"timestamp": "",
"source": "github",
"line_count": 505,
"max_line_length": 106,
"avg_line_length": 25.61188118811881,
"alnum_prop": 0.6915880624710067,
"repo_name": "bingosummer/azure_storage_service_broker",
"id": "bf88b4be6401d112a32ffdba2c5ddd1c8a9086da",
"size": "12934",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/sender_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "30876"
},
{
"name": "Shell",
"bytes": "1961"
}
],
"symlink_target": ""
} |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="nb" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Gamecash</source>
<translation>Om Gamecash</translation>
</message>
<message>
<location line="+39"/>
<source><b>Gamecash</b> version</source>
<translation><b>Gamecash</b> versjon</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Dette er eksperimentell programvare.
Distribuert under MIT/X11 programvarelisensen, se medfølgende fil COPYING eller http://www.opensource.org/licenses/mit-license.php.
Dette produktet inneholder programvare utviklet av OpenSSL prosjektet for bruk i OpenSSL Toolkit (http://www.openssl.org/) og kryptografisk programvare skrevet av Eric Young ([email protected]) og UPnP programvare skrevet av Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Gamecash developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adressebok</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Dobbeltklikk for å redigere adresse eller merkelapp</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Lag en ny adresse</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopier den valgte adressen til systemets utklippstavle</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Ny Adresse</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Gamecash addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Dette er dine Gamecash-adresser for mottak av betalinger. Du kan gi forskjellige adresser til alle som skal betale deg for å holde bedre oversikt.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopier Adresse</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Vis &QR Kode</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Gamecash address</source>
<translation>Signer en melding for å bevise at du eier en Gamecash-adresse</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signér &Melding</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Slett den valgte adressen fra listen.</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Eksporter data fra nåværende fane til fil</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Gamecash address</source>
<translation>Verifiser en melding for å være sikker på at den ble signert av en angitt Gamecash-adresse</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verifiser Melding</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Slett</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Gamecash addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopier &Merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Rediger</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Send &Coins</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Eksporter adressebok</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparert fil (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Feil ved eksportering</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ingen merkelapp)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialog for Adgangsfrase</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Angi adgangsfrase</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Ny adgangsfrase</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Gjenta ny adgangsfrase</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Skriv inn den nye adgangsfrasen for lommeboken.<br/>Vennligst bruk en adgangsfrase med <b>10 eller flere tilfeldige tegn</b>, eller <b>åtte eller flere ord</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Krypter lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Denne operasjonen krever adgangsfrasen til lommeboken for å låse den opp.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Lås opp lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Denne operasjonen krever adgangsfrasen til lommeboken for å dekryptere den.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Dekrypter lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Endre adgangsfrase</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Skriv inn gammel og ny adgangsfrase for lommeboken.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Bekreft kryptering av lommebok</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation>Advarsel: Hvis du krypterer lommeboken og mister adgangsfrasen, så vil du <b>MISTE ALLE DINE LITECOINS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Er du sikker på at du vil kryptere lommeboken?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>VIKTIG: Tidligere sikkerhetskopier av din lommebok-fil, bør erstattes med den nylig genererte, krypterte filen, da de blir ugyldiggjort av sikkerhetshensyn så snart du begynner å bruke den nye krypterte lommeboken.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Advarsel: Caps Lock er på !</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Lommebok kryptert</translation>
</message>
<message>
<location line="-56"/>
<source>Gamecash will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your gamecashs from being stolen by malware infecting your computer.</source>
<translation>Gamecash vil nå lukkes for å fullføre krypteringsprosessen. Husk at kryptering av lommeboken ikke fullt ut kan beskytte dine gamecashs fra å bli stjålet om skadevare infiserer datamaskinen.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Kryptering av lommebok feilet</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Kryptering av lommebok feilet på grunn av en intern feil. Din lommebok ble ikke kryptert.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>De angitte adgangsfrasene er ulike.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Opplåsing av lommebok feilet</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Adgangsfrasen angitt for dekryptering av lommeboken var feil.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Dekryptering av lommebok feilet</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Adgangsfrase for lommebok endret.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Signer &melding...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synkroniserer med nettverk...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Oversikt</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Vis generell oversikt over lommeboken</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transaksjoner</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Vis transaksjonshistorikk</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Rediger listen over adresser og deres merkelapper</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Vis listen over adresser for mottak av betalinger</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Avslutt</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Avslutt applikasjonen</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Gamecash</source>
<translation>Vis informasjon om Gamecash</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Om &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Vis informasjon om Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Innstillinger...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Krypter Lommebok...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Lag &Sikkerhetskopi av Lommebok...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Endre Adgangsfrase...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importere blokker...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Re-indekserer blokker på disk...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Gamecash address</source>
<translation>Send til en Gamecash-adresse</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Gamecash</source>
<translation>Endre oppsett for Gamecash</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Sikkerhetskopiér lommebok til annet sted</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Endre adgangsfrasen brukt for kryptering av lommebok</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Feilsøkingsvindu</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Åpne konsoll for feilsøk og diagnostikk</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verifiser melding...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Gamecash</source>
<translation>Gamecash</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Lommebok</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Send</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Motta</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Adressebok</translation>
</message>
<message>
<location line="+22"/>
<source>&About Gamecash</source>
<translation>&Om Gamecash</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Gjem / vis</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Vis eller skjul hovedvinduet</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Krypter de private nøklene som tilhører lommeboken din</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Gamecash addresses to prove you own them</source>
<translation>Signér en melding for å bevise at du eier denne adressen</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Gamecash addresses</source>
<translation>Bekreft meldinger for å være sikker på at de ble signert av en angitt Gamecash-adresse</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Fil</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Innstillinger</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Hjelp</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Verktøylinje for faner</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnett]</translation>
</message>
<message>
<location line="+47"/>
<source>Gamecash client</source>
<translation>Gamecashklient</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Gamecash network</source>
<translation><numerusform>%n aktiv forbindelse til Gamecash-nettverket</numerusform><numerusform>%n aktive forbindelser til Gamecash-nettverket</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Lastet %1 blokker med transaksjonshistorikk.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Transaksjoner etter dette vil ikke være synlige enda.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Denne transaksjonen overstiger størrelsesbegrensningen. Du kan likevel sende den med et gebyr på %1, som går til nodene som prosesserer transaksjonen din og støtter nettverket. Vil du betale gebyret?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Ajour</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Kommer ajour...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Bekreft transaksjonsgebyr</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Sendt transaksjon</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Innkommende transaksjon</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dato: %1
Beløp: %2
Type: %3
Adresse: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI håndtering</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Gamecash address or malformed URI parameters.</source>
<translation>URI kunne ikke tolkes! Dette kan forårsakes av en ugyldig Gamecash-adresse eller feil i URI-parametere.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Lommeboken er <b>kryptert</b> og for tiden <b>ulåst</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Lommeboken er <b>kryptert</b> og for tiden <b>låst</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Gamecash can no longer continue safely and will quit.</source>
<translation>En fatal feil har inntruffet. Det er ikke trygt å fortsette og Gamecash må derfor avslutte.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Nettverksvarsel</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Rediger adresse</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Merkelapp</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Merkelappen koblet til denne adressen i adresseboken</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Adressen til denne oppføringen i adresseboken. Denne kan kun endres for utsendingsadresser.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Ny mottaksadresse</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Ny utsendingsadresse</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Rediger mottaksadresse</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Rediger utsendingsadresse</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Den oppgitte adressen "%1" er allerede i adresseboken.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Gamecash address.</source>
<translation>Den angitte adressed "%1" er ikke en gyldig Gamecash-adresse.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Kunne ikke låse opp lommeboken.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Generering av ny nøkkel feilet.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Gamecash-Qt</source>
<translation>Gamecash-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versjon</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Bruk:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>kommandolinjevalg</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>valg i brukergrensesnitt</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Sett språk, for eksempel "nb_NO" (standardverdi: fra operativsystem)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Start minimert
</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Vis splashskjerm ved oppstart (standardverdi: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Innstillinger</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Hoved</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Betal transaksjons&gebyr</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Gamecash after logging in to the system.</source>
<translation>Start Gamecash automatisk etter innlogging.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Gamecash on system login</source>
<translation>&Start Gamecash ved systeminnlogging</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Nettverk</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Gamecash client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Åpne automatisk Gamecash klientporten på ruteren. Dette virker kun om din ruter støtter UPnP og dette er påslått.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Sett opp port vha. &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Gamecash network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Koble til Gamecash-nettverket gjennom en SOCKS proxy (f.eks. ved tilkobling gjennom Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Koble til gjenom SOCKS proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-adresse for mellomtjener (f.eks. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Proxyens port (f.eks. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Versjon:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Proxyens SOCKS versjon (f.eks. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Vindu</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Vis kun ikon i systemkurv etter minimering av vinduet.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimer til systemkurv istedenfor oppgavelinjen</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimerer vinduet istedenfor å avslutte applikasjonen når vinduet lukkes. Når dette er slått på avsluttes applikasjonen kun ved å velge avslutt i menyen.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimer ved lukking</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Visning</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Språk for brukergrensesnitt</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Gamecash.</source>
<translation>Språket for brukergrensesnittet kan settes her. Innstillingen trer i kraft ved omstart av Gamecash.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Enhet for visning av beløper:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Velg standard delt enhet for visning i grensesnittet og for sending av gamecashs.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Gamecash addresses in the transaction list or not.</source>
<translation>Om Gamecash-adresser skal vises i transaksjonslisten eller ikke.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Vis adresser i transaksjonslisten</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Avbryt</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Bruk</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>standardverdi</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Advarsel</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Gamecash.</source>
<translation>Denne innstillingen trer i kraft etter omstart av Gamecash.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Angitt proxyadresse er ugyldig.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Skjema</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Gamecash network after a connection is established, but this process has not completed yet.</source>
<translation>Informasjonen som vises kan være foreldet. Din lommebok synkroniseres automatisk med Gamecash-nettverket etter at tilkobling er opprettet, men denne prosessen er ikke ferdig enda.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Ubekreftet</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Lommebok</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Umoden:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Minet saldo har ikke modnet enda</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Siste transaksjoner</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Din nåværende saldo</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Totalt antall ubekreftede transaksjoner som ikke telles med i saldo enda</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>ute av synk</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start gamecash: click-to-pay handler</source>
<translation>Kan ikke starte gamecash: klikk-og-betal håndterer</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Dialog for QR Kode</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Etterspør Betaling</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Beløp:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Merkelapp:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Melding:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Lagre Som...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Feil ved koding av URI i QR kode.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Angitt beløp er ugyldig.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resulterende URI for lang, prøv å redusere teksten for merkelapp / melding.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Lagre QR Kode</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG bilder (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Klientnavn</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>-</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Klientversjon</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informasjon</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Bruker OpenSSL versjon</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Oppstartstidspunkt</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Nettverk</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Antall tilkoblinger</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>På testnett</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokkjeden</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Nåværende antall blokker</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Estimert totalt antall blokker</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Tidspunkt for siste blokk</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Åpne</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Kommandolinjevalg</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Gamecash-Qt help message to get a list with possible Gamecash command-line options.</source>
<translation>Vis Gamecash-Qt hjelpemelding for å få en liste med mulige kommandolinjevalg.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Vis</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsoll</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Byggedato</translation>
</message>
<message>
<location line="-104"/>
<source>Gamecash - Debug window</source>
<translation>Gamecash - vindu for feilsøk</translation>
</message>
<message>
<location line="+25"/>
<source>Gamecash Core</source>
<translation>Gamecash Kjerne</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Loggfil for feilsøk</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Gamecash debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Åpne Gamecash loggfil for feilsøk fra datamappen. Dette kan ta noen sekunder for store loggfiler.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Tøm konsoll</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Gamecash RPC console.</source>
<translation>Velkommen til Gamecash RPC konsoll.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Bruk opp og ned pil for å navigere historikken, og <b>Ctrl-L</b> for å tømme skjermen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Skriv <b>help</b> for en oversikt over kommandoer.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Send Gamecashs</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Send til flere enn én mottaker</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Legg til Mottaker</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Fjern alle transaksjonsfelter</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Fjern &Alt</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Bekreft sending</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>S&end</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> til %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Bekreft sending av gamecashs</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Er du sikker på at du vil sende %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> og </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Adresse for mottaker er ugyldig.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Beløpen som skal betales må være over 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Beløpet overstiger saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Totalbeløpet overstiger saldo etter at %1 transaksjonsgebyr er lagt til.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Duplikate adresser funnet. Kan bare sende én gang til hver adresse per operasjon.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Feil: Opprettelse av transaksjon feilet </translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Feil: Transaksjonen ble avvist. Dette kan skje om noe av beløpet allerede var brukt, f.eks. hvis du kopierte wallet.dat og noen gamecashs ble brukt i kopien men ikke ble markert som brukt her.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Skjema</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Beløp:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Betal &Til:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen betalingen skal sendes til (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Skriv inn en merkelapp for denne adressen for å legge den til i din adressebok</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Merkelapp:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Velg adresse fra adresseboken</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Lim inn adresse fra utklippstavlen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Fjern denne mottakeren</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Gamecash address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Skriv inn en Gamecash adresse (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signaturer - Signer / Verifiser en melding</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Signér Melding</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Du kan signere meldinger med dine adresser for å bevise at du eier dem. Ikke signér vage meldinger da phishing-angrep kan prøve å lure deg til å signere din identitet over til andre. Signér kun fullt detaljerte utsagn som du er enig i.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen for signering av meldingen (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Velg en adresse fra adresseboken</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Lim inn adresse fra utklippstavlen</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Skriv inn meldingen du vil signere her</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopier valgt signatur til utklippstavle</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Gamecash address</source>
<translation>Signer meldingen for å bevise at du eier denne Gamecash-adressen</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Tilbakestill alle felter for meldingssignering</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Fjern &Alt</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verifiser Melding</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Angi adresse for signering, melding (vær sikker på at du kopierer linjeskift, mellomrom, tab, etc. helt nøyaktig) og signatur under for å verifisere meldingen. Vær forsiktig med at du ikke gir signaturen mer betydning enn det som faktisk står i meldingen, for å unngå å bli lurt av såkalte "man-in-the-middle" angrep.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen meldingen var signert med (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Gamecash address</source>
<translation>Verifiser meldingen for å være sikker på at den ble signert av den angitte Gamecash-adressen</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Tilbakestill alle felter for meldingsverifikasjon</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Gamecash address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Skriv inn en Gamecash adresse (f.eks. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Klikk "Signer Melding" for å generere signatur</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Gamecash signature</source>
<translation>Angi Gamecash signatur</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Angitt adresse er ugyldig.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Vennligst sjekk adressen og prøv igjen.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Angitt adresse refererer ikke til en nøkkel.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Opplåsing av lommebok ble avbrutt.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Privat nøkkel for den angitte adressen er ikke tilgjengelig.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Signering av melding feilet.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Melding signert.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Signaturen kunne ikke dekodes.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Vennligst sjekk signaturen og prøv igjen.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Signaturen passer ikke til meldingen.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verifikasjon av melding feilet.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Melding verifisert.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Gamecash developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnett]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Åpen til %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/frakoblet</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/ubekreftet</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 bekreftelser</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, kringkast gjennom %n node</numerusform><numerusform>, kringkast gjennom %n noder</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Kilde</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generert</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Fra</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Til</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>egen adresse</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>merkelapp</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Kredit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>blir moden om %n blokk</numerusform><numerusform>blir moden om %n blokker</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>ikke akseptert</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debet</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaksjonsgebyr</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Nettobeløp</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Melding</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Kommentar</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaksjons-ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Genererte gamecashs må modnes 120 blokker før de kan brukes. Da du genererte denne blokken ble den kringkastet til nettverket for å legges til i blokkjeden. Hvis den ikke kommer inn i kjeden får den tilstanden "ikke akseptert" og vil ikke kunne brukes. Dette skjer noen ganger hvis en annen node genererer en blokk noen sekunder fra din.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informasjon for feilsøk</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaksjon</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Inndata</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>sann</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>usann</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, har ikke blitt kringkastet uten problemer enda.</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>ukjent</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaksjonsdetaljer</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Her vises en detaljert beskrivelse av transaksjonen</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Åpen til %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Frakoblet (%1 bekreftelser)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Ubekreftet (%1 av %2 bekreftelser)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bekreftet (%1 bekreftelser)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Minet saldo blir tilgjengelig når den modner om %n blokk</numerusform><numerusform>Minet saldo blir tilgjengelig når den modner om %n blokker</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Denne blokken har ikke blitt mottatt av noen andre noder og vil sannsynligvis ikke bli akseptert!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generert men ikke akseptert</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Mottatt med</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Mottatt fra</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Betaling til deg selv</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Utvunnet</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>-</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaksjonsstatus. Hold muspekeren over dette feltet for å se antall bekreftelser.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Dato og tid for da transaksjonen ble mottat.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type transaksjon.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Mottaksadresse for transaksjonen</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Beløp fjernet eller lagt til saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Alle</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>I dag</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Denne uken</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Denne måneden</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Forrige måned</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Dette året</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Intervall...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Mottatt med</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Til deg selv</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Utvunnet</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Andre</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Skriv inn adresse eller merkelapp for søk</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimumsbeløp</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopier merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopiér beløp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Kopier transaksjons-ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Rediger merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Vis transaksjonsdetaljer</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Eksporter transaksjonsdata</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparert fil (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Bekreftet</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Merkelapp</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Beløp</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Feil ved eksport</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Intervall:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>til</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Send Gamecashs</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Eksporter data fra nåværende fane til fil</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Sikkerhetskopier lommebok</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Lommebokdata (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Sikkerhetskopiering feilet</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>En feil oppstod under lagringen av lommeboken til den nye plasseringen.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Sikkerhetskopiering fullført</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Lommebokdata ble lagret til den nye plasseringen. </translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Gamecash version</source>
<translation>Gamecash versjon</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Bruk:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or gamecashd</source>
<translation>Send kommando til -server eller gamecashd</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>List opp kommandoer</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Vis hjelpetekst for en kommando</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Innstillinger:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: gamecash.conf)</source>
<translation>Angi konfigurasjonsfil (standardverdi: gamecash.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: gamecashd.pid)</source>
<translation>Angi pid-fil (standardverdi: gamecashd.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Angi mappe for datafiler</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Sett størrelse på mellomlager for database i megabytes (standardverdi: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Lytt etter tilkoblinger på <port> (standardverdi: 9333 eller testnet: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Hold maks <n> koblinger åpne til andre noder (standardverdi: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Koble til node for å hente adresser til andre noder, koble så fra igjen</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Angi din egen offentlige adresse</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Grenseverdi for å koble fra noder med dårlig oppførsel (standardverdi: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Antall sekunder noder med dårlig oppførsel hindres fra å koble til på nytt (standardverdi: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>En feil oppstod ved opprettelse av RPC port %u for lytting: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>Lytt etter JSON-RPC tilkoblinger på <port> (standardverdi: 9332 or testnet: 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Ta imot kommandolinje- og JSON-RPC-kommandoer</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Kjør i bakgrunnen som daemon og ta imot kommandoer</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Bruk testnettverket</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Ta imot tilkoblinger fra utsiden (standardverdi: 1 hvis uten -proxy eller -connect)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=gamecashrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Gamecash Alert" [email protected]
</source>
<translation>%s, du må angi rpcpassord i konfigurasjonsfilen.
%s
Det anbefales at du bruker det følgende tilfeldige passordet:
rpcbruker=gamecashrpc
rpcpassord=%s
(du behøver ikke å huske passordet)
Brukernavnet og passordet MÅ IKKE være like.
Om filen ikke eksisterer, opprett den nå med eier-kun-les filrettigheter.
Det er også anbefalt at å sette varselsmelding slik du får melding om problemer.
For eksempel: varselmelding=echo %%s | mail -s "Gamecash varsel" [email protected]</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>En feil oppstod under oppsettet av RPC port %u for IPv6, tilbakestilles til IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Bind til angitt adresse. Bruk [vertsmaskin]:port notasjon for IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Gamecash is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Kjør kommando når relevant varsel blir mottatt (%s i cmd er erstattet med TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Kjør kommando når en lommeboktransaksjon endres (%s i cmd er erstattet med TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Sett maks størrelse for transaksjoner med høy prioritet / lavt gebyr, i bytes (standardverdi: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Advarsel: -paytxfee er satt veldig høyt! Dette er transaksjonsgebyret du betaler når du sender transaksjoner.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Advarsel: Viste transaksjoner kan være feil! Du, eller andre noder, kan trenge en oppgradering.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Gamecash will not work properly.</source>
<translation>Advarsel: Vennligst undersøk at din datamaskin har riktig dato og klokkeslett! Hvis klokken er stilt feil vil ikke Gamecash fungere riktig.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Valg for opprettelse av blokker:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Koble kun til angitt(e) node(r)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Oppdaget korrupt blokkdatabase</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Oppdag egen IP-adresse (standardverdi: 1 ved lytting og uten -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Ønsker du å gjenopprette blokkdatabasen nå?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Feil under oppstart av lommebokdatabasemiljø %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Feil under åpning av blokkdatabase</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Kunne ikke lytte på noen port. Bruk -listen=0 hvis det er dette du vil.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Finn andre noder gjennom DNS-oppslag (standardverdi: 1 med mindre -connect er oppgit)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Gjenopprett blokkjedeindex fra blk000??.dat filer</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Verifiserer blokker...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verifiserer lommebok...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Ugyldig -tor adresse: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maks mottaksbuffer per forbindelse, <n>*1000 bytes (standardverdi: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maks sendebuffer per forbindelse, <n>*1000 bytes (standardverdi: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Koble kun til noder i nettverket <nett> (IPv4, IPv6 eller Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Skriv ekstra informasjon for feilsøk. Medfører at alle -debug* valg tas med</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Skriv ekstra informasjon for feilsøk av nettverk</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Sett tidsstempel på debugmeldinger</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Gamecash Wiki for SSL setup instructions)</source>
<translation>SSL valg: (se Gamecash Wiki for instruksjoner for oppsett av SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Velg versjon av socks proxy (4-5, standardverdi 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Send spor/debug informasjon til konsollet istedenfor debug.log filen</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Send spor/debug informasjon til debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Sett maks blokkstørrelse i bytes (standardverdi: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Sett minimum blokkstørrelse i bytes (standardverdi: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Krymp debug.log filen når klienten starter (standardverdi: 1 hvis uten -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Angi tidsavbrudd for forbindelse i millisekunder (standardverdi: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Bruk UPnP for lytteport (standardverdi: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Bruk UPnP for lytteport (standardverdi: 1 ved lytting)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Bruk en proxy for å nå skjulte tor tjenester (standardverdi: samme som -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Brukernavn for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Advarsel: Denne versjonen er foreldet, oppgradering kreves!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Passord for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Tillat JSON-RPC tilkoblinger fra angitt IP-adresse</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Send kommandoer til node på <ip> (standardverdi: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Eksekvér kommando når beste blokk endrer seg (%s i kommandoen erstattes med blokkens hash)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Oppgradér lommebok til nyeste format</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Angi størrelse på nøkkel-lager til <n> (standardverdi: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Se gjennom blokk-kjeden etter manglende lommeboktransaksjoner</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Bruk OpenSSL (https) for JSON-RPC forbindelser</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Servers sertifikat (standardverdi: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Servers private nøkkel (standardverdi: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Akseptable krypteringsmetoder (standardverdi: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Denne hjelpemeldingen</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Kan ikke binde til %s på denne datamaskinen (bind returnerte feil %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Koble til gjennom socks proxy</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Tillat DNS oppslag for -addnode, -seednode og -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Laster adresser...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Feil ved lasting av wallet.dat: Lommeboken er skadet</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Gamecash</source>
<translation>Feil ved lasting av wallet.dat: Lommeboken krever en nyere versjon av Gamecash</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Gamecash to complete</source>
<translation>Lommeboken måtte skrives om: start Gamecash på nytt for å fullføre</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Feil ved lasting av wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Ugyldig -proxy adresse: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Ukjent nettverk angitt i -onlynet '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Ukjent -socks proxy versjon angitt: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Kunne ikke slå opp -bind adresse: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Kunne ikke slå opp -externalip adresse: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Ugyldig beløp for -paytxfee=<beløp>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Ugyldig beløp</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Utilstrekkelige midler</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Laster blokkindeks...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Legg til node for tilkobling og hold forbindelsen åpen</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Gamecash is probably already running.</source>
<translation>Kan ikke binde til %s på denne datamaskinen. Sannsynligvis kjører Gamecash allerede.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Gebyr per KB for transaksjoner du sender</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Laster lommebok...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Kan ikke nedgradere lommebok</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Kan ikke skrive standardadresse</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Leser gjennom...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Ferdig med lasting</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>For å bruke %s opsjonen</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Feil</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Du må sette rpcpassword=<passord> i konfigurasjonsfilen:
%s
Hvis filen ikke finnes, opprett den med leserettighet kun for eier av filen.</translation>
</message>
</context>
</TS>
| {
"content_hash": "1df44e880f5144be536fa06b2eba7efd",
"timestamp": "",
"source": "github",
"line_count": 2938,
"max_line_length": 395,
"avg_line_length": 38.473791695030634,
"alnum_prop": 0.6266233766233766,
"repo_name": "gamecashofficial/gamecash",
"id": "8f8e8265e25179ad7b8d7ef6da762e9d60bc99c1",
"size": "113266",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/locale/bitcoin_nb.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "32556"
},
{
"name": "C++",
"bytes": "16732500"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50615"
},
{
"name": "Makefile",
"bytes": "103777"
},
{
"name": "NSIS",
"bytes": "6106"
},
{
"name": "Objective-C",
"bytes": "1052"
},
{
"name": "Objective-C++",
"bytes": "5864"
},
{
"name": "OpenEdge ABL",
"bytes": "22243"
},
{
"name": "Python",
"bytes": "69714"
},
{
"name": "QMake",
"bytes": "14714"
},
{
"name": "Roff",
"bytes": "18284"
},
{
"name": "Shell",
"bytes": "16339"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
/**
* This package contains the classes for AutoRestDateTimeTestService.
* Test Infrastructure for AutoRest.
*/
package fixtures.bodydatetime;
| {
"content_hash": "66da04538d7d611c6838534d1e15190d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 74,
"avg_line_length": 35.84615384615385,
"alnum_prop": 0.7639484978540773,
"repo_name": "matt-gibbs/AutoRest",
"id": "f80592157536483047525e247f524e5d21ff3e96",
"size": "466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetime/package-info.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "819"
},
{
"name": "C#",
"bytes": "8136352"
},
{
"name": "CSS",
"bytes": "110"
},
{
"name": "HTML",
"bytes": "274"
},
{
"name": "Java",
"bytes": "3142156"
},
{
"name": "JavaScript",
"bytes": "3665342"
},
{
"name": "PowerShell",
"bytes": "5703"
},
{
"name": "Ruby",
"bytes": "217469"
},
{
"name": "TypeScript",
"bytes": "158338"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 297028 $ -->
<refentry xml:id="function.stats-cdf-weibull" xmlns="http://docbook.org/ns/docbook">
<refnamediv>
<refname>stats_cdf_weibull</refname>
<refpurpose>Not documented</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<type>float</type><methodname>stats_cdf_weibull</methodname>
<methodparam><type>float</type><parameter>par1</parameter></methodparam>
<methodparam><type>float</type><parameter>par2</parameter></methodparam>
<methodparam><type>float</type><parameter>par3</parameter></methodparam>
<methodparam><type>int</type><parameter>which</parameter></methodparam>
</methodsynopsis>
&warn.undocumented.func;
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
<para>
<variablelist>
<varlistentry>
<term><parameter>par1</parameter></term>
<listitem>
<para>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>par2</parameter></term>
<listitem>
<para>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>par3</parameter></term>
<listitem>
<para>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>which</parameter></term>
<listitem>
<para>
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
</para>
</refsect1>
<!-- Use when ERRORS exist
<refsect1 role="errors">
&reftitle.errors;
<para>
When does this function throw E_* level errors, or exceptions?
</para>
</refsect1>
-->
<!-- Use when a CHANGELOG exists
<refsect1 role="changelog">
&reftitle.changelog;
<para>
<informaltable>
<tgroup cols="2">
<thead>
<row>
<entry>&Version;</entry>
<entry>&Description;</entry>
</row>
</thead>
<tbody>
<row>
<entry>Enter the PHP version of change here</entry>
<entry>Description of change</entry>
</row>
</tbody>
</tgroup>
</informaltable>
</para>
</refsect1>
-->
<!-- Use when examples exist
<refsect1 role="examples">
&reftitle.examples;
<para>
<example>
<title>A <function>stats_cdf_weibull</function> example</title>
<para>
Any text that describes the purpose of the example, or
what goes on in the example should go here (inside the
<example> tag, not out
</para>
<programlisting role="php">
<![CDATA[
<?php
if ($anexample === true) {
echo 'Use the PEAR Coding Standards';
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Use the PEAR Coding Standards
]]>
</screen>
</example>
</para>
</refsect1>
-->
<!-- Use when adding See Also links
<refsect1 role="seealso">
&reftitle.seealso;
<para>
<simplelist>
<member><function></function></member>
<member>Or <link linkend="somethingelse">something else</link></member>
</simplelist>
</para>
</refsect1>
-->
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
| {
"content_hash": "1c8e88f53d07c1c952c0a24487941473",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 84,
"avg_line_length": 21.853658536585368,
"alnum_prop": 0.6434151785714286,
"repo_name": "mziyut/.vim",
"id": "6a707a09a2166a65530d4d35c4c0a886287eee59",
"size": "3584",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "dict/.neocomplete-php/phpdoc/en/reference/stats/functions/stats-cdf-weibull.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2223"
},
{
"name": "Ruby",
"bytes": "939"
},
{
"name": "Shell",
"bytes": "582"
},
{
"name": "Vim script",
"bytes": "22415"
}
],
"symlink_target": ""
} |
Subsets and Splits