text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
<?php
/**
* ZfcUser Configuration
*
* If you have a ./config/autoload/ directory set up for your project, you can
* drop this config file in it and change the values as you wish.
*/
$settings = array(
/**
* Zend\Db\Adapter\Adapter DI Alias
*
* Please specify the DI alias for the configured Zend\Db\Adapter\Adapter
* instance that ZfcUser should use.
*/
//'zend_db_adapter' => 'Zend\Db\Adapter\Adapter',
/**
* User Model Entity Class
*
* Name of Entity class to use. Useful for using your own entity class
* instead of the default one provided. Default is ZfcUser\Entity\User.
* The entity class should implement ZfcUser\Entity\UserInterface
*/
'user_entity_class' => 'RBac\Entity\UserRole',
/**
* Enable registration
*
* Allows users to register through the website.
*
* Accepted values: boolean true or false
*/
//'enable_registration' => true,
/**
* Enable Username
*
* Enables username field on the registration form, and allows users to log
* in using their username OR email address. Default is false.
*
* Accepted values: boolean true or false
*/
'enable_username' => true,
/**
* Authentication Adapters
*
* Specify the adapters that will be used to try and authenticate the user
*
* Default value: array containing 'ZfcUser\Authentication\Adapter\Db' with priority 100
* Accepted values: array containing services that implement 'ZfcUser\Authentication\Adapter\ChainableAdapter'
*/
'auth_adapters' => array( 100 => 'ZfcUser\Authentication\Adapter\Db' ),
/**
* Enable Display Name
*
* Enables a display name field on the registration form, which is persisted
* in the database. Default value is false.
*
* Accepted values: boolean true or false
*/
//'enable_display_name' => true,
/**
* Modes for authentication identity match
*
* Specify the allowable identity modes, in the order they should be
* checked by the Authentication plugin.
*
* Default value: array containing 'email'
* Accepted values: array containing one or more of: email, username
*/
//'auth_identity_fields' => array( 'email' ),
/**
* Login form timeout
*
* Specify the timeout for the CSRF security field of the login form
* in seconds. Default value is 300 seconds.
*
* Accepted values: positive int value
*/
//'login_form_timeout' => 300,
/**
* Registration form timeout
*
* Specify the timeout for the CSRF security field of the registration form
* in seconds. Default value is 300 seconds.
*
* Accepted values: positive int value
*/
//'user_form_timeout' => 300,
/**
* Login After Registration
*
* Automatically logs the user in after they successfully register. Default
* value is false.
*
* Accepted values: boolean true or false
*/
//'login_after_registration' => true,
/**
* Registration Form Captcha
*
* Determines if a captcha should be utilized on the user registration form.
* Default value is false.
*/
//'use_registration_form_captcha' => false,
/**
* Form Captcha Options
*
* Currently used for the registration form, but re-usable anywhere. Use
* this to configure which Zend\Captcha adapter to use, and the options to
* pass to it. The default uses the Figlet captcha.
*/
/*'form_captcha_options' => array(
'class' => 'figlet',
'options' => array(
'wordLen' => 5,
'expiration' => 300,
'timeout' => 300,
),
),*/
/**
* Use Redirect Parameter If Present
*
* Upon successful authentication, check for a 'redirect' POST or GET parameter
*
* Accepted values: boolean true or false
*/
//'use_redirect_parameter_if_present' => true,
/**
* Sets the view template for the user login widget
*
* Default value: 'zfc-user/user/login.phtml'
* Accepted values: string path to a view script
*/
//'user_login_widget_view_template' => 'zfc-user/user/login.phtml',
/**
* Login Redirect Route
*
* Upon successful login the user will be redirected to the entered route
*
* Default value: 'zfcuser'
* Accepted values: A valid route name within your application or a callback.
* If callback used, it will receive the identity as the param
*
*/
//'login_redirect_route' => 'zfcuser',
/**
* Logout Redirect Route
*
* Upon logging out the user will be redirected to the enterd route
*
* Default value: 'zfcuser/login'
* Accepted values: A valid route name within your application
*/
//'logout_redirect_route' => 'zfcuser/login',
/**
* Password Security
*
* DO NOT CHANGE THE PASSWORD HASH SETTINGS FROM THEIR DEFAULTS
* Unless A) you have done sufficient research and fully understand exactly
* what you are changing, AND B) you have a very specific reason to deviate
* from the default settings and know what you're doing.
*
* The password hash settings may be changed at any time without
* invalidating existing user accounts. Existing user passwords will be
* re-hashed automatically on their next successful login.
*/
/**
* Password Cost
*
* The number represents the base-2 logarithm of the iteration count used for
* hashing. Default is 14 (about 10 hashes per second on an i5).
*
* Accepted values: integer between 4 and 31
*/
//'password_cost' => 14,
/**
* Enable user state usage
*
* Should user's state be used in the registration/login process?
*/
//'enable_user_state' => true,
/**
* Default user state upon registration
*
* What state user should have upon registration?
* Allowed value type: integer
*/
//'default_user_state' => 1,
/**
* States which are allowing user to login
*
* When user tries to login, is his/her state one of the following?
* Include null if you want user's with no state to login as well.
* Allowed value types: null and integer
*/
//'allowed_login_states' => array( null, 1 ),
/**
* User table name
*/
//'table_name' => 'user',
/**
* End of ZfcUser configuration
*/
);
/**
* You do not need to edit below this line
*/
return array(
'zfcuser' => $settings,
'service_manager' => array(
'aliases' => array(
'zfcuser_zend_db_adapter' => (isset($settings['zend_db_adapter'])) ? $settings['zend_db_adapter']: 'Zend\Db\Adapter\Adapter',
),
),
);
| {'content_hash': 'd5179c5cd50b2e466b065263ba1ec010', 'timestamp': '', 'source': 'github', 'line_count': 236, 'max_line_length': 137, 'avg_line_length': 29.300847457627118, 'alnum_prop': 0.6117136659436009, 'repo_name': 'julillosamaral/zend_proyect', 'id': 'b954c0ce83d03c48ad926b63a3afadb8ff0a3193', 'size': '6915', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'config/autoload/zfcuser.global.php', 'mode': '33261', 'license': 'bsd-3-clause', 'language': []} |
(function (win, undefined) {
'use strict';
// Promise
// https://gist.github.com/rikschennink/11279384 (fork)
var exports = function Promise() {
this._thens = [];
};
exports.prototype = {
/* This is the "front end" API. */
// then(onResolve, onReject): Code waiting for this promise uses the
// then() method to be notified when the promise is complete. There
// are two completion callbacks: onReject and onResolve. A more
// robust promise implementation will also have an onProgress handler.
then: function (onResolve, onReject) {
// capture calls to then()
this._thens.push({
resolve: onResolve,
reject: onReject
});
},
// Some promise implementations also have a cancel() front end API that
// calls all of the onReject() callbacks (aka a "cancelable promise").
// cancel: function (reason) {},
/* This is the "back end" API. */
// resolve(resolvedValue): The resolve() method is called when a promise
// is resolved (duh). The resolved value (if any) is passed by the resolver
// to this method. All waiting onResolve callbacks are called
// and any future ones are, too, each being passed the resolved value.
resolve: function (val) {
this._complete('resolve', val);
},
// reject(exception): The reject() method is called when a promise cannot
// be resolved. Typically, you'd pass an exception as the single parameter,
// but any other argument, including none at all, is acceptable.
// All waiting and all future onReject callbacks are called when reject()
// is called and are passed the exception parameter.
reject: function (ex) {
this._complete('reject', ex);
},
// Some promises may have a progress handler. The back end API to signal a
// progress "event" has a single parameter. The contents of this parameter
// could be just about anything and is specific to your implementation.
// progress: function (data) {},
/* "Private" methods. */
_complete: function (which, arg) {
// switch over to sync then()
/* jshint unused:false*/
this.then = which === 'resolve' ?
function (resolve, reject) {
resolve(arg);
} : function (resolve, reject) {
reject(arg);
};
// disallow multiple calls to resolve or reject
this.resolve = this.reject =
function () {
throw new Error('Promise already completed.');
};
// complete all waiting (async) then()s
var aThen;
var i = 0; /* jshint -W084 */
/* jshint -W030 */
while (aThen = this._thens[i++]) {
aThen[which] && aThen[which](arg);
}
delete this._thens;
}
};
// CommonJS
if (typeof module !== 'undefined' && module.exports) {
module.exports = exports;
}
// AMD
else if (typeof define === 'function' && define.amd) {
define(function () {
return exports;
});
}
// Browser globals
else {
win.Promise = exports;
}
}(this)); | {'content_hash': '10b84a36bed187240ea92ee085929c14', 'timestamp': '', 'source': 'github', 'line_count': 97, 'max_line_length': 83, 'avg_line_length': 35.134020618556704, 'alnum_prop': 0.5531103286384976, 'repo_name': 'ericweerstra/frontend-bootstrap', 'id': 'c7c6d9eba9f520bc7b07928c4f25a8a3ea75251e', 'size': '3408', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/static/js/vendor/conditionerjs/utils/Promise.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '1267'}, {'name': 'HTML', 'bytes': '1703'}, {'name': 'JavaScript', 'bytes': '11488'}, {'name': 'Shell', 'bytes': '3573'}]} |
'use strict';
/*
* ngcode
* https://github.com/silverbux/ngcode
* AngularJS Code Generator
*/
var path = require('path')
, utils = require(path.resolve(path.join(__dirname, 'utils')))
, _ = require('lodash')
, fs = require('fs')
, program = require('commander');
function NgCode(arg) {
this.init(arg);
};
NgCode.prototype.init = function (arg) {
var title = arg.title;
this.method = arg.method;
this.showmessage = arg.showmessage
this.title = {
orig : title,
cap : _.capitalize(title),
low : title.toLowerCase(),
camel : _.camelCase(title)
}
this.generate()
};
NgCode.prototype.generate = function () {
var method = this.method
, title = this.title
, showmessage = this.showmessage
, path = title.low + '.' + method + '.js'
, writeFile = this.write
this.getTemplate(function (data) {
var compiled = _.template(data);
data = compiled({'title': title});
writeFile(path, data, function (data) {
if ( showmessage ) {
utils.doneGenerateMessage(path)
}
})
})
};
NgCode.prototype.getTemplate = function (cb) {
var method = this.method;
var tplPath = path.join(__dirname, '../templates', method + '.txt')
fs.exists(tplPath, function (exists) {
if (exists) {
fs.readFile(tplPath, 'utf-8', function (err, data) {
if (err) throw err;
return cb(data)
});
} else {
utils.error('Unknown Command: ' + method);
}
});
};
NgCode.prototype.write = function (path, data, cb) {
fs.exists(path, function (exists) {
if (exists) {
utils.error(path + ' already exists. ')
} else {
fs.writeFile(path, data, function (err) {
if (err) throw err;
return cb('success')
})
}
});
};
program
.version('0.0.9')
.arguments('<cmd>')
.action(function (cmd, env) {
var _command = cmd.split(':');
var cmd = _.first(_command);
var title = _.last(_command);
switch (cmd) {
case 'con':
cmd = 'controller';
break;
case 'dir':
cmd = 'directive';
break;
case 'fac':
cmd = 'factory';
break;
case 'fil':
cmd = 'filter';
break;
case 'mod':
cmd = 'module';
break;
case 'ser':
cmd = 'service';
break;
}
var arg = {
method: cmd,
title: title,
showmessage: true,
}
new NgCode(arg);
})
program.on('--help', function () {
console.log(' Examples:');
console.log(' ');
console.log(' Directives');
console.log(' ngcode directive:helloworld');
console.log(' ');
console.log(' Controllers');
console.log(' ngcode controller:helloworld');
console.log(' ');
console.log(' Factory');
console.log(' ngcode factory:helloworld');
console.log(' ');
console.log(' Filter');
console.log(' ngcode filter:helloworld');
console.log(' ');
console.log(' Module');
console.log(' ngcode module:helloworld');
console.log(' ');
console.log(' Service');
console.log(' ngcode service:helloworld');
console.log('');
});
program.parse(process.argv);
module.exports = NgCode | {'content_hash': 'd168f44b58d9ccb8b894ed78fc9b0dee', 'timestamp': '', 'source': 'github', 'line_count': 145, 'max_line_length': 69, 'avg_line_length': 22.117241379310343, 'alnum_prop': 0.561895852821952, 'repo_name': 'silverbux/ngcode', 'id': '41582a537859a61de5b90a4566751487d8f5547b', 'size': '3207', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/main.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '10372'}]} |
// @formatter:off
package com.microsoft.alm.teamfoundation.workitemtracking.webapi.models;
import java.util.ArrayList;
import java.util.Date;
/**
*/
public class WorkItemQueryResult {
private Date asOf;
private ArrayList<WorkItemFieldReference> columns;
private QueryResultType queryResultType;
private QueryType queryType;
private ArrayList<WorkItemQuerySortColumn> sortColumns;
private ArrayList<WorkItemLink> workItemRelations;
private ArrayList<WorkItemReference> workItems;
public Date getAsOf() {
return asOf;
}
public void setAsOf(final Date asOf) {
this.asOf = asOf;
}
public ArrayList<WorkItemFieldReference> getColumns() {
return columns;
}
public void setColumns(final ArrayList<WorkItemFieldReference> columns) {
this.columns = columns;
}
public QueryResultType getQueryResultType() {
return queryResultType;
}
public void setQueryResultType(final QueryResultType queryResultType) {
this.queryResultType = queryResultType;
}
public QueryType getQueryType() {
return queryType;
}
public void setQueryType(final QueryType queryType) {
this.queryType = queryType;
}
public ArrayList<WorkItemQuerySortColumn> getSortColumns() {
return sortColumns;
}
public void setSortColumns(final ArrayList<WorkItemQuerySortColumn> sortColumns) {
this.sortColumns = sortColumns;
}
public ArrayList<WorkItemLink> getWorkItemRelations() {
return workItemRelations;
}
public void setWorkItemRelations(final ArrayList<WorkItemLink> workItemRelations) {
this.workItemRelations = workItemRelations;
}
public ArrayList<WorkItemReference> getWorkItems() {
return workItems;
}
public void setWorkItems(final ArrayList<WorkItemReference> workItems) {
this.workItems = workItems;
}
}
| {'content_hash': 'a0617b70715346c818e1055a1e4a27b2', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 87, 'avg_line_length': 25.526315789473685, 'alnum_prop': 0.7077319587628866, 'repo_name': 'Microsoft/vso-httpclient-java', 'id': '146cf1afc8a703be2ec8eef769f1a75cc2287be6', 'size': '2477', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/workitemtracking/webapi/models/WorkItemQueryResult.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '760'}, {'name': 'Java', 'bytes': '4771131'}]} |
package com.adobe.internal.fxg.dom.types;
/**
* The LigatureLevel class.
*
* Controls which
* ligatures in the font will be used. Minimum turns on rlig, common is
* rlig + clig + liga, uncommon is rlig + clig + liga + dlig, exotic is
* rlig + clig + liga + dlig + hlig. There is no way to turn the various
* ligature features on independently. Default is "common". </li>
* <li><b>locale</b> (String): The locale of the text. Controls case
* transformations and shaping. Standard locale identifiers as described
* in Unicode Technical Standard #35 are used. For example en,
* en_US and en-US are all English, ja is Japanese. Locale applied at
* the paragraph and higher level impacts resolution of "auto" values
* for dominantBaseline, justificationRule, justificationStyle and
* leadingModel.
*
* <pre>
* 0 = minimum
* 1 = common
* 2 = uncommon
* 3 = exotic
* </pre>
*
*/
public enum LigatureLevel
{
/**
* The enum representing an 'minimum' LigatureLevel.
*/
MINIMUM,
/**
* The enum representing an 'common' LigatureLevel.
*/
COMMON,
/**
* The enum representing an 'uncommon' LigatureLevel.
*/
UNCOMMON,
/**
* The enum representing an 'exotic' LigatureLevel.
*/
EXOTIC;
}
| {'content_hash': '66d6ed2f623dd5712d5357e32dd4d00c', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 73, 'avg_line_length': 26.12, 'alnum_prop': 0.6454823889739663, 'repo_name': 'apache/flex-sdk', 'id': '0616bac009bfb877506bd8b21fea8d19a69ef7f4', 'size': '2125', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'modules/fxgutils/src/java/com/adobe/internal/fxg/dom/types/LigatureLevel.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AGS Script', 'bytes': '478'}, {'name': 'ASP', 'bytes': '6381'}, {'name': 'ActionScript', 'bytes': '34795676'}, {'name': 'AngelScript', 'bytes': '477651'}, {'name': 'Awk', 'bytes': '1958'}, {'name': 'Batchfile', 'bytes': '40336'}, {'name': 'C', 'bytes': '2845'}, {'name': 'C++', 'bytes': '12015'}, {'name': 'CSS', 'bytes': '508448'}, {'name': 'HTML', 'bytes': '84174'}, {'name': 'Java', 'bytes': '15078807'}, {'name': 'JavaScript', 'bytes': '109405'}, {'name': 'PureBasic', 'bytes': '362'}, {'name': 'Roff', 'bytes': '59633'}, {'name': 'Shell', 'bytes': '308605'}, {'name': 'Visual Basic', 'bytes': '4498'}, {'name': 'XSLT', 'bytes': '757371'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Sun Mar 17 11:03:31 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>PropertyConsumer (BOM: * : All 2.4.0.Final API)</title>
<meta name="date" content="2019-03-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="PropertyConsumer (BOM: * : All 2.4.0.Final API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":18};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],16:["t5","Default Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/PropertyConsumer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.4.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/wildfly/swarm/config/management/Property.html" title="class in org.wildfly.swarm.config.management"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/wildfly/swarm/config/management/PropertySupplier.html" title="interface in org.wildfly.swarm.config.management"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/management/PropertyConsumer.html" target="_top">Frames</a></li>
<li><a href="PropertyConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.wildfly.swarm.config.management</div>
<h2 title="Interface PropertyConsumer" class="title">Interface PropertyConsumer<T extends <a href="../../../../../org/wildfly/swarm/config/management/Property.html" title="class in org.wildfly.swarm.config.management">Property</a><T>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Functional Interface:</dt>
<dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd>
</dl>
<hr>
<br>
<pre><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a>
public interface <span class="typeNameLabel">PropertyConsumer<T extends <a href="../../../../../org/wildfly/swarm/config/management/Property.html" title="class in org.wildfly.swarm.config.management">Property</a><T>></span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html#accept-T-">accept</a></span>(<a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html" title="type parameter in PropertyConsumer">T</a> value)</code>
<div class="block">Configure a pre-constructed instance of Property resource</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>default <a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html" title="interface in org.wildfly.swarm.config.management">PropertyConsumer</a><<a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html" title="type parameter in PropertyConsumer">T</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html#andThen-org.wildfly.swarm.config.management.PropertyConsumer-">andThen</a></span>(<a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html" title="interface in org.wildfly.swarm.config.management">PropertyConsumer</a><<a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html" title="type parameter in PropertyConsumer">T</a>> after)</code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="accept-org.wildfly.swarm.config.management.Property-">
<!-- -->
</a><a name="accept-T-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>accept</h4>
<pre>void accept(<a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html" title="type parameter in PropertyConsumer">T</a> value)</pre>
<div class="block">Configure a pre-constructed instance of Property resource</div>
</li>
</ul>
<a name="andThen-org.wildfly.swarm.config.management.PropertyConsumer-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>andThen</h4>
<pre>default <a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html" title="interface in org.wildfly.swarm.config.management">PropertyConsumer</a><<a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html" title="type parameter in PropertyConsumer">T</a>> andThen(<a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html" title="interface in org.wildfly.swarm.config.management">PropertyConsumer</a><<a href="../../../../../org/wildfly/swarm/config/management/PropertyConsumer.html" title="type parameter in PropertyConsumer">T</a>> after)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/PropertyConsumer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.4.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/wildfly/swarm/config/management/Property.html" title="class in org.wildfly.swarm.config.management"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/wildfly/swarm/config/management/PropertySupplier.html" title="interface in org.wildfly.swarm.config.management"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/management/PropertyConsumer.html" target="_top">Frames</a></li>
<li><a href="PropertyConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {'content_hash': '365879f4cbfd28810819b76028d8f4d0', 'timestamp': '', 'source': 'github', 'line_count': 248, 'max_line_length': 648, 'avg_line_length': 45.108870967741936, 'alnum_prop': 0.6537945829981229, 'repo_name': 'wildfly-swarm/wildfly-swarm-javadocs', 'id': 'db30068861178cf8b6a18dd4595bbf1abe8c7c0c', 'size': '11187', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': '2.4.0.Final/apidocs/org/wildfly/swarm/config/management/PropertyConsumer.html', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
from nipype.testing import assert_equal
from nipype.interfaces.fsl.maths import MeanImage
def test_MeanImage_inputs():
input_map = dict(args=dict(argstr='%s',
),
dimension=dict(argstr='-%smean',
position=4,
usedefault=True,
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
in_file=dict(argstr='%s',
mandatory=True,
position=2,
),
internal_datatype=dict(argstr='-dt %s',
position=1,
),
nan2zeros=dict(argstr='-nan',
position=3,
),
out_file=dict(argstr='%s',
genfile=True,
hash_files=False,
position=-2,
),
output_datatype=dict(argstr='-odt %s',
position=-1,
),
output_type=dict(),
terminal_output=dict(mandatory=True,
nohash=True,
),
)
inputs = MeanImage.input_spec()
for key, metadata in input_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def test_MeanImage_outputs():
output_map = dict(out_file=dict(),
)
outputs = MeanImage.output_spec()
for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value
| {'content_hash': '3972f4217c4b25eb1d0e49cb6951bed0', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 78, 'avg_line_length': 24.555555555555557, 'alnum_prop': 0.6184012066365008, 'repo_name': 'dmordom/nipype', 'id': 'f297cdcc5530e9ad2daff0793312d293f2e72f6a', 'size': '1380', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'nipype/interfaces/fsl/tests/test_auto_MeanImage.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '9090'}, {'name': 'Matlab', 'bytes': '5018'}, {'name': 'Python', 'bytes': '3854524'}, {'name': 'Shell', 'bytes': '2959'}, {'name': 'Tcl', 'bytes': '43408'}]} |
import java.util.*;
class ram
{
public static void main(String args[])
{
Scanner S = new Scanner(System.in);
int a,b;
System.out.println("enter a and b " );
a = S.nextInt();
b = S.nextInt();
int c = a +b;
System.out.println(c);
}
} | {'content_hash': 'ad2494da8b0796e6ac17cf9cf959af34', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 39, 'avg_line_length': 18.571428571428573, 'alnum_prop': 0.5769230769230769, 'repo_name': 'abhishek-anand13/java-on-the-web', 'id': '5ffdd3d54477b2b0252b771bd43fe8ec758ba52b', 'size': '260', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'users/BETN1CS13004/ram.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '5387'}, {'name': 'Java', 'bytes': '10189'}, {'name': 'PHP', 'bytes': '8414'}]} |
/* *\
** Squants **
** **
** Scala Quantities and Units of Measure Library and DSL **
** (c) 2013-2015, Gary Keorkunian **
** **
\* */
package squants.experimental
import scala.util.{ Failure, Success, Try }
/**
* Represents a Dimension or Quantity Type
*
* This trait should be mixed into the Companion Objects of specific Quantity Types.
*
* @tparam A Quantity Type
*/
trait Dimension[A <: Quantity[A, _]] {
/**
* The name
* @return
*/
def name: String
/**
* Set of available units
* @return
*/
def units: Set[UnitOfMeasure[A]]
/**
* The unit with a conversions factor of 1.
* The conversionFactor for other units should be set relative to this unit.
* @return
*/
def primaryUnit: UnitOfMeasure[A] with PrimaryUnit
/**
* The International System of Units (SI) Base Unit
* @return
*/
def siUnit: UnitOfMeasure[A] with SiUnit
/**
* Maps a string representation of a unit symbol into the matching UnitOfMeasure object
* @param symbol String
* @return
*/
def symbolToUnit(symbol: String): Option[UnitOfMeasure[A]] = units.find(u ⇒ u.symbol == symbol)
/**
* Tries to map a string or tuple value to Quantity of this Dimension
* @param value the source string (ie, "10 kW") or tuple (ie, (10, "kW"))
* @return Try[A]
*/
protected def parse(value: Any) = value match {
case s: String ⇒ parseString(s)
case (v: BigDecimal, u: String) ⇒ parseTuple(v, u)
case (v: Double, u: String) ⇒ parseTuple(v, u)
case (v: Float, u: String) ⇒ parseTuple(v, u)
case (v: Long, u: String) ⇒ parseTuple(v, u)
case (v: Int, u: String) ⇒ parseTuple(v, u)
}
private def parseString(s: String): Try[Quantity[A, BigDecimal]] = {
s match {
case QuantityString(value, symbol) ⇒ Success(symbolToUnit(symbol).get(BigDecimal(value)))
case _ ⇒ Failure(QuantityParseException(s"Unable to parse $name", s))
}
}
private lazy val QuantityString = ("^([-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?) *(" + units.map { u: UnitOfMeasure[A] ⇒ u.symbol }.reduceLeft(_ + "|" + _) + ")$").r
private def parseTuple[N : SquantsNumeric](value: N, symbol: String): Try[Quantity[A, N]] = {
symbolToUnit(symbol) match {
case Some(unit) ⇒ Success(unit(value))
case None ⇒ Failure(QuantityParseException(s"Unable to identify $name unit $symbol", (value, symbol).toString()))
}
}
}
case class QuantityParseException(message: String, expression: String) extends Exception
/**
* SI Base Quantity
*/
trait BaseDimension { self: Dimension[_] ⇒
/**
* SI Base Unit for this Quantity
* @return
*/
def siUnit: SiBaseUnit
/**
* SI Dimension Symbol
* @return
*/
def dimensionSymbol: String
}
| {'content_hash': '11cef140e763756e01f0de3b82850800', 'timestamp': '', 'source': 'github', 'line_count': 100, 'max_line_length': 167, 'avg_line_length': 31.68, 'alnum_prop': 0.5467171717171717, 'repo_name': 'underscorenico/squants', 'id': '02c02cb4813a3faecd722c80e7f0939c8f9f7bbc', 'size': '3194', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'shared/src/test/scala/squants/experimental/Dimension.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Scala', 'bytes': '818513'}]} |
require 'spec_helper'
describe 'as a client' do
let!(:client) { create_client }
it "should display services information" do
expect(client.services.all).to contain_exactly(client.metadata)
end
end
| {'content_hash': 'd4fd8196096c64b26a790a3cab25cf67', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 67, 'avg_line_length': 23.11111111111111, 'alnum_prop': 0.7307692307692307, 'repo_name': 'engineyard/core-client-rb', 'id': '881209250ed0c89be0c995f95bea500d4de2b234', 'size': '208', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/services_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Gherkin', 'bytes': '7158'}, {'name': 'Ruby', 'bytes': '582533'}]} |
This directory contains Cargo's documentation. There are two parts, [The Cargo Book]
which is built with [mdbook] and the man pages, which are built with [Asciidoctor].
The man pages are also included in The Cargo Book as HTML.
[The Cargo Book]: https://doc.rust-lang.org/cargo/
### Building the book
Building the book requires [mdBook]. To get it:
[mdBook]: https://github.com/rust-lang/mdBook
```console
$ cargo install mdbook
```
To build the book:
```console
$ mdbook build
```
`mdbook` provides a variety of different commands and options to help you work
on the book:
* `mdbook build --open`: Build the book and open it in a web browser.
* `mdbook serve`: Launches a web server on localhost. It also automatically
rebuilds the book whenever any file changes and automatically reloads your
web browser.
The book contents are driven by the [`SUMMARY.md`](src/SUMMARY.md) file, and
every file must be linked there.
### Building the man pages
Building the man pages requires [Asciidoctor]. See the linked page for
installation instructions. It also requires the `make` build tool and `ruby`.
[Asciidoctor]: https://asciidoctor.org/
The source files are located in the [`src/doc/man`](man) directory. The
[`Makefile`](Makefile) is used to rebuild the man pages. It outputs the man
pages into [`src/etc/man`](../etc/man) and the HTML versions into
[`src/doc/man/generated`](man/generated). The Cargo Book has some markdown
stub files in [`src/doc/src/commands`](src/commands) which load the generated
HTML files.
To build the man pages, run `make` in the `src/doc` directory:
```console
$ make
```
The build script uses a few Asciidoctor extensions. See
[`asciidoc-extension.rb`](asciidoc-extension.rb) for details.
## Contributing
We'd love your help with improving the documentation! Please feel free to
[open issues](https://github.com/rust-lang/cargo/issues) about anything, and
send in PRs for things you'd like to fix or change. If your change is large,
please open an issue first, so we can make sure that it's something we'd
accept before you go through the work of getting a PR together.
| {'content_hash': '100f1fc73834f0eb3482b5ddbb54d2d6', 'timestamp': '', 'source': 'github', 'line_count': 63, 'max_line_length': 84, 'avg_line_length': 33.65079365079365, 'alnum_prop': 0.7495283018867924, 'repo_name': 'vojtechkral/cargo', 'id': '85da35bc84f0bbe226e507e45ac4a77055205efa', 'size': '2143', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/doc/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '10421'}, {'name': 'HTML', 'bytes': '2473'}, {'name': 'JavaScript', 'bytes': '1276'}, {'name': 'Makefile', 'bytes': '14196'}, {'name': 'Roff', 'bytes': '45462'}, {'name': 'Rust', 'bytes': '1798516'}, {'name': 'Shell', 'bytes': '9966'}]} |
#pragma once
void CheckSuitability();
void StartIpcCommunication(TCHAR* lpCmdLine);
void ReceiveIpcData();
void PrepareForLaunching();
void CreateTargetProcess();
void FinishIpcCommunication();
void ResumeAndWaitForTargetProcess();
| {'content_hash': '745889f44198e78707b5eb1142e0873c', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 45, 'avg_line_length': 13.444444444444445, 'alnum_prop': 0.7933884297520661, 'repo_name': 'J-A-B-R/Console-Utilities', 'id': '98e8631f0462c73a2135a136a467c5212ab28b50', 'size': '845', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Elevate Stub/Process.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '65124'}, {'name': 'C++', 'bytes': '2848'}, {'name': 'Objective-C', 'bytes': '2375'}]} |
layout: page
title: Seattle Police Officer 5606 Novella V. Fraser
permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/5606/
---
**Age as of Feb. 24, 2016:** 53
| {'content_hash': '2fcaad322e34fe6f699530fa57aebc8b', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 88, 'avg_line_length': 32.0, 'alnum_prop': 0.7604166666666666, 'repo_name': 'seattlepublicrecords/seattlepublicrecords.github.io', 'id': '23c51268b8a692ac9a74dd6b0a7d07840640c914', 'size': '196', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'information/agencies/city_of_seattle/seattle_police_department/copbook/5606/index.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '14496'}, {'name': 'HTML', 'bytes': '14591'}, {'name': 'JavaScript', 'bytes': '5297'}, {'name': 'Ruby', 'bytes': '964'}]} |
~~~~~~~~~~~~~~~~~~~~~~
Model description
~~~~~~~~~~~~~~~~~~~~~~
Wind power plants
=================
The windpowerlib provides three classes for modelling wind power as wind turbines (:py:class:`~.wind_turbine.WindTurbine`),
wind farms (:py:class:`~.wind_farm.WindFarm`) and wind turbine clusters (:py:class:`~.wind_turbine_cluster.WindTurbineCluster`).
Descriptions can also be found in the sections
:ref:`wind_turbine_label`, :ref:`wind_farm_label` and :ref:`wind_turbine_cluster_label`.
Height correction and conversion of weather data
================================================
Weather data is usually available for a restricted amount of heights above ground.
However, for wind feed-in time series calculations weather data is needed at hub
height of the examined wind turbines. Thus, the windpowerlib provides functions for the height
correction of weather data.
Functions for the height correction of wind speed to the hub height of a wind turbine are described in the
:ref:`windspeedmodule-label` module. Respectively a function for the height correction of temperature data is provided in the
:ref:`temperature_module_label` module. Functions for density calculations can be found in the
:ref:`density_module_label` module.
If weather data is available for at least two different heights the respective figure at hub height
can be determined by using linear or logarithmic inter-/extrapolation functions of the :ref:`tools_module_label` module.
Power output calculations
=========================
Wind feed-in time series can be calculated via power curves and power coefficient curves in the windpowerlib.
Functions for power output calculations are described in the :ref:`poweroutput_module_label` module.
Wake losses
===========
The windpowerlib provides two options for the consideration of wake losses in wind farms:
reduction of wind speeds and wind farm efficiency (reduction of power in power curves).
For the first option wind efficiency curves are provided which determine the
average reduction of wind speeds within a wind farm induced by wake losses depending on the wind speed. These curves
were taken from the dena-Netzstudie II and the dissertation of Kaspar Knorr
(for references see :py:func:`~.get_wind_efficiency_curve`).
The following graph shows all provided wind efficiency curves. The mean wind efficiency curves were calculated in
the dena-Netzstudie II and by Kaspar Knorr by averaging wind efficiency curves of 12 wind farms distributed over Germany (dena) or
respectively of over 2000 wind farms in Germany (Knorr). Curves with the appendix 'extreme'
are wind efficiency curves of single wind farms that are extremely deviating from the respective
mean wind efficiency curve.
.. image:: _files/wind_efficiency_curves.svg
:scale: 99 %
:alt: Wind efficiency curves
:align: center
The second option to consider wake losses is to apply them to power curves by reducing the power values
by a constant or on a wind speed depending wind farm efficiency (see :py:func:`~.wake_losses_to_power_curve`).
Applying the wind farm efficiency (curve) to power curves instead of feed-in time series has the advantage that the
power curves can further be aggregated to obtain turbine cluster power curves (see :py:class:`~.wind_turbine_cluster.WindTurbineCluster`).
Smoothing of power curves
=========================
To account for the spatial distribution of wind speeds within an area the windpowerlib provides a
function for power curve smoothing and uses the approach of Nørgaard and Holttinen (for references see :py:func:`~.smooth_power_curve`).
The modelchains
===============
The modelchains are implemented to ensure an easy start into the Windpowerlib. They work
like models that combine all functions provided in the library. Via parameteres desired functions
of the windpowerlib can be selected. For parameters not being specified default parameters are used.
The :ref:`modelchain_module_label` is a model
to determine the output of a wind turbine while the :ref:`tc_modelchain_module_label` is a model to determine
the output of a wind farm or wind turbine cluster.
The usage of both modelchains is shown in the :ref:`examples_section_label` section.
| {'content_hash': '53fc88d52b8ad5d23bf9d2909dc55e9b', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 138, 'avg_line_length': 54.06410256410256, 'alnum_prop': 0.7661844913445578, 'repo_name': 'wind-python/windpowerlib', 'id': '6a0f70be9d0ec07a04f0d08aac10209b314f3416', 'size': '4218', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev', 'path': 'doc/model_description.rst', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Jupyter Notebook', 'bytes': '181328'}, {'name': 'Python', 'bytes': '251227'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>poe4j-gui</artifactId>
<parent>
<groupId>com.swandiggy</groupId>
<artifactId>poe4j-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.github.github</groupId>
<artifactId>site-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.logback-extensions</groupId>
<artifactId>logback-ext-spring</artifactId>
<version>0.1.4</version>
</dependency>
<dependency>
<groupId>com.swandiggy</groupId>
<artifactId>poe4j</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
</project> | {'content_hash': '61b12b12f42c6e1516e1c396b3176867', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 108, 'avg_line_length': 33.442622950819676, 'alnum_prop': 0.5647058823529412, 'repo_name': 'Jacob-Swanson/poe4j', 'id': '89f7848114ceff1da0bbaf89bcc3886c26f0d1fa', 'size': '2040', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'poe4j-gui/pom.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '568'}, {'name': 'HTML', 'bytes': '8273'}, {'name': 'Java', 'bytes': '316355'}, {'name': 'JavaScript', 'bytes': '11908'}]} |
"""
Routines for configuring Glance
"""
import logging
import logging.config
import logging.handlers
import os
import tempfile
from oslo_concurrency import lockutils
from oslo_config import cfg
from oslo_policy import policy
from paste import deploy
from glance import i18n
from glance.version import version_info as version
_ = i18n._
paste_deploy_opts = [
cfg.StrOpt('flavor',
help=_('Partial name of a pipeline in your paste configuration '
'file with the service name removed. For example, if '
'your paste section name is '
'[pipeline:glance-api-keystone] use the value '
'"keystone"')),
cfg.StrOpt('config_file',
help=_('Name of the paste configuration file.')),
]
image_format_opts = [
cfg.ListOpt('container_formats',
default=['ami', 'ari', 'aki', 'bare', 'ovf', 'ova'],
help=_("Supported values for the 'container_format' "
"image attribute"),
deprecated_opts=[cfg.DeprecatedOpt('container_formats',
group='DEFAULT')]),
cfg.ListOpt('disk_formats',
default=['ami', 'ari', 'aki', 'vhd', 'vmdk', 'raw', 'qcow2',
'vdi', 'iso'],
help=_("Supported values for the 'disk_format' "
"image attribute"),
deprecated_opts=[cfg.DeprecatedOpt('disk_formats',
group='DEFAULT')]),
]
task_opts = [
cfg.IntOpt('task_time_to_live',
default=48,
help=_("Time in hours for which a task lives after, either "
"succeeding or failing"),
deprecated_opts=[cfg.DeprecatedOpt('task_time_to_live',
group='DEFAULT')]),
cfg.StrOpt('task_executor',
default='taskflow',
help=_("Specifies which task executor to be used to run the "
"task scripts.")),
cfg.StrOpt('work_dir',
default=None,
help=_('Work dir for asynchronous task operations. '
'The directory set here will be used to operate over '
'images - normally before they are imported in the '
'destination store. When providing work dir, make sure '
'enough space is provided for concurrent tasks to run '
'efficiently without running out of space. A rough '
'estimation can be done by multiplying the number of '
'`max_workers` - or the N of workers running - by an '
'average image size (e.g 500MB). The image size '
'estimation should be done based on the average size in '
'your deployment. Note that depending on the tasks '
'running you may need to multiply this number by some '
'factor depending on what the task does. For example, '
'you may want to double the available size if image '
'conversion is enabled. All this being said, remember '
'these are just estimations and you should do them '
'based on the worst case scenario and be prepared to '
'act in case they were wrong.')),
]
common_opts = [
cfg.BoolOpt('allow_additional_image_properties', default=True,
help=_('Whether to allow users to specify image properties '
'beyond what the image schema provides')),
cfg.IntOpt('image_member_quota', default=128,
help=_('Maximum number of image members per image. '
'Negative values evaluate to unlimited.')),
cfg.IntOpt('image_property_quota', default=128,
help=_('Maximum number of properties allowed on an image. '
'Negative values evaluate to unlimited.')),
cfg.IntOpt('image_tag_quota', default=128,
help=_('Maximum number of tags allowed on an image. '
'Negative values evaluate to unlimited.')),
cfg.IntOpt('image_location_quota', default=10,
help=_('Maximum number of locations allowed on an image. '
'Negative values evaluate to unlimited.')),
cfg.StrOpt('data_api', default='glance.db.sqlalchemy.api',
help=_('Python module path of data access API')),
cfg.IntOpt('limit_param_default', default=25,
help=_('Default value for the number of items returned by a '
'request if not specified explicitly in the request')),
cfg.IntOpt('api_limit_max', default=1000,
help=_('Maximum permissible number of items that could be '
'returned by a request')),
cfg.BoolOpt('show_image_direct_url', default=False,
help=_('Whether to include the backend image storage location '
'in image properties. Revealing storage location can '
'be a security risk, so use this setting with '
'caution!')),
cfg.BoolOpt('show_multiple_locations', default=False,
help=_('Whether to include the backend image locations '
'in image properties. '
'For example, if using the file system store a URL of '
'"file:///path/to/image" will be returned to the user '
'in the \'direct_url\' meta-data field. '
'Revealing storage location can '
'be a security risk, so use this setting with '
'caution! The overrides show_image_direct_url.')),
cfg.IntOpt('image_size_cap', default=1099511627776,
help=_("Maximum size of image a user can upload in bytes. "
"Defaults to 1099511627776 bytes (1 TB)."
"WARNING: this value should only be increased after "
"careful consideration and must be set to a value under "
"8 EB (9223372036854775808).")),
cfg.StrOpt('user_storage_quota', default='0',
help=_("Set a system wide quota for every user. This value is "
"the total capacity that a user can use across "
"all storage systems. A value of 0 means unlimited."
"Optional unit can be specified for the value. Accepted "
"units are B, KB, MB, GB and TB representing "
"Bytes, KiloBytes, MegaBytes, GigaBytes and TeraBytes "
"respectively. If no unit is specified then Bytes is "
"assumed. Note that there should not be any space "
"between value and unit and units are case sensitive.")),
cfg.BoolOpt('enable_v1_api', default=True,
help=_("Deploy the v1 OpenStack Images API.")),
cfg.BoolOpt('enable_v2_api', default=True,
help=_("Deploy the v2 OpenStack Images API.")),
cfg.BoolOpt('enable_v1_registry', default=True,
help=_("Deploy the v1 OpenStack Registry API.")),
cfg.BoolOpt('enable_v2_registry', default=True,
help=_("Deploy the v2 OpenStack Registry API.")),
cfg.StrOpt('pydev_worker_debug_host',
help=_('The hostname/IP of the pydev process listening for '
'debug connections')),
cfg.IntOpt('pydev_worker_debug_port', default=5678,
help=_('The port on which a pydev process is listening for '
'connections.')),
cfg.StrOpt('metadata_encryption_key', secret=True,
help=_('AES key for encrypting store \'location\' metadata. '
'This includes, if used, Swift or S3 credentials. '
'Should be set to a random string of length 16, 24 or '
'32 bytes')),
cfg.StrOpt('digest_algorithm', default='sha1',
help=_('Digest algorithm which will be used for digital '
'signature; the default is sha1 the default in Kilo '
'for a smooth upgrade process, and it will be updated '
'with sha256 in next release(L). Use the command '
'"openssl list-message-digest-algorithms" to get the '
'available algorithms supported by the version of '
'OpenSSL on the platform. Examples are "sha1", '
'"sha256", "sha512", etc.')),
]
CONF = cfg.CONF
CONF.register_opts(paste_deploy_opts, group='paste_deploy')
CONF.register_opts(image_format_opts, group='image_format')
CONF.register_opts(task_opts, group='task')
CONF.register_opts(common_opts)
policy.Enforcer(CONF)
def parse_args(args=None, usage=None, default_config_files=None):
if "OSLO_LOCK_PATH" not in os.environ:
lockutils.set_defaults(tempfile.gettempdir())
CONF(args=args,
project='glance',
version=version.cached_version_string(),
usage=usage,
default_config_files=default_config_files)
def parse_cache_args(args=None):
config_files = cfg.find_config_files(project='glance', prog='glance-cache')
parse_args(args=args, default_config_files=config_files)
def _get_deployment_flavor(flavor=None):
"""
Retrieve the paste_deploy.flavor config item, formatted appropriately
for appending to the application name.
:param flavor: if specified, use this setting rather than the
paste_deploy.flavor configuration setting
"""
if not flavor:
flavor = CONF.paste_deploy.flavor
return '' if not flavor else ('-' + flavor)
def _get_paste_config_path():
paste_suffix = '-paste.ini'
conf_suffix = '.conf'
if CONF.config_file:
# Assume paste config is in a paste.ini file corresponding
# to the last config file
path = CONF.config_file[-1].replace(conf_suffix, paste_suffix)
else:
path = CONF.prog + paste_suffix
return CONF.find_file(os.path.basename(path))
def _get_deployment_config_file():
"""
Retrieve the deployment_config_file config item, formatted as an
absolute pathname.
"""
path = CONF.paste_deploy.config_file
if not path:
path = _get_paste_config_path()
if not path:
msg = _("Unable to locate paste config file for %s.") % CONF.prog
raise RuntimeError(msg)
return os.path.abspath(path)
def load_paste_app(app_name, flavor=None, conf_file=None):
"""
Builds and returns a WSGI app from a paste config file.
We assume the last config file specified in the supplied ConfigOpts
object is the paste config file, if conf_file is None.
:param app_name: name of the application to load
:param flavor: name of the variant of the application to load
:param conf_file: path to the paste config file
:raises RuntimeError when config file cannot be located or application
cannot be loaded from config file
"""
# append the deployment flavor to the application name,
# in order to identify the appropriate paste pipeline
app_name += _get_deployment_flavor(flavor)
if not conf_file:
conf_file = _get_deployment_config_file()
try:
logger = logging.getLogger(__name__)
logger.debug("Loading %(app_name)s from %(conf_file)s",
{'conf_file': conf_file, 'app_name': app_name})
app = deploy.loadapp("config:%s" % conf_file, name=app_name)
# Log the options used when starting if we're in debug mode...
if CONF.debug:
CONF.log_opt_values(logger, logging.DEBUG)
return app
except (LookupError, ImportError) as e:
msg = (_("Unable to load %(app_name)s from "
"configuration file %(conf_file)s."
"\nGot: %(e)r") % {'app_name': app_name,
'conf_file': conf_file,
'e': e})
logger.error(msg)
raise RuntimeError(msg)
| {'content_hash': '575a015b526d88c98f213002bc92e4ea', 'timestamp': '', 'source': 'github', 'line_count': 265, 'max_line_length': 79, 'avg_line_length': 46.60377358490566, 'alnum_prop': 0.5726315789473684, 'repo_name': 'wkoathp/glance', 'id': 'b8b96364a4fd72ebbd423e23dfdbc916388318a8', 'size': '13009', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'glance/common/config.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '3844475'}, {'name': 'Shell', 'bytes': '7860'}]} |
require_relative 'fluent/format/version'
require 'fluent/load'
require_relative 'fluent/format/format'
require_relative 'fluent/format/check'
require_relative 'fluent/format'
| {'content_hash': '798d6dabba8458812b3fc905f1aa8d7a', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 40, 'avg_line_length': 35.0, 'alnum_prop': 0.8171428571428572, 'repo_name': 'sonots/fluent-format', 'id': 'be03cb37b84971fc2c54f069c2f3d9d5a53c2c39', 'size': '175', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/fluent-format.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '14028'}]} |
package com.liaoyu.web.system;
import java.io.PrintWriter;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.liaoyu.bean.Notice;
import com.liaoyu.service.user.NoticeService;
import com.liaoyu.web.BaseAction;
import com.opensymphony.xwork2.Preparable;
@Controller @Scope("prototype")
public class NoticeAction extends BaseAction implements Preparable{
private static final long serialVersionUID = 1L;
private PrintWriter out;
@Resource NoticeService ns;
private String ncontent;
private String item[];
public String[] getItem() {
return item;
}
public void setItem(String[] item) {
this.item = item;
}
public String getNcontent() {
return ncontent;
}
public void setNcontent(String ncontent) {
this.ncontent = ncontent;
}
@Override
public void prepare() throws Exception {
out=getResponse().getWriter();
}
public String add(){
try {
Notice notice=new Notice();
notice.setnContent(getNcontent());
notice.setnTime(new Date().toLocaleString());
ns.save(notice);
out.print(0);
return null;
} catch (Exception e) {
e.printStackTrace();
out.print(1);
return null;
}
}
public String delete(){
if(item!=null&&item.length>0){
try {
for(String num:item)
ns.delete(Integer.parseInt(num));
} catch (NumberFormatException e) {
this.addActionMessage("对不起,出错啦");
return "error";
}
this.addActionMessage("删除成功");
return SUCCESS;
}
else{
this.addActionMessage("对不起,出错啦");
return "error";
}
}
}
| {'content_hash': '52c218e10616af810b61e44be1c8a4f9', 'timestamp': '', 'source': 'github', 'line_count': 72, 'max_line_length': 67, 'avg_line_length': 22.444444444444443, 'alnum_prop': 0.7128712871287128, 'repo_name': 'kingzou/uushop', 'id': 'cb1cfc815e817ff766b7f8dbf33308f4e659349c', 'size': '1652', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/liaoyu/web/system/NoticeAction.java', 'mode': '33188', 'license': 'bsd-2-clause', 'language': []} |
/*=== ACCORDION MENU ===*/
/*
Simple JQuery menu.
HTML structure to use:
Notes:
Each menu MUST have a class 'menu' set. If the menu doesn't have this, the JS won't make it dynamic
If you want a panel to be expanded at page load, give the containing LI element the classname 'expand'.
Use this to set the right state in your page (generation) code.
Optional extra classnames for the UL element that holds an accordion:
noaccordion : no accordion functionality
collapsible : menu works like an accordion but can be fully collapsed
<ul class="menu [optional class] [optional class]">
<li><a href="#">Sub menu heading</a>
<ul>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
...
...
</ul>
// This item is open at page load time
<li class="expand"><a href="#">Sub menu heading</a>
<ul>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
...
...
</ul>
...
...
</ul>
Copyright 2007-2010 by Marco van Hylckama Vlieg
web: http://www.i-marco.nl/weblog/
email: [email protected]
Free to use any way you like.
*/
jQuery.fn.initMenu = function() {
return this.each(function(){
var theMenu = $(this).get(0);
$('.acitem', this).hide();
$('li.expand > .acitem', this).show();
$('li.expand > .acitem', this).prev().addClass('active');
$('li a', this).click(
function(e) {
e.stopImmediatePropagation();
var theElement = $(this).next();
var parent = this.parentNode.parentNode;
if($(parent).hasClass('noaccordion')) {
if(theElement[0] === undefined) {
window.location.href = this.href;
}
$(theElement).slideToggle('normal', function() {
if ($(this).is(':visible')) {
$(this).prev().addClass('active');
}
else {
$(this).prev().removeClass('active');
}
});
return false;
}
else {
if(theElement.hasClass('acitem') && theElement.is(':visible')) {
if($(parent).hasClass('collapsible')) {
$('.acitem:visible', parent).first().slideUp('normal',
function() {
$(this).prev().removeClass('active');
}
);
return false;
}
return false;
}
if(theElement.hasClass('acitem') && !theElement.is(':visible')) {
$('.acitem:visible', parent).first().slideUp('normal', function() {
$(this).prev().removeClass('active');
});
theElement.slideDown('normal', function() {
$(this).prev().addClass('active');
});
return false;
}
}
}
);
});
}; | {'content_hash': '5a72faa2f570c9d1de3a8a60061a0d15', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 103, 'avg_line_length': 34.57142857142857, 'alnum_prop': 0.461038961038961, 'repo_name': 'rsuarezdeveloper/cpm', 'id': '9dcfe725dc392e312236e80a61e4b569a68fe123', 'size': '3388', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web/js/accordion.jquery.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '432589'}, {'name': 'JavaScript', 'bytes': '1745562'}, {'name': 'PHP', 'bytes': '160036'}]} |
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
| {'content_hash': '45b4fa63aacd51736c9a36adfef8b8bb', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 90, 'avg_line_length': 31.6, 'alnum_prop': 0.6582278481012658, 'repo_name': 'WTGrim/-WeChat-easeMob', 'id': '70954379468c30f16ba1343349cc12ff3e15471e', 'size': '331', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '环信仿微信/环信demo/main.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '8410'}, {'name': 'C++', 'bytes': '1206'}, {'name': 'Objective-C', 'bytes': '872403'}, {'name': 'Objective-C++', 'bytes': '15269'}, {'name': 'Ruby', 'bytes': '279'}, {'name': 'Shell', 'bytes': '9029'}]} |
<?php
namespace Autenticacao\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class DenyController extends AbstractActionController {
public function indexAction() {
return new ViewModel();
}
}
| {'content_hash': 'e58d437920a954ef86d9382a33d32964', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 55, 'avg_line_length': 18.5, 'alnum_prop': 0.7567567567567568, 'repo_name': 'edianogama/cursozend2', 'id': 'a88b0600a91c095ff8c57717a28061e4a0d976ff', 'size': '259', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'module/Autenticacao/src/Autenticacao/Controller/DenyController.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '711'}, {'name': 'CSS', 'bytes': '1042'}, {'name': 'HTML', 'bytes': '36102'}, {'name': 'PHP', 'bytes': '70200'}]} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<!-- THEME UTILITY -->
<link rel="stylesheet" href="../../../_themes/utils/loader.css" type="text/css">
<!-- END THEME UTILITY -->
<!-- THEME UTILITY -->
<script type="text/javascript" src="../../../_themes/utils/loader.js"></script>
<!-- END THEME UTILITY -->
<!-- CORE -->
<!-- Can be replaced by wink.min.js -->
<script type="text/javascript" src="../../../_amd/js/amd.js"></script>
<script type="text/javascript" src="../../../_base/_base/js/base.js"></script>
<script type="text/javascript" src="../../../_base/error/js/error.js"></script>
<script type="text/javascript" src="../../../_base/json/js/json.js"></script>
<script type="text/javascript" src="../../../_base/ua/js/ua.js"></script>
<script type="text/javascript" src="../../../_base/topics/js/topics.js"></script>
<script type="text/javascript" src="../../../_base/_feat/js/feat.js"></script>
<script type="text/javascript" src="../../../_base/_feat/js/feat_json.js"></script>
<script type="text/javascript" src="../../../_base/_feat/js/feat_css.js"></script>
<script type="text/javascript" src="../../../_base/_feat/js/feat_event.js"></script>
<script type="text/javascript" src="../../../_base/_feat/js/feat_dom.js"></script>
<script type="text/javascript" src="../../../fx/_xy/js/2dfx.js"></script>
<script type="text/javascript" src="../../../math/_basics/js/basics.js"></script>
<script type="text/javascript" src="../../../net/xhr/js/xhr.js"></script>
<script type="text/javascript" src="../../../ui/xy/layer/js/layer.js"></script>
<script type="text/javascript" src="../../../ux/event/js/event.js"></script>
<script type="text/javascript" src="../../../ux/touch/js/touch.js"></script>
<!-- END CORE -->
<script>
Test = function()
{
this.dummyMethod1 = function(parameters)
{
alert('dummy method 1 ' + parameters);
wink.unsubscribe('/test/events/alert1', {method: 'dummyMethod1', context: this});
wink.subscribe('/test/events/alert1', {method: 'dummyMethod2', context: this});
}
this.dummyMethod2 = function(parameters)
{
alert('dummy method 2 ' + parameters);
}
this.init = function()
{
wink.subscribe('/test/events/alert1', {method: 'dummyMethod1', context: this});
}
}
var test = new Test();
function doFireEvent()
{
wink.publish('/test/events/alert1', 'value1');
}
</script>
</head>
<body onload="test.init()">
<div class="w_box w_header w_bg_dark">
<span id="title">topics</span>
<input type="button" value="home" class="w_button w_radius w_bg_light w_right" onclick="window.location='../../../index.html?theme='+theme"/>
</div>
<div class="w_bloc">
Click on the method below to trigger '/test/events/alert1' events.
</div>
<div style="text-align: center">
<input type="button" value="test" onClick="doFireEvent()" class="w_button w_border w_radius w_bg_dark" />
</div>
</body>
</html> | {'content_hash': 'cba1c5902b0a57b871c3119ad3302593', 'timestamp': '', 'source': 'github', 'line_count': 80, 'max_line_length': 144, 'avg_line_length': 40.825, 'alnum_prop': 0.5927740355174526, 'repo_name': 'winktoolkit/wink', 'id': 'f8219f1347b0a7eab4a1f26d24f870bed651f325', 'size': '3266', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_base/topics/test/test_topics_2.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '199862'}, {'name': 'Java', 'bytes': '406412'}, {'name': 'JavaScript', 'bytes': '1415050'}, {'name': 'PHP', 'bytes': '34760'}, {'name': 'Ruby', 'bytes': '578'}, {'name': 'Shell', 'bytes': '1652'}]} |
package breeze.optimize
import breeze.linalg.norm
import breeze.math.{MutableEnumeratedCoordinateField, MutableFiniteCoordinateField, NormedModule}
import breeze.optimize.FirstOrderMinimizer.ConvergenceReason
import breeze.stats.distributions.{RandBasis, ThreadLocalRandomGenerator}
import breeze.util.Implicits._
import breeze.util.SerializableLogging
import org.apache.commons.math3.random.MersenneTwister
import FirstOrderMinimizer.ConvergenceCheck
/**
*
* @author dlwh
*/
abstract class FirstOrderMinimizer[T, DF<:StochasticDiffFunction[T]](val convergenceCheck: ConvergenceCheck[T])
(implicit space: NormedModule[T, Double]) extends Minimizer[T,DF] with SerializableLogging {
def this(maxIter: Int = -1,
tolerance: Double = 1E-6,
fvalMemory: Int = 100,
relativeTolerance: Boolean = true)(implicit space: NormedModule[T, Double]) =
this(FirstOrderMinimizer.defaultConvergenceCheck[T](maxIter, tolerance, relativeTolerance, fvalMemory))
/**
* Any history the derived minimization function needs to do its updates. typically an approximation
* to the second derivative/hessian matrix.
*/
type History
type State = FirstOrderMinimizer.State[T, convergenceCheck.Info, History]
import space.normImpl
protected def initialHistory(f: DF, init: T): History
protected def adjustFunction(f: DF): DF = f
protected def adjust(newX: T, newGrad: T, newVal: Double):(Double,T) = (newVal,newGrad)
protected def chooseDescentDirection(state: State, f: DF):T
protected def determineStepSize(state: State, f: DF, direction: T):Double
protected def takeStep(state: State, dir: T, stepSize:Double):T
protected def updateHistory(newX: T, newGrad: T, newVal: Double, f: DF, oldState: State):History
protected def initialState(f: DF, init: T): State = {
val x = init
val history = initialHistory(f,init)
val (value, grad) = calculateObjective(f, x, history)
val (adjValue,adjGrad) = adjust(x,grad,value)
FirstOrderMinimizer.State(x,value,grad,adjValue,adjGrad,0,adjValue,history, convergenceCheck.initialInfo)
}
protected def calculateObjective(f: DF, x: T, history: History): (Double, T) = {
f.calculate(x)
}
def infiniteIterations(f: DF, state: State): Iterator[State] = {
var failedOnce = false
val adjustedFun = adjustFunction(f)
Iterator.iterate(state) { state => try {
val dir = chooseDescentDirection(state, adjustedFun)
val stepSize = determineStepSize(state, adjustedFun, dir)
logger.info(f"Step Size: $stepSize%.4g")
val x = takeStep(state,dir,stepSize)
val (value,grad) = calculateObjective(adjustedFun, x, state.history)
val (adjValue,adjGrad) = adjust(x,grad,value)
val oneOffImprovement = (state.adjustedValue - adjValue)/(state.adjustedValue.abs max adjValue.abs max 1E-6 * state.initialAdjVal.abs)
logger.info(f"Val and Grad Norm: $adjValue%.6g (rel: $oneOffImprovement%.3g) ${norm(adjGrad)}%.6g")
val history = updateHistory(x,grad,value, adjustedFun, state)
val newCInfo = convergenceCheck.update(x, grad, value, state, state.convergenceInfo)
failedOnce = false
FirstOrderMinimizer.State(x, value, grad, adjValue, adjGrad, state.iter + 1, state.initialAdjVal, history, newCInfo)
} catch {
case x: FirstOrderException if !failedOnce =>
failedOnce = true
logger.error("Failure! Resetting history: " + x)
state.copy(history = initialHistory(adjustedFun, state.x))
case x: FirstOrderException =>
logger.error("Failure again! Giving up and returning. Maybe the objective is just poorly behaved?")
state.copy(searchFailed = true)
}
}
}
def iterations(f: DF, init: T): Iterator[State] = {
val adjustedFun = adjustFunction(f)
infiniteIterations(f, initialState(adjustedFun, init)).takeUpToWhere{s =>
convergenceCheck.apply(s, s.convergenceInfo) match {
case Some(converged) =>
logger.info(s"Converged because ${converged.reason}")
true
case None =>
false
}
}
}
def minimize(f: DF, init: T): T = {
minimizeAndReturnState(f, init).x
}
def minimizeAndReturnState(f: DF, init: T):State = {
iterations(f, init).last
}
}
sealed class FirstOrderException(msg: String="") extends RuntimeException(msg)
class NaNHistory extends FirstOrderException
class StepSizeUnderflow extends FirstOrderException
class StepSizeOverflow extends FirstOrderException
class LineSearchFailed(gradNorm: Double, dirNorm: Double) extends FirstOrderException("Grad norm: %.4f Dir Norm: %.4f".format(gradNorm, dirNorm))
object FirstOrderMinimizer {
/**
* Tracks the information about the optimizer, including the current point, its value, gradient, and then any history.
* Also includes information for checking convergence.
* @param x the current point being considered
* @param value f(x)
* @param grad f.gradientAt(x)
* @param adjustedValue f(x) + r(x), where r is any regularization added to the objective. For LBFGS, this is f(x).
* @param adjustedGradient f'(x) + r'(x), where r is any regularization added to the objective. For LBFGS, this is f'(x).
* @param iter what iteration number we are on.
* @param initialAdjVal f(x_0) + r(x_0), used for checking convergence
* @param history any information needed by the optimizer to do updates.
* @param searchFailed did the line search fail?
*/
case class State[+T, +ConvergenceInfo, +History](x: T,
value: Double, grad: T,
adjustedValue: Double, adjustedGradient: T,
iter: Int,
initialAdjVal: Double,
history: History,
convergenceInfo: ConvergenceInfo,
searchFailed: Boolean = false) {
}
trait ConvergenceCheck[T] {
type Info
def initialInfo: Info
def apply(state: State[T, _, _], info: Info):Option[ConvergenceReason]
def update(newX: T, newGrad: T, newVal: Double, oldState: State[T, _, _], oldInfo: Info):Info
def ||(otherCheck: ConvergenceCheck[T]): ConvergenceCheck[T] = orElse(otherCheck)
def orElse(other: ConvergenceCheck[T]):ConvergenceCheck[T] = {
SequenceConvergenceCheck(asChecks ++ other.asChecks)
}
protected def asChecks:IndexedSeq[ConvergenceCheck[T]] = IndexedSeq(this)
}
object ConvergenceCheck {
implicit def fromPartialFunction[T](pf: PartialFunction[State[T, _, _], ConvergenceReason]):ConvergenceCheck[T] = new ConvergenceCheck[T] {
override type Info = Unit
def update(newX: T, newGrad: T, newVal: Double, oldState: State[T, _, _], oldInfo: Info):Info = oldInfo
override def apply(state: State[T, _, _], info: Info): Option[ConvergenceReason] = pf.lift(state)
override def initialInfo: Info = ()
}
}
case class SequenceConvergenceCheck[T](checks: IndexedSeq[ConvergenceCheck[T]]) extends ConvergenceCheck[T] {
type Info = IndexedSeq[ConvergenceCheck[T]#Info]
override def initialInfo: IndexedSeq[ConvergenceCheck[T]#Info] = checks.map(_.initialInfo)
override def update(newX: T, newGrad: T, newVal: Double, oldState: State[T, _, _], oldInfo: Info): Info = {
require(oldInfo.length == checks.length)
(checks zip oldInfo).map { case (c, i) => c.update(newX, newGrad, newVal, oldState, i.asInstanceOf[c.Info]) }
}
override def apply(state: State[T, _, _], info: IndexedSeq[ConvergenceCheck[T]#Info]): Option[ConvergenceReason] = {
(checks zip info).iterator.flatMap { case (c, i) => c(state, i.asInstanceOf[c.Info])}.toStream.headOption
}
}
trait ConvergenceReason {
def reason: String
}
case object MaxIterations extends ConvergenceReason {
override def reason: String = "max iterations reached"
}
case object FunctionValuesConverged extends ConvergenceReason {
override def reason: String = "function values converged"
}
case object GradientConverged extends ConvergenceReason {
override def reason: String = "gradient converged"
}
case object SearchFailed extends ConvergenceReason {
override def reason: String = "line search failed!"
}
case object MonitorFunctionNotImproving extends ConvergenceReason {
override def reason: String = "monitor function is not improving"
}
case object ProjectedStepConverged extends ConvergenceReason {
override def reason: String = "projected step converged"
}
def maxIterationsReached[T](maxIter: Int): ConvergenceCheck[T] = ConvergenceCheck.fromPartialFunction {
case s: State[_, _, _] if (s.iter >= maxIter && maxIter >= 0) =>
MaxIterations
}
def functionValuesConverged[T](tolerance: Double = 1E-9, relative: Boolean = true, historyLength: Int = 10): ConvergenceCheck[T] = {
new FunctionValuesConverged[T](tolerance, relative, historyLength)
}
case class FunctionValuesConverged[T](tolerance: Double, relative: Boolean, historyLength: Int) extends ConvergenceCheck[T] {
override type Info = IndexedSeq[Double]
override def update(newX: T, newGrad: T, newVal: Double, oldState: State[T, _, _], oldInfo: Info): Info = {
(oldInfo :+ newVal).takeRight(historyLength)
}
override def apply(state: State[T, _, _], info: IndexedSeq[Double]): Option[ConvergenceReason] = {
if(info.length >= 2 && (state.adjustedValue - info.max).abs <= tolerance * (if (relative) state.initialAdjVal else 1.0)) {
Some(FunctionValuesConverged)
} else {
None
}
}
override def initialInfo: Info = IndexedSeq(Double.PositiveInfinity)
}
def gradientConverged[T](tolerance: Double, relative: Boolean = true)(implicit space: NormedModule[T, Double]): ConvergenceCheck[T] = {
import space.normImpl
ConvergenceCheck.fromPartialFunction[T] {
case s: State[T, _, _] if (norm(s.adjustedGradient) <= math.max(tolerance * (if (relative) s.adjustedValue else 1.0), 1E-8)) =>
GradientConverged
}
}
def searchFailed[T]: ConvergenceCheck[T] = ConvergenceCheck.fromPartialFunction {
case s: State[_, _, _] if (s.searchFailed) =>
SearchFailed
}
/**
* Runs the function, and if it fails to decreased by at least improvementRequirement numFailures times in a row,
* then we abort
* @param f
* @param numFailures
* @param evalFrequency how often we run the evaluation
* @tparam T
*/
def monitorFunctionValues[T](f: T=>Double,
numFailures: Int = 5,
improvementRequirement: Double = 1E-2,
evalFrequency: Int = 10):ConvergenceCheck[T] = new MonitorFunctionValuesCheck(f, numFailures, improvementRequirement, evalFrequency)
case class MonitorFunctionValuesCheck[T](f: T=>Double, numFailures: Int, improvementRequirement: Double, evalFrequency: Int) extends ConvergenceCheck[T] with SerializableLogging {
case class Info(bestValue: Double, numFailures: Int)
override def update(newX: T, newGrad: T, newVal: Double, oldState: State[T, _, _], oldInfo: Info): Info = {
if (oldState.iter % evalFrequency == 0) {
val newValue = f(newX)
if (newValue <= oldInfo.bestValue * (1 - improvementRequirement)) {
logger.info(f"External function improved: current ${newValue}%.3f old: ${oldInfo.bestValue}%.3f")
Info(numFailures = 0, bestValue = newValue)
} else {
logger.info(f"External function failed to improve sufficiently! current ${newValue}%.3f old: ${oldInfo.bestValue}%.3f")
oldInfo.copy(numFailures = oldInfo.numFailures + 1)
}
} else {
oldInfo
}
}
override def apply(state: State[T, _, _], info: Info): Option[ConvergenceReason] = {
if(info.numFailures >= numFailures) {
Some(MonitorFunctionNotImproving)
} else {
None
}
}
override def initialInfo: Info = Info(Double.PositiveInfinity, 0)
}
def defaultConvergenceCheck[T](maxIter: Int, tolerance: Double, relative: Boolean = true, fvalMemory: Int = 20)(implicit space: NormedModule[T, Double]): ConvergenceCheck[T] =
(
maxIterationsReached[T](maxIter) ||
functionValuesConverged(tolerance, relative, fvalMemory) ||
gradientConverged[T](tolerance, relative) ||
searchFailed
)
/**
* OptParams is a Configuration-compatible case class that can be used to select optimization
* routines at runtime.
*
* Configurations:
* 1) useStochastic=false,useL1=false: LBFGS with L2 regularization
* 2) useStochastic=false,useL1=true: OWLQN with L1 regularization
* 3) useStochastic=true,useL1=false: AdaptiveGradientDescent with L2 regularization
* 3) useStochastic=true,useL1=true: AdaptiveGradientDescent with L1 regularization
*
*
* @param batchSize size of batches to use if useStochastic and you give a BatchDiffFunction
* @param regularization regularization constant to use.
* @param alpha rate of change to use, only applies to SGD.
* @param maxIterations, how many iterations to do.
* @param useL1 if true, use L1 regularization. Otherwise, use L2.
* @param tolerance convergence tolerance, looking at both average improvement and the norm of the gradient.
* @param useStochastic if false, use LBFGS or OWLQN. If true, use some variant of Stochastic Gradient Descent.
*/
case class OptParams(batchSize:Int = 512,
regularization: Double = 0.0,
alpha: Double = 0.5,
maxIterations:Int = 1000,
useL1: Boolean = false,
tolerance:Double = 1E-5,
useStochastic: Boolean= false,
randomSeed: Int = 0) {
private implicit val random = new RandBasis(new ThreadLocalRandomGenerator(new MersenneTwister(randomSeed)))
@deprecated("Use breeze.optimize.minimize(f, init, params) instead.", "0.10")
def minimize[T](f: BatchDiffFunction[T], init: T)(implicit space: MutableFiniteCoordinateField[T, _, Double]): T = {
this.iterations(f, init).last.x
}
@deprecated("Use breeze.optimize.minimize(f, init, params) instead.", "0.10")
def minimize[T](f: DiffFunction[T], init: T)(implicit space: MutableEnumeratedCoordinateField[T, _, Double]): T = {
this.iterations(f, init).last.x
}
@deprecated("Use breeze.optimize.iterations(f, init, params) instead.", "0.10")
def iterations[T](f: BatchDiffFunction[T], init: T)(implicit space: MutableFiniteCoordinateField[T, _, Double]): Iterator[FirstOrderMinimizer[T, BatchDiffFunction[T]]#State] = {
val it = if(useStochastic) {
this.iterations(f.withRandomBatches(batchSize), init)(space)
} else {
iterations(f:DiffFunction[T], init)
}
it.asInstanceOf[Iterator[FirstOrderMinimizer[T, BatchDiffFunction[T]]#State]]
}
@deprecated("Use breeze.optimize.iterations(f, init, params) instead.", "0.10")
def iterations[T](f: StochasticDiffFunction[T], init:T)(implicit space: MutableFiniteCoordinateField[T, _, Double]):Iterator[FirstOrderMinimizer[T, StochasticDiffFunction[T]]#State] = {
val r = if(useL1) {
new AdaptiveGradientDescent.L1Regularization[T](regularization, eta=alpha, maxIter = maxIterations)(space, random)
} else { // L2
new AdaptiveGradientDescent.L2Regularization[T](regularization, alpha, maxIterations)(space, random)
}
r.iterations(f,init)
}
@deprecated("Use breeze.optimize.iterations(f, init, params) instead.", "0.10")
def iterations[T, K](f: DiffFunction[T], init:T)(implicit space: MutableEnumeratedCoordinateField[T, K, Double]): Iterator[LBFGS[T]#State] = {
if(useL1) new OWLQN[K, T](maxIterations, 5, regularization, tolerance)(space).iterations(f,init)
else (new LBFGS[T](maxIterations, 5, tolerance=tolerance)(space)).iterations(DiffFunction.withL2Regularization(f,regularization),init)
}
}
}
| {'content_hash': '40d8837fe204c3ba51c4a4b76e8f5ec6', 'timestamp': '', 'source': 'github', 'line_count': 366, 'max_line_length': 189, 'avg_line_length': 44.62021857923497, 'alnum_prop': 0.6744228767374931, 'repo_name': 'claydonkey/breeze', 'id': '2756de5ea227700f2795ac5f9921abcdaac4fe9b', 'size': '16331', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'math/src/main/scala/breeze/optimize/FirstOrderMinimizer.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '4123'}, {'name': 'Scala', 'bytes': '2366863'}]} |
package meta
import (
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"time"
"github.com/gogo/protobuf/proto"
"github.com/influxdb/influxdb/meta/internal"
)
// Max size of a message before we treat the size as invalid
const (
MaxMessageSize = 1024 * 1024 * 1024
leaderDialTimeout = 10 * time.Second
)
// rpc handles request/response style messaging between cluster nodes
type rpc struct {
logger *log.Logger
tracingEnabled bool
store interface {
cachedData() *Data
IsLeader() bool
Leader() string
Peers() []string
AddPeer(host string) error
CreateNode(host string) (*NodeInfo, error)
NodeByHost(host string) (*NodeInfo, error)
WaitForDataChanged() error
}
}
type JoinResult struct {
RaftEnabled bool
RaftNodes []string
NodeID uint64
}
type Reply interface {
GetHeader() *internal.ResponseHeader
}
// proxyLeader proxies the connection to the current raft leader
func (r *rpc) proxyLeader(conn *net.TCPConn) {
if r.store.Leader() == "" {
r.sendError(conn, "no leader")
return
}
leaderConn, err := net.DialTimeout("tcp", r.store.Leader(), leaderDialTimeout)
if err != nil {
r.sendError(conn, fmt.Sprintf("dial leader: %v", err))
return
}
defer leaderConn.Close()
leaderConn.Write([]byte{MuxRPCHeader})
if err := proxy(leaderConn.(*net.TCPConn), conn); err != nil {
r.sendError(conn, fmt.Sprintf("leader proxy error: %v", err))
}
}
// handleRPCConn reads a command from the connection and executes it.
func (r *rpc) handleRPCConn(conn net.Conn) {
defer conn.Close()
// RPC connections should execute on the leader. If we are not the leader,
// proxy the connection to the leader so that clients an connect to any node
// in the cluster.
r.traceCluster("rpc connection from: %v", conn.RemoteAddr())
if !r.store.IsLeader() {
r.proxyLeader(conn.(*net.TCPConn))
return
}
// Read and execute request.
typ, resp, err := func() (internal.RPCType, proto.Message, error) {
// Read request size.
var sz uint64
if err := binary.Read(conn, binary.BigEndian, &sz); err != nil {
return internal.RPCType_Error, nil, fmt.Errorf("read size: %s", err)
}
if sz == 0 {
return 0, nil, fmt.Errorf("invalid message size: %d", sz)
}
if sz >= MaxMessageSize {
return 0, nil, fmt.Errorf("max message size of %d exceeded: %d", MaxMessageSize, sz)
}
// Read request.
buf := make([]byte, sz)
if _, err := io.ReadFull(conn, buf); err != nil {
return internal.RPCType_Error, nil, fmt.Errorf("read request: %s", err)
}
// Determine the RPC type
rpcType := internal.RPCType(btou64(buf[0:8]))
buf = buf[8:]
r.traceCluster("recv %v request on: %v", rpcType, conn.RemoteAddr())
switch rpcType {
case internal.RPCType_FetchData:
var req internal.FetchDataRequest
if err := proto.Unmarshal(buf, &req); err != nil {
return internal.RPCType_Error, nil, fmt.Errorf("fetch request unmarshal: %v", err)
}
resp, err := r.handleFetchData(&req)
return rpcType, resp, err
case internal.RPCType_Join:
var req internal.JoinRequest
if err := proto.Unmarshal(buf, &req); err != nil {
return internal.RPCType_Error, nil, fmt.Errorf("join request unmarshal: %v", err)
}
resp, err := r.handleJoinRequest(&req)
return rpcType, resp, err
default:
return internal.RPCType_Error, nil, fmt.Errorf("unknown rpc type:%v", rpcType)
}
}()
// Handle unexpected RPC errors
if err != nil {
resp = &internal.ErrorResponse{
Header: &internal.ResponseHeader{
OK: proto.Bool(false),
},
}
typ = internal.RPCType_Error
}
// Set the status header and error message
if reply, ok := resp.(Reply); ok {
reply.GetHeader().OK = proto.Bool(err == nil)
if err != nil {
reply.GetHeader().Error = proto.String(err.Error())
}
}
r.sendResponse(conn, typ, resp)
}
func (r *rpc) sendResponse(conn net.Conn, typ internal.RPCType, resp proto.Message) {
// Marshal the response back to a protobuf
buf, err := proto.Marshal(resp)
if err != nil {
r.logger.Printf("unable to marshal response: %v", err)
return
}
// Encode response back to connection.
if _, err := conn.Write(r.pack(typ, buf)); err != nil {
r.logger.Printf("unable to write rpc response: %s", err)
}
}
func (r *rpc) sendError(conn net.Conn, msg string) {
r.traceCluster(msg)
resp := &internal.ErrorResponse{
Header: &internal.ResponseHeader{
OK: proto.Bool(false),
Error: proto.String(msg),
},
}
r.sendResponse(conn, internal.RPCType_Error, resp)
}
// handleFetchData handles a request for the current nodes meta data
func (r *rpc) handleFetchData(req *internal.FetchDataRequest) (*internal.FetchDataResponse, error) {
var (
b []byte
data *Data
err error
)
for {
data = r.store.cachedData()
if data.Index != req.GetIndex() {
b, err = data.MarshalBinary()
if err != nil {
return nil, err
}
break
}
if !req.GetBlocking() {
break
}
if err := r.store.WaitForDataChanged(); err != nil {
return nil, err
}
}
return &internal.FetchDataResponse{
Header: &internal.ResponseHeader{
OK: proto.Bool(true),
},
Index: proto.Uint64(data.Index),
Term: proto.Uint64(data.Term),
Data: b}, nil
}
// handleJoinRequest handles a request to join the cluster
func (r *rpc) handleJoinRequest(req *internal.JoinRequest) (*internal.JoinResponse, error) {
r.traceCluster("join request from: %v", *req.Addr)
node, err := func() (*NodeInfo, error) {
// attempt to create the node
node, err := r.store.CreateNode(*req.Addr)
// if it exists, return the existing node
if err == ErrNodeExists {
return r.store.NodeByHost(*req.Addr)
} else if err != nil {
return nil, fmt.Errorf("create node: %v", err)
}
// FIXME: jwilder: adding raft nodes is tricky since going
// from 1 node (leader) to two kills the cluster because
// quorum is lost after adding the second node. For now,
// can only add non-raft enabled nodes
// If we have less than 3 nodes, add them as raft peers
// if len(r.store.Peers()) < MaxRaftNodes {
// if err = r.store.AddPeer(*req.Addr); err != nil {
// return node, fmt.Errorf("add peer: %v", err)
// }
// }
return node, err
}()
nodeID := uint64(0)
if node != nil {
nodeID = node.ID
}
if err != nil {
return nil, err
}
return &internal.JoinResponse{
Header: &internal.ResponseHeader{
OK: proto.Bool(true),
},
//EnableRaft: proto.Bool(contains(r.store.Peers(), *req.Addr)),
EnableRaft: proto.Bool(false),
RaftNodes: r.store.Peers(),
NodeID: proto.Uint64(nodeID),
}, err
}
// pack returns a TLV style byte slice encoding the size of the payload, the RPC type
// and the RPC data
func (r *rpc) pack(typ internal.RPCType, b []byte) []byte {
buf := u64tob(uint64(len(b)) + 8)
buf = append(buf, u64tob(uint64(typ))...)
buf = append(buf, b...)
return buf
}
// fetchMetaData returns the latest copy of the meta store data from the current
// leader.
func (r *rpc) fetchMetaData(blocking bool) (*Data, error) {
assert(r.store != nil, "store is nil")
// Retrieve the current known leader.
leader := r.store.Leader()
if leader == "" {
return nil, errors.New("no leader")
}
var index, term uint64
data := r.store.cachedData()
if data != nil {
index = data.Index
term = data.Index
}
resp, err := r.call(leader, &internal.FetchDataRequest{
Index: proto.Uint64(index),
Term: proto.Uint64(term),
Blocking: proto.Bool(blocking),
})
if err != nil {
return nil, err
}
switch t := resp.(type) {
case *internal.FetchDataResponse:
// If data is nil, then the term and index we sent matches the leader
if t.GetData() == nil {
return nil, nil
}
ms := &Data{}
if err := ms.UnmarshalBinary(t.GetData()); err != nil {
return nil, fmt.Errorf("rpc unmarshal metadata: %v", err)
}
return ms, nil
case *internal.ErrorResponse:
return nil, fmt.Errorf("rpc failed: %s", t.GetHeader().GetError())
default:
return nil, fmt.Errorf("rpc failed: unknown response type: %v", t.String())
}
}
// join attempts to join a cluster at remoteAddr using localAddr as the current
// node's cluster address
func (r *rpc) join(localAddr, remoteAddr string) (*JoinResult, error) {
req := &internal.JoinRequest{
Addr: proto.String(localAddr),
}
resp, err := r.call(remoteAddr, req)
if err != nil {
return nil, err
}
switch t := resp.(type) {
case *internal.JoinResponse:
return &JoinResult{
RaftEnabled: t.GetEnableRaft(),
RaftNodes: t.GetRaftNodes(),
NodeID: t.GetNodeID(),
}, nil
case *internal.ErrorResponse:
return nil, fmt.Errorf("rpc failed: %s", t.GetHeader().GetError())
default:
return nil, fmt.Errorf("rpc failed: unknown response type: %v", t.String())
}
}
// call sends an encoded request to the remote leader and returns
// an encoded response value.
func (r *rpc) call(dest string, req proto.Message) (proto.Message, error) {
// Determine type of request
var rpcType internal.RPCType
switch t := req.(type) {
case *internal.JoinRequest:
rpcType = internal.RPCType_Join
case *internal.FetchDataRequest:
rpcType = internal.RPCType_FetchData
default:
return nil, fmt.Errorf("unknown rpc request type: %v", t)
}
// Create a connection to the leader.
conn, err := net.DialTimeout("tcp", dest, leaderDialTimeout)
if err != nil {
return nil, err
}
defer conn.Close()
// Write a marker byte for rpc messages.
_, err = conn.Write([]byte{MuxRPCHeader})
if err != nil {
return nil, err
}
b, err := proto.Marshal(req)
if err != nil {
return nil, fmt.Errorf("rpc marshal: %v", err)
}
// Write request size & bytes.
if _, err := conn.Write(r.pack(rpcType, b)); err != nil {
return nil, fmt.Errorf("write %v rpc: %s", rpcType, err)
}
data, err := ioutil.ReadAll(conn)
if err != nil {
return nil, fmt.Errorf("read %v rpc: %v", rpcType, err)
}
// Should always have a size and type
if exp := 16; len(data) < exp {
return nil, fmt.Errorf("rpc %v failed: short read: got %v, exp %v", rpcType, len(data), exp)
}
sz := btou64(data[0:8])
if len(data[8:]) != int(sz) {
return nil, fmt.Errorf("rpc %v failed: short read: got %v, exp %v", rpcType, len(data[8:]), sz)
}
// See what response type we got back, could get a general error response
rpcType = internal.RPCType(btou64(data[8:16]))
data = data[16:]
var resp proto.Message
switch rpcType {
case internal.RPCType_Join:
resp = &internal.JoinResponse{}
case internal.RPCType_FetchData:
resp = &internal.FetchDataResponse{}
case internal.RPCType_Error:
resp = &internal.ErrorResponse{}
default:
return nil, fmt.Errorf("unknown rpc response type: %v", rpcType)
}
if err := proto.Unmarshal(data, resp); err != nil {
return nil, fmt.Errorf("rpc unmarshal: %v", err)
}
if reply, ok := resp.(Reply); ok {
if !reply.GetHeader().GetOK() {
return nil, fmt.Errorf("rpc %v failed: %s", rpcType, reply.GetHeader().GetError())
}
}
return resp, nil
}
func (r *rpc) traceCluster(msg string, args ...interface{}) {
if r.tracingEnabled {
r.logger.Printf("rpc error: "+msg, args...)
}
}
func u64tob(v uint64) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, v)
return b
}
func btou64(b []byte) uint64 {
return binary.BigEndian.Uint64(b)
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
| {'content_hash': 'dc48f2044ef2856821c404d8a69bc6ab', 'timestamp': '', 'source': 'github', 'line_count': 445, 'max_line_length': 100, 'avg_line_length': 25.530337078651684, 'alnum_prop': 0.6646421969897016, 'repo_name': 'crask/kafka-offset-mon', 'id': '2e8fad99af9652579c3c790a1054bc8acda8f763', 'size': '11361', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'Godeps/_workspace/src/github.com/influxdb/influxdb/meta/rpc.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '17830'}, {'name': 'PHP', 'bytes': '1687'}]} |
<?php
namespace Achillesp\Matryoshka\Test;
use Achillesp\Matryoshka\MatryoshkaServiceProvider;
use Achillesp\Matryoshka\Test\Models\Post;
use Illuminate\Database\Capsule\Manager as DB;
use Orchestra\Testbench\TestCase as OrchestraTestCase;
abstract class TestCase extends OrchestraTestCase
{
public function setUp()
{
parent::setUp();
$this->setUpDatabase();
$this->migrateTables();
}
protected function getPackageProviders($app)
{
return [
MatryoshkaServiceProvider::class,
];
}
protected function setUpDatabase()
{
$database = new DB();
$database->addConnection(['driver' => 'sqlite', 'database' => ':memory:']);
$database->bootEloquent();
$database->setAsGlobal();
}
protected function migrateTables()
{
DB::schema()->create('posts', function ($table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
}
protected function makePost()
{
$post = new Post();
$post->title = 'Some title';
$post->save();
return $post;
}
}
| {'content_hash': 'e234a5cc516b1ff84da01c4624e965fa', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 83, 'avg_line_length': 22.41509433962264, 'alnum_prop': 0.5892255892255892, 'repo_name': 'achillesp/matryoshka', 'id': 'eb94c35e214271817003a7b38db7e6ace97c1a88', 'size': '1188', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/TestCase.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '12145'}]} |
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Sql.Models;
namespace Azure.ResourceManager.Sql
{
internal partial class BackupLongTermRetentionPoliciesRestOperations
{
private string subscriptionId;
private Uri endpoint;
private ClientDiagnostics _clientDiagnostics;
private HttpPipeline _pipeline;
/// <summary> Initializes a new instance of BackupLongTermRetentionPoliciesRestOperations. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="endpoint"> server parameter. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public BackupLongTermRetentionPoliciesRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
endpoint ??= new Uri("https://management.azure.com");
this.subscriptionId = subscriptionId;
this.endpoint = endpoint;
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
internal HttpMessage CreateGetRequest(string resourceGroupName, string serverName, string databaseName, LongTermRetentionPolicyName policyName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Sql/servers/", false);
uri.AppendPath(serverName, true);
uri.AppendPath("/databases/", false);
uri.AppendPath(databaseName, true);
uri.AppendPath("/backupLongTermRetentionPolicies/", false);
uri.AppendPath(policyName.ToString(), true);
uri.AppendQuery("api-version", "2017-03-01-preview", true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Gets a database's long term retention policy. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="policyName"> The policy name. Should always be Default. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception>
public async Task<Response<BackupLongTermRetentionPolicy>> GetAsync(string resourceGroupName, string serverName, string databaseName, LongTermRetentionPolicyName policyName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (serverName == null)
{
throw new ArgumentNullException(nameof(serverName));
}
if (databaseName == null)
{
throw new ArgumentNullException(nameof(databaseName));
}
using var message = CreateGetRequest(resourceGroupName, serverName, databaseName, policyName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
BackupLongTermRetentionPolicy value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = BackupLongTermRetentionPolicy.DeserializeBackupLongTermRetentionPolicy(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets a database's long term retention policy. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="policyName"> The policy name. Should always be Default. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception>
public Response<BackupLongTermRetentionPolicy> Get(string resourceGroupName, string serverName, string databaseName, LongTermRetentionPolicyName policyName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (serverName == null)
{
throw new ArgumentNullException(nameof(serverName));
}
if (databaseName == null)
{
throw new ArgumentNullException(nameof(databaseName));
}
using var message = CreateGetRequest(resourceGroupName, serverName, databaseName, policyName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
BackupLongTermRetentionPolicy value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = BackupLongTermRetentionPolicy.DeserializeBackupLongTermRetentionPolicy(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateCreateOrUpdateRequest(string resourceGroupName, string serverName, string databaseName, LongTermRetentionPolicyName policyName, BackupLongTermRetentionPolicy parameters)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Put;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Sql/servers/", false);
uri.AppendPath(serverName, true);
uri.AppendPath("/databases/", false);
uri.AppendPath(databaseName, true);
uri.AppendPath("/backupLongTermRetentionPolicies/", false);
uri.AppendPath(policyName.ToString(), true);
uri.AppendQuery("api-version", "2017-03-01-preview", true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(parameters);
request.Content = content;
return message;
}
/// <summary> Sets a database's long term retention policy. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="policyName"> The policy name. Should always be Default. </param>
/// <param name="parameters"> The long term retention policy info. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, or <paramref name="parameters"/> is null. </exception>
public async Task<Response> CreateOrUpdateAsync(string resourceGroupName, string serverName, string databaseName, LongTermRetentionPolicyName policyName, BackupLongTermRetentionPolicy parameters, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (serverName == null)
{
throw new ArgumentNullException(nameof(serverName));
}
if (databaseName == null)
{
throw new ArgumentNullException(nameof(databaseName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateCreateOrUpdateRequest(resourceGroupName, serverName, databaseName, policyName, parameters);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Sets a database's long term retention policy. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="policyName"> The policy name. Should always be Default. </param>
/// <param name="parameters"> The long term retention policy info. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, or <paramref name="parameters"/> is null. </exception>
public Response CreateOrUpdate(string resourceGroupName, string serverName, string databaseName, LongTermRetentionPolicyName policyName, BackupLongTermRetentionPolicy parameters, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (serverName == null)
{
throw new ArgumentNullException(nameof(serverName));
}
if (databaseName == null)
{
throw new ArgumentNullException(nameof(databaseName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateCreateOrUpdateRequest(resourceGroupName, serverName, databaseName, policyName, parameters);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListByDatabaseRequest(string resourceGroupName, string serverName, string databaseName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Sql/servers/", false);
uri.AppendPath(serverName, true);
uri.AppendPath("/databases/", false);
uri.AppendPath(databaseName, true);
uri.AppendPath("/backupLongTermRetentionPolicies", false);
uri.AppendQuery("api-version", "2017-03-01-preview", true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
return message;
}
/// <summary> Gets a database's long term retention policy. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception>
public async Task<Response<BackupLongTermRetentionPolicy>> ListByDatabaseAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (serverName == null)
{
throw new ArgumentNullException(nameof(serverName));
}
if (databaseName == null)
{
throw new ArgumentNullException(nameof(databaseName));
}
using var message = CreateListByDatabaseRequest(resourceGroupName, serverName, databaseName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
BackupLongTermRetentionPolicy value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = BackupLongTermRetentionPolicy.DeserializeBackupLongTermRetentionPolicy(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets a database's long term retention policy. </summary>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception>
public Response<BackupLongTermRetentionPolicy> ListByDatabase(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken = default)
{
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (serverName == null)
{
throw new ArgumentNullException(nameof(serverName));
}
if (databaseName == null)
{
throw new ArgumentNullException(nameof(databaseName));
}
using var message = CreateListByDatabaseRequest(resourceGroupName, serverName, databaseName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
BackupLongTermRetentionPolicy value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = BackupLongTermRetentionPolicy.DeserializeBackupLongTermRetentionPolicy(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
}
}
| {'content_hash': '0402082282beb160031243886e92203f', 'timestamp': '', 'source': 'github', 'line_count': 339, 'max_line_length': 250, 'avg_line_length': 55.02064896755162, 'alnum_prop': 0.6263671456144113, 'repo_name': 'yugangw-msft/azure-sdk-for-net', 'id': 'ba174e0c3a1d677528a920f1120662732fa1fa51', 'size': '18790', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/BackupLongTermRetentionPoliciesRestOperations.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '118'}, {'name': 'Batchfile', 'bytes': '817'}, {'name': 'C#', 'bytes': '55680650'}, {'name': 'CSS', 'bytes': '685'}, {'name': 'Cucumber', 'bytes': '89597'}, {'name': 'JavaScript', 'bytes': '1719'}, {'name': 'PowerShell', 'bytes': '24329'}, {'name': 'Shell', 'bytes': '45'}]} |
needs_sphinx = '1.3'
from recommonmark.parser import CommonMarkParser
from recommonmark.transform import AutoStructify
import re
import os, os.path
source_parsers = {
'.md': CommonMarkParser,
}
html_context = {
'github_user': 'NEAT-project',
'github_repo': 'neat',
'github_version': 'master',
'display_github': True,
'conf_py_path': '/docs/',
}
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
source_suffix = ['.md', '.rst']
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'NEAT'
copyright = '2016, The NEAT Authors'
author = 'The NEAT Authors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = 'NEAT v0.1'
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
# html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generated.
#
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'NEATdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
'papersize': 'a4paper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'NEAT.tex', 'NEAT Documentation',
'The NEAT Authors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False
# If true, show page references after internal links.
#
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#
# latex_appendices = []
# It false, will not define \strong, \code, itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True
# If false, no module index is generated.
#
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'neat', 'NEAT Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'NEAT', 'NEAT Documentation',
author, 'NEAT', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []
# If false, no module index is generated.
#
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False
from docutils import nodes, transforms
import os
class AutoDocRefFix(AutoStructify):
def parse_ref(self, ref):
"""Analyze the ref block, and return the information needed.
Parameters
----------
ref : nodes.reference
Returns
-------
result : tuple of (str, str, str)
The returned result is tuple of (title, uri, docpath).
title is the display title of the ref.
uri is the html uri of to the ref after resolve.
docpath is the absolute document path to the document, if
the target corresponds to an internal document, this can bex None
"""
assert isinstance(ref, nodes.reference)
title = None
if len(ref.children) == 0:
title = ref['name']
elif isinstance(ref.children[0], nodes.Text):
# OYSTEDAL: Use all children of the ref object as the link text
# This is necessary because _ is translated into a text object of
# its own
title = ''.join(map(lambda x: x.astext(), ref.children))
# title = ref.children[0].astext()
uri = ref['refuri']
if uri.find('://') != -1:
return (title, uri, None)
anchor = None
arr = uri.split('#')
if len(arr) == 2:
anchor = arr[1]
if len(arr) > 2 or len(arr[0]) == 0:
return (title, uri, None)
uri = arr[0]
abspath = os.path.abspath(os.path.join(self.file_dir, uri))
relpath = os.path.relpath(abspath, self.root_dir)
suffix = abspath.rsplit('.', 1)
if len(suffix) == 2 and suffix[1] in AutoStructify.suffix_set and (
os.path.exists(abspath) and abspath.startswith(self.root_dir)):
# replace the path separator if running on non-UNIX environment
if os.path.sep != '/':
relpath = relpath.replace(os.path.sep, '/')
docpath = '/' + relpath.rsplit('.', 1)[0]
# rewrite suffix to html, this is suboptimal
uri = docpath + '.html'
if anchor is None:
return (title, uri, docpath)
else:
return (title, uri + '#' + anchor, None)
else:
# use url resolver
if self.url_resolver:
uri = self.url_resolver(relpath)
if anchor:
uri += '#' + anchor
return (title, uri, None)
def auto_doc_ref(self, node):
"""Try to convert a reference to docref in rst.
Parameters
----------
node : nodes.reference
A reference node in doctree.
Returns
-------
tocnode: docutils node
The converted toc tree node, None if conversion is not possible.
"""
if not self.config['enable_auto_doc_ref']:
return None
assert isinstance(node, nodes.reference)
title, uri, docpath = self.parse_ref(node)
if title is None:
return None
if docpath:
print(docpath)
if '.md' in docpath:
self.reporter.warning('Missing a file? Could not find', uri)
content = u'%s <%s>' % (title, docpath)
self.state_machine.reset(self.document,
node.parent,
self.current_level)
return self.state_machine.run_role('doc', content=content)
else:
# inplace modify uri
node['refuri'] = uri
return None
def load_embedded_code_for_block(self, node):
assert isinstance(node, nodes.literal_block)
content = node.rawsource.split('\n')
original_node = node
if 'language' not in node:
return None
language = node['language']
match = re.search("[ ]?embed::", language)
if not match:
return None
embedded_language = re.search("[ ]?language::(\w+)", language)
if embedded_language:
language = embedded_language.group(1)
else:
language = ""
self.state_machine.reset(self.document,
node.parent,
self.current_level)
args = ''.join(content).strip().split(':')
start = 0
end = -1
lines = None
if len(args) == 1:
file_name = args[0]
if len(file_name) == 0:
lines = ['Usage: filename:start-end']
language = "txt"
else:
file_path = os.path.join(os.getcwd(), file_name)
try:
with open(file_path, 'r') as f:
lines = [ line.replace('\n','') for line in f.readlines() ]
has_file = True
except IOError:
lines = ['Unable to open/read file', file_name]
language = "txt"
else:
file_name = args[0]
file_slice = args[1]
has_file = False
file_path = os.path.join(os.getcwd(), file_name)
try:
with open(file_path, 'r') as f:
lines = [ line.replace('\n','') for line in f.readlines() ]
has_file = True
except IOError:
lines = ['Unable to open/read file', file_name]
language = "txt"
if has_file:
m = re.search("(\d+)?-(\d+)?", file_slice)
if m:
groups = m.groups()
if groups[0]:
start = int(groups[0]) - 1
if groups[1]:
end = int(groups[1])
if end >= len(lines) or end == -1:
end = len(lines)
return self.state_machine.run_directive(
'code-block', arguments=[language],
content=lines[start:end])
def find_replace(self, node):
newnode = None
if isinstance(node, nodes.literal_block):
newnode = self.load_embedded_code_for_block(node)
return newnode if newnode else AutoStructify.find_replace(self, node)
def setup(app):
app.add_config_value('recommonmark_config', {
# 'url_resolver': lambda url: github_doc_root + url,
'auto_toc_tree_section': 'Contents',
'enable_auto_doc_ref': True,
}, True)
app.add_transform(AutoDocRefFix)
| {'content_hash': 'dc845754e217fc41d8506e925e4dbc79', 'timestamp': '', 'source': 'github', 'line_count': 509, 'max_line_length': 83, 'avg_line_length': 30.92141453831041, 'alnum_prop': 0.6093144418323909, 'repo_name': 'NEAT-project/neat', 'id': '3ea12acf214dbf534c5b87a2b47b350ce8139bac', 'size': '16638', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/conf.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '1083254'}, {'name': 'C++', 'bytes': '46588'}, {'name': 'CMake', 'bytes': '19683'}, {'name': 'CSS', 'bytes': '230'}, {'name': 'HTML', 'bytes': '4564'}, {'name': 'Jupyter Notebook', 'bytes': '25376'}, {'name': 'Makefile', 'bytes': '1034'}, {'name': 'Python', 'bytes': '105894'}, {'name': 'SWIG', 'bytes': '6197'}, {'name': 'Shell', 'bytes': '82547'}]} |
@ParametersAreNonnullByDefault
package org.zalando.riptide.httpclient.metrics;
import javax.annotation.ParametersAreNonnullByDefault;
| {'content_hash': '594933a71a8d453c5e6d07817f149fbc', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 54, 'avg_line_length': 33.75, 'alnum_prop': 0.8888888888888888, 'repo_name': 'zalando/riptide', 'id': 'a9c74a3e0ddf1692ba5af49f7a2522388d292f59', 'size': '135', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'riptide-httpclient/src/main/java/org/zalando/riptide/httpclient/metrics/package-info.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '993134'}, {'name': 'Shell', 'bytes': '1050'}]} |
layout: page
title: Champion Tech Media Award Ceremony
date: 2016-05-24
author: Scott Wolf
tags: weekly links, java
status: published
summary: Integer enim sem, vestibulum id.
banner: images/banner/meeting-01.jpg
booking:
startDate: 02/20/2016
endDate: 02/23/2016
ctyhocn: TTNHRHX
groupCode: CTMAC
published: true
---
Pellentesque dui sem, ornare eget tempor vitae, accumsan ac velit. Morbi varius magna nibh, non vehicula nunc mollis congue. Integer dignissim viverra ante, ac ullamcorper odio. Cras semper sagittis tincidunt. Donec posuere facilisis nibh vel bibendum. Etiam congue sed mauris et pretium. Quisque auctor ex elit, in blandit ipsum accumsan sit amet.
Phasellus finibus nunc a magna varius volutpat. Ut imperdiet, orci sit amet condimentum ultrices, nisl lacus tincidunt ligula, ut dignissim ante metus in sapien. Pellentesque accumsan varius leo in ornare. Vivamus a sem sed neque congue volutpat. Donec auctor turpis eu leo tempus, quis posuere ex suscipit. Proin efficitur velit metus, non consequat justo eleifend sed. Cras id ultricies magna, sit amet lacinia lorem. Etiam a pellentesque nisl. Sed sapien nisl, commodo eget dictum a, condimentum non velit. Suspendisse ut gravida urna. Vivamus elementum maximus neque, quis pellentesque massa. Nunc pretium auctor malesuada. Aliquam tempus auctor imperdiet. Sed condimentum ante non pellentesque accumsan. Sed ornare suscipit nulla, ac semper justo dignissim sit amet.
1 Integer porttitor purus ac malesuada laoreet
1 Cras consectetur massa vel eleifend rutrum.
Nullam sed euismod nulla, a pretium justo. Cras vehicula eget mauris maximus tristique. Cras elementum ipsum odio, a egestas enim pretium id. Morbi euismod tellus ut varius suscipit. Nullam mollis ex nisi, ac commodo metus maximus faucibus. Vestibulum feugiat purus consectetur urna mollis congue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum pulvinar augue ac felis semper efficitur.
| {'content_hash': '9804555f59ec99957bc36078b2a3ffca', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 771, 'avg_line_length': 90.04545454545455, 'alnum_prop': 0.8127208480565371, 'repo_name': 'KlishGroup/prose-pogs', 'id': '692e527e1a1c7614cbaaee2e968568f389422752', 'size': '1985', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': 'pogs/T/TTNHRHX/CTMAC/index.md', 'mode': '33188', 'license': 'mit', 'language': []} |
namespace IPFilter.Models
{
public enum CompressionFormat
{
None = 0,
GZip = 1,
Zip = 2
}
} | {'content_hash': 'e489d64e5de5401e8b0c8ffcf867f999', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 33, 'avg_line_length': 14.11111111111111, 'alnum_prop': 0.5039370078740157, 'repo_name': 'DavidMoore/ipfilter', 'id': '4bca8c4c1e67881f3908b8080f70ceeaab1f1d52', 'size': '127', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Code/IPFilter/Models/CompressionFormat.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '464873'}]} |
#ifndef VOMS_DOIO_H
#define VOMS_DOIO_H
#include <stdarg.h>
extern char *snprintf_wrap(const char *format, ...);
extern char *vsnprintf_wrap(const char *format, va_list v);
#endif
| {'content_hash': '6d52f8079fb8a6a04ea0a16f742a7412', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 59, 'avg_line_length': 18.4, 'alnum_prop': 0.7119565217391305, 'repo_name': 'ellert/canl-c', 'id': '05272167d95e04c36875ccfb71fc343118df9773', 'size': '1260', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/proxy/doio.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '411414'}, {'name': 'Lex', 'bytes': '3998'}, {'name': 'Makefile', 'bytes': '6450'}, {'name': 'Perl', 'bytes': '2009'}, {'name': 'Yacc', 'bytes': '7890'}]} |
{-# LANGUAGE OverloadedStrings #-}
module Treecreeper where
import Text.Parsec.Combinator
import Text.Parsec.Prim
import Text.Parsec.Char
import Text.Parsec.String
import Data.Text (Text)
import Data.Tree hiding (subForest)
import Data.Time (UTCTime)
import Data.Monoid (mconcat)
import System.Environment (getArgs)
import Control.Exception (catch, SomeException)
import Control.Monad.Identity (Identity, liftM2)
import Control.Applicative ((*>), (<*), (<$>), (<*>))
--------------------------------------------------------------------------------
-- --
-- Function definitions --
-- --
--------------------------------------------------------------------------------
forest :: Parser (Forest String)
forest = node `initBy1` nodeToken
node :: Parser (Tree String)
node = Node <$> value <*> (try (descendToken *> subForest <* ascendToken) <|> return [])
<?> "empty node encountered."
value :: Parser String
value = try (anyChar `many1Till` (noConsume stopTokens)) <|>
(anyChar `many1Till` eof)
where stopTokens = choice [nodeToken, descendToken, ascendToken]
-- allows an empty subforest, but's that intended.
subForest :: Parser (Forest String)
subForest = (nodeToken *> node) `manyTill` (noConsume ascendToken)
mkToken :: String -> Parser String
mkToken str = try $ withSpaces (string str <* notFollowedBy alphaNum)
nodeToken :: Parser String
nodeToken = mkToken ":node"
descendToken :: Parser String
descendToken = mkToken ":descend"
ascendToken :: Parser String
ascendToken = mkToken ":ascend"
withSpaces :: Parser a -> Parser a
withSpaces p = spaces *> p <* spaces
--------------------------------------------------------------------------------
-- --
-- Function definitions that should be in the official Parsec API... --
-- --
--------------------------------------------------------------------------------
initBy1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a]
initBy1 p sep = many1 (sep >> p)
many1Till :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a]
many1Till p end = scan
where scan = do
x <- p
do { end *> return [x] } <|> do { xs <- scan; return (x:xs) }
noConsume :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m a
noConsume = try . lookAhead
--------------------------------------------------------------------------------
-- --
-- Main --
-- --
--------------------------------------------------------------------------------
main = do
args <- getArgs
let fileName =
case args of
(a:as) -> a
_ -> "testinput.txt"
input <- catch (readFile fileName) $
\err -> do
print (err :: SomeException)
return ""
putStr input
| {'content_hash': '80776dad623dae3781873eb4251a6e35', 'timestamp': '', 'source': 'github', 'line_count': 91, 'max_line_length': 88, 'avg_line_length': 37.010989010989015, 'alnum_prop': 0.4328978622327791, 'repo_name': 'obscaenvs/treecreeper', 'id': 'e5e8ffd72006fad8532977a93baa369772327d04', 'size': '3368', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Treecreeper.hs', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Haskell', 'bytes': '3368'}]} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Monadenium hedigerianum Malaisse
### Remarks
null | {'content_hash': 'deed282d545daa7279ff2395a1d82dee', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 12.461538461538462, 'alnum_prop': 0.7345679012345679, 'repo_name': 'mdoering/backbone', 'id': 'f375a66c0fe57f3cebfbb6c0c7bc7c01418e25cf', 'size': '225', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Euphorbia/Euphorbia hedigeriana/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
\documentclass{article}
\usepackage[pdftex,active,tightpage]{preview}
\setlength\PreviewBorder{2mm}
\usepackage{pgfplots}
\usepackage{tikz}
\usetikzlibrary{arrows, positioning, calc}
\begin{document}
\begin{preview}
\begin{tikzpicture}
\begin{axis}[
axis x line=middle,
axis y line=left,
enlarge y limits=true,
xmode=log, % Logarithmic x axis
xmin=0.01, xmax=1, % Positive domain...
xticklabel=\pgfmathparse{exp(\tick)}\pgfmathprintnumber{\pgfmathresult},
xticklabel style={/pgf/number format/.cd,fixed}, % Use fixed point notation
width=15cm, height=8cm, % size of the image
grid = major,
grid style={dashed, gray!30},
ymin=-1, % start the diagram at this y-coordinate
ymax= 1, % end the diagram at this y-coordinate
axis background/.style={fill=white},
ylabel=$y$,
xlabel=$x$,
legend style={at={(0.9,0.95)}, anchor=north}
]
\addplot[domain=0.01:1, red, thick,samples=2000] {-sin(deg(1/(x)))};
\legend{$\sin(\frac{1}{x})$}
\end{axis}
\end{tikzpicture}
\end{preview}
\end{document}
| {'content_hash': 'f8360f25c72ac3afe72d8e98a1644a90', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 83, 'avg_line_length': 32.05555555555556, 'alnum_prop': 0.6239168110918544, 'repo_name': 'MartinThoma/LaTeX-examples', 'id': '0836fa2b6eae9a570409d1f08043f9f9e4b1c0ff', 'size': '1154', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tikz/sin(1divx)/sin(1divx).tex', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '104'}, {'name': 'Asymptote', 'bytes': '16054'}, {'name': 'Batchfile', 'bytes': '187'}, {'name': 'C', 'bytes': '7885'}, {'name': 'Gnuplot', 'bytes': '383'}, {'name': 'HTML', 'bytes': '10585'}, {'name': 'Haskell', 'bytes': '9401'}, {'name': 'Java', 'bytes': '95574'}, {'name': 'JavaScript', 'bytes': '33665'}, {'name': 'Jupyter Notebook', 'bytes': '15400'}, {'name': 'Makefile', 'bytes': '403103'}, {'name': 'Prolog', 'bytes': '4515'}, {'name': 'Python', 'bytes': '58056'}, {'name': 'Raku', 'bytes': '357'}, {'name': 'Scala', 'bytes': '6990'}, {'name': 'Shell', 'bytes': '2783'}, {'name': 'ShellSession', 'bytes': '3837'}, {'name': 'Smarty', 'bytes': '572'}, {'name': 'Tcl', 'bytes': '250'}, {'name': 'TeX', 'bytes': '5244843'}, {'name': 'X10', 'bytes': '2354'}]} |
#include "ExtensionExporter.hpp"
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <VoxieBackend/IO/Operation.hpp>
#include <VoxieBackend/IO/OperationRegistry.hpp>
#include <VoxieBackend/IO/OperationResult.hpp>
#include <VoxieBackend/Component/Extension.hpp>
#include <VoxieBackend/Component/ExternalOperation.hpp>
using namespace vx;
using namespace vx::io;
QSharedPointer<vx::io::ExtensionExporter> vx::io::parseExporter(
const QJsonObject& json) {
QString name = json["Name"].toString();
QString displayName = json["DisplayName"].toString();
QString description = json["Description"].toString();
QList<QString> patterns;
for (const auto& entry : json["Patterns"].toArray())
patterns << entry.toString();
QList<QString> targetPrototypeNames;
for (const auto& targetName : json["TargetPrototypeNames"].toArray())
targetPrototypeNames << targetName.toString();
(void)description; // TODO: use description?
FilenameFilter filter(displayName, patterns);
auto exporter =
makeSharedQObject<ExtensionExporter>(name, filter, targetPrototypeNames);
exporter->setSelf(exporter);
return exporter;
}
ExtensionExporter::ExtensionExporter(const QString& name,
const FilenameFilter& filter,
const QList<QString>& targetPrototypeNames)
: Exporter(name, filter, targetPrototypeNames) {}
ExtensionExporter::~ExtensionExporter() {}
QSharedPointer<OperationResult> ExtensionExporter::exportData(
const QSharedPointer<vx::Data>& data, const QString& fileName) {
auto op = Operation::create();
auto result = OperationResult::create(op);
op->setDescription("Export " + fileName);
OperationRegistry::instance()->addOperation(op);
auto exOp =
ExternalOperationExport::create(op, fileName, "Export " + fileName, data);
auto ext = qSharedPointerDynamicCast<Extension>(this->container());
// Should always be in an extension
if (!ext) {
throw Exception("de.uni_stuttgart.Voxie.InternalError",
"extension is nullptr in exportData()");
}
// if (debuggerSupportEnabled->isChecked())
// ext->startOperationDebug(exOp);
// else
ext->startOperation(exOp);
return result;
}
| {'content_hash': 'b8544081f6363998a3e6734e759c7a65', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 80, 'avg_line_length': 32.7536231884058, 'alnum_prop': 0.7123893805309734, 'repo_name': 'voxie-viewer/voxie', 'id': '287b7d23b883fb910a8a46e2d594d11b2f8df764', 'size': '3386', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/VoxieBackend/Component/ExtensionExporter.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '151'}, {'name': 'C', 'bytes': '582785'}, {'name': 'C++', 'bytes': '1860251'}, {'name': 'CMake', 'bytes': '1934'}, {'name': 'JavaScript', 'bytes': '3194'}, {'name': 'Makefile', 'bytes': '2053'}, {'name': 'Python', 'bytes': '36220'}, {'name': 'QMake', 'bytes': '20169'}, {'name': 'Shell', 'bytes': '2367'}]} |
package com.github.racc.tscg;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import com.github.racc.tscg.reflectors.fastclasspathscanner.FastClasspathScanningReflector;
import com.github.racc.tscg.reflectors.reflections.ReflectionsReflector;
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner;
import org.reflections.Reflections;
import org.reflections.scanners.FieldAnnotationsScanner;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.MethodParameterScanner;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Key;
import com.google.inject.Module;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigBeanFactory;
import com.typesafe.config.ConfigObject;
import com.typesafe.config.ConfigValue;
import com.typesafe.config.ConfigValueType;
/**
* Include this {@link Module} in your {@link Guice} bootstrapping to Automagically
* get bindings to your {@link TypesafeConfig} annotated configuration parameters.
*
* @author jason
*/
public class TypesafeConfigModule extends AbstractModule {
private final Config config;
private final Reflector reflections;
private final Set<TypesafeConfig> boundAnnotations;
private TypesafeConfigModule(Config config, Reflector reflections) {
this.config = config;
this.reflections = reflections;
this.boundAnnotations = new HashSet<TypesafeConfig>();
}
/**
* Essentially calls fromConfigWithPackage with a package name of "" to construct a TypesafeConfigModule.
*
* @param config the config to use.
* @return The constructed TypesafeConfigModule.
* @deprecated this is deprecated as there is a known issue with scanning the classpath for annotations
* in this mode, when running a packaged jar file.
* use {@link #fromConfigWithPackage(Config, String)} instead and limit the packages to scan.
*/
@Deprecated
public static TypesafeConfigModule fromConfig(Config config) {
return fromConfigWithPackage(config, "");
}
/**
* Scans the specified packages for annotated classes, and applies Config values to them.
*
* @param config the Config to derive values from
* @param packageNamePrefix the prefix to limit scanning to - e.g. "com.github"
* @return The constructed TypesafeConfigModule.
*/
public static TypesafeConfigModule fromConfigWithPackage(Config config, String packageNamePrefix) {
Reflections reflections = createPackageScanningReflections(packageNamePrefix);
return fromConfigWithReflections(config, reflections);
}
/**
* Scans the specified packages for annotated classes, and applies Config values to them.
*
* @param config the Config to derive values from
* @param reflections the reflections object to use
* @return The constructed TypesafeConfigModule.
*/
public static TypesafeConfigModule fromConfigWithReflections(Config config, Reflections reflections) {
return new TypesafeConfigModule(config, new ReflectionsReflector(reflections));
}
/**
* Scans the specified packages for annotated classes, and applies Config values to them.
*
* @param config the Config to derive values from
* @return The constructed TypesafeConfigModule.
*/
public static TypesafeConfigModule fromConfigUsingClasspathScanner(Config config, String ...scannerSpec) {
return new TypesafeConfigModule(config, new FastClasspathScanningReflector(scannerSpec));
}
public static Reflections createPackageScanningReflections(String packageNamePrefix){
ConfigurationBuilder configBuilder =
new ConfigurationBuilder()
.filterInputsBy(new FilterBuilder().includePackage(packageNamePrefix))
.setUrls(ClasspathHelper.forPackage(packageNamePrefix))
.setScanners(
new TypeAnnotationsScanner(),
new MethodParameterScanner(),
new MethodAnnotationsScanner(),
new FieldAnnotationsScanner()
);
return new Reflections(configBuilder);
}
@SuppressWarnings({ "rawtypes"})
@Override
protected void configure() {
Set<Constructor> annotatedConstructors = reflections.getConstructorsWithAnyParamAnnotated(TypesafeConfig.class);
for (Constructor c : annotatedConstructors) {
Parameter[] params = c.getParameters();
bindParameters(params);
}
Set<Method> annotatedMethods = reflections.getMethodsWithAnyParamAnnotated(TypesafeConfig.class);
for (Method m : annotatedMethods) {
Parameter[] params = m.getParameters();
bindParameters(params);
}
Set<Field> annotatedFields = reflections.getFieldsAnnotatedWith(TypesafeConfig.class);
for (Field f : annotatedFields) {
TypesafeConfig annotation = f.getAnnotation(TypesafeConfig.class);
bindValue(f.getType(), f.getAnnotatedType().getType(), annotation);
}
}
private void bindParameters(Parameter[] params) {
for (Parameter p : params) {
if (p.isAnnotationPresent(TypesafeConfig.class)) {
TypesafeConfig annotation = p.getAnnotation(TypesafeConfig.class);
bindValue(p.getType(), p.getAnnotatedType().getType(), annotation);
}
}
}
private void bindValue(Class<?> paramClass, Type paramType, TypesafeConfig annotation) {
// Prevents multiple bindings on the same annotation
if (!boundAnnotations.contains(annotation)) {
@SuppressWarnings("unchecked")
Key<Object> key = (Key<Object>) Key.get(paramType, annotation);
String configPath = annotation.value();
Object configValue = getConfigValue(paramClass, paramType, configPath);
bind(key).toInstance(configValue);
boundAnnotations.add(annotation);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Object getConfigValue(Class<?> paramClass, Type paramType, String path) {
Optional<Object> extractedValue = ConfigExtractors.extractConfigValue(config, paramClass, path);
if (extractedValue.isPresent()) {
return extractedValue.get();
}
ConfigValue configValue = config.getValue(path);
ConfigValueType valueType = configValue.valueType();
if (valueType.equals(ConfigValueType.OBJECT) && Map.class.isAssignableFrom(paramClass)) {
ConfigObject object = config.getObject(path);
return object.unwrapped();
} else if (valueType.equals(ConfigValueType.OBJECT)) {
Object bean = ConfigBeanFactory.create(config.getConfig(path), paramClass);
return bean;
} else if (valueType.equals(ConfigValueType.LIST) && List.class.isAssignableFrom(paramClass)) {
Type listType = ((ParameterizedType) paramType).getActualTypeArguments()[0];
Optional<List<?>> extractedListValue =
ListExtractors.extractConfigListValue(config, listType, path);
if (extractedListValue.isPresent()) {
return extractedListValue.get();
} else {
List<? extends Config> configList = config.getConfigList(path);
return configList.stream()
.map(cfg -> {
Object created = ConfigBeanFactory.create(cfg, (Class) listType);
return created;
})
.collect(Collectors.toList());
}
}
throw new RuntimeException("Cannot obtain config value for " + paramType + " at path: " + path);
}
} | {'content_hash': '4640de1a2f1d1200d123fce162f686ea', 'timestamp': '', 'source': 'github', 'line_count': 196, 'max_line_length': 114, 'avg_line_length': 38.494897959183675, 'alnum_prop': 0.7683233929754805, 'repo_name': 'racc/typesafeconfig-guice', 'id': 'e21c567991fcb8c80f6c14333a322fe84ddaaa5f', 'size': '7545', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/github/racc/tscg/TypesafeConfigModule.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '57000'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>projective-geometry: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.2~camlp4 / projective-geometry - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
projective-geometry
<small>
8.10.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-08 00:01:27 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-08 00:01:27 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp4 4.03+1 Camlp4 is a system for writing extensible parsers for programming languages
conf-findutils 1 Virtual package relying on findutils
conf-which 1 Virtual package relying on which
coq 8.5.2~camlp4 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.03.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.03.0 Official 4.03.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlbuild 0.14.2 OCamlbuild is a build system with builtin rules to easily build most OCaml projects
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/projective-geometry"
license: "GPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ProjectiveGeometry"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: geometry"
"keyword: projective"
"keyword: Fano"
"keyword: homogeneous coordinates model"
"keyword: flat"
"keyword: rank"
"keyword: Desargues"
"keyword: Moulton"
"category: Mathematics/Geometry/General"
"date: 2009-10"
]
authors: [
"Nicolas Magaud <[email protected]>"
"Julien Narboux <[email protected]>"
"Pascal Schreck <[email protected]>"
]
bug-reports: "https://github.com/coq-contribs/projective-geometry/issues"
dev-repo: "git+https://github.com/coq-contribs/projective-geometry.git"
synopsis: "Projective Geometry"
description: """
This contributions contains elements of formalization of projective geometry.
In the plane:
Two axiom systems are shown equivalent. We prove some results about the
decidability of the the incidence and equality predicates. The classic
notion of duality between points and lines is formalized thanks to a
functor. The notion of 'flat' is defined and flats are characterized.
Fano's plane, the smallest projective plane is defined. We show that Fano's plane is desarguesian.
In the space:
We prove Desargues' theorem."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/projective-geometry/archive/v8.10.0.tar.gz"
checksum: "md5=d6807a8a37bfd7aee33f251ef1709f54"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-projective-geometry.8.10.0 coq.8.5.2~camlp4</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.2~camlp4).
The following dependencies couldn't be met:
- coq-projective-geometry -> coq >= 8.10 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-projective-geometry.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {'content_hash': '7cf576d0c15d4dd29ec81176df213bfc', 'timestamp': '', 'source': 'github', 'line_count': 187, 'max_line_length': 159, 'avg_line_length': 42.54545454545455, 'alnum_prop': 0.5725238813474107, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'b5e41bfa4f78a25d3c4ba31ef921691f0d709e88', 'size': '7981', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.03.0-2.0.5/released/8.5.2~camlp4/projective-geometry/8.10.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
static NSString* const kKTSecretViewControllerTextViewPlaceholderText = @"Share a thought";
static CGFloat const kKTSecretTextViewDefaultContainerInsetFromTop = 150.0f;
static CGFloat const kKTSecretTextViewDefaultContainerInsetFromTopMinimum = 30.9f;
static NSUInteger const kKTSecretTextViewMaxNumberOfLines = 10;
static UIEdgeInsets const kKTSecretTextViewDefaultTextContainerInset = {kKTSecretTextViewDefaultContainerInsetFromTop, 10.0f, 20.0f, 10.0f};
@interface KTSecretTextView()<
UITextViewDelegate
>
@property (nonatomic) CGFloat defaultSingleLineHeight;
@property (nonatomic, strong) NSDictionary *textAttributes;
@end
@implementation KTSecretTextView
#pragma mark - Public
- (instancetype)init
{
if (self = [super init]) {
self.delegate = self;
self.textAlignment = NSTextAlignmentCenter;
self.backgroundColor = [UIColor clearColor];
self.tintColor = [UIColor whiteColor];
self.autocorrectionType = UITextAutocorrectionTypeNo;
self.text = kKTSecretViewControllerTextViewPlaceholderText;
[self setupDefaultContentInset];
}
return self;
}
- (void)setText:(NSString *)text
{
self.attributedText = [[NSAttributedString alloc] initWithString:text attributes:self.textAttributes];
}
#pragma mark - Override
- (void)setTintColor:(UIColor *)tintColor
{
[super setTintColor:tintColor];
self.textColor = tintColor;
}
#pragma mark - Private
#pragma mark - Private properties
- (NSDictionary*)textAttributes
{
if (!_textAttributes) {
NSMutableParagraphStyle *paragrahStyle = [NSMutableParagraphStyle new];
paragrahStyle.lineSpacing = 6.0f;
paragrahStyle.alignment = NSTextAlignmentCenter;
NSShadow *shadow = [NSShadow new];
shadow.shadowColor = [UIColor blackColor];
shadow.shadowOffset = CGSizeMake(1, 1);
shadow.shadowBlurRadius = 2.0f;
_textAttributes = @{
NSFontAttributeName: [UIFont fontWithName:@"AvenirNextCondensed-Medium" size:22.0f],
NSParagraphStyleAttributeName: paragrahStyle,
NSForegroundColorAttributeName: [UIColor whiteColor],
NSShadowAttributeName: shadow
};
}
return _textAttributes;
}
#pragma mark - Initialization Helpers
- (void)setupDefaultContentInset
{
self.textContainerInset = kKTSecretTextViewDefaultTextContainerInset;
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView *viewToReceiveTouch = nil;
CGRect rectForCurrentText = [self.layoutManager usedRectForTextContainer:self.textContainer];
rectForCurrentText.origin.x += self.textContainerInset.left;
rectForCurrentText.origin.y += self.textContainerInset.top;
if (!CGRectContainsPoint(rectForCurrentText, point)) {
viewToReceiveTouch = [self.secretTextViewDelegate secretTextView:self viewForHitTest:point withEvent:event];
if (self.isFirstResponder) {
[self resignFirstResponder];
}
}
// consume event if delegate doesnt provide a view or is inside tect
if (!viewToReceiveTouch) {
viewToReceiveTouch = self;
}
return viewToReceiveTouch;
}
#pragma mark - UITextViewDelegate methods
-(void)textViewDidBeginEditing:(UITextView *)textView
{
NSString *text = textView.text;
if ([text isEqualToString:kKTSecretViewControllerTextViewPlaceholderText]) {
// clear placeholder text
textView.text = @"";
// save the line height for single line text for calculation
[self updateSingleLineHeightFromTextContainer];
}
}
-(void)textViewDidEndEditing:(UITextView *)textView
{
// reset to placeholder text if empty
NSString *text = textView.text;
if (![text length]) {
textView.text = kKTSecretViewControllerTextViewPlaceholderText;
}
}
- (void)textViewDidChange:(UITextView *)textView
{
[self updateContentInsetOnContentChange:textView];
if ([self.secretTextViewDelegate respondsToSelector:@selector(secretTextView:textViewDidChange:)]) {
[self.secretTextViewDelegate secretTextView:self textViewDidChange:textView];
}
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
BOOL shouldChangeText = YES;
CGRect rectForCurrentText = [self.layoutManager usedRectForTextContainer:self.textContainer];
NSUInteger numberOfLines = round(rectForCurrentText.size.height/self.defaultSingleLineHeight);
// do not allow adding new text if reached maximum line limit
if (numberOfLines > kKTSecretTextViewMaxNumberOfLines) {
if ([text length]) {
shouldChangeText = NO;
}
}
return shouldChangeText;
}
#pragma makr - text container resize methods
- (void)updateSingleLineHeightFromTextContainer
{
// save default single line height which is useful for calculating insets later on
CGRect rectForCurrentText = [self.layoutManager usedRectForTextContainer:self.textContainer];
self.defaultSingleLineHeight = rectForCurrentText.size.height;
}
- (void)updateContentInsetOnContentChange:(UITextView *)textView
{
CGRect rectForCurrentText = [self.layoutManager usedRectForTextContainer:self.textContainer];
CGFloat containerInsetFromTop = kKTSecretTextViewDefaultContainerInsetFromTop;
UIEdgeInsets containerInsets = kKTSecretTextViewDefaultTextContainerInset;
NSUInteger numberOfLines = round(rectForCurrentText.size.height/self.defaultSingleLineHeight);
// when text starts to fill up the textview, change the content inset allowing the text to move up
if (numberOfLines > 2) {
containerInsetFromTop = numberOfLines*self.defaultSingleLineHeight + kKTSecretTextViewDefaultContainerInsetFromTopMinimum;
}
// set to default value if calculation went beyond or below alloweed thresholds
if ( (containerInsetFromTop < kKTSecretTextViewDefaultContainerInsetFromTopMinimum) ||
(containerInsetFromTop > kKTSecretTextViewDefaultContainerInsetFromTop) ){
containerInsetFromTop = kKTSecretTextViewDefaultContainerInsetFromTopMinimum;
}
containerInsets.top = containerInsetFromTop;
self.textContainerInset = containerInsets;
}
@end
| {'content_hash': '56947a6463632e9349358e23be245e03', 'timestamp': '', 'source': 'github', 'line_count': 187, 'max_line_length': 140, 'avg_line_length': 34.1283422459893, 'alnum_prop': 0.7295518646192416, 'repo_name': 'kenshin03/KTSecretTextView', 'id': '662a92266e44309812dfa0ce8c74eea8e432258b', 'size': '6650', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'SecretTextView/KTSecretTextView.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '78661'}, {'name': 'Ruby', 'bytes': '1053'}]} |
package com.eason.springmvc.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by feng yingsheng on 10/3/2017.
*/
@Slf4j
public class MyInterceptor extends HandlerInterceptorAdapter {
public MyInterceptor() {
super();
log.info("myInterceptor now is created...");
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("myInterceptor preHandle now...");
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("myInterceptor posthandle now.....");
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("myInterceptor afterCompletion now....");
super.afterCompletion(request, response, handler, ex);
}
@Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("myInterceptor afterConcurrentHandlingStarted now....");
super.afterConcurrentHandlingStarted(request, response, handler);
}
}
| {'content_hash': '87d2bd56de531614a0216b863d7262cf', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 146, 'avg_line_length': 38.674418604651166, 'alnum_prop': 0.7492483463619964, 'repo_name': 'EasonFeng5870/core', 'id': '8220b62bc25364018268f086434800c763611f09', 'size': '1663', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'springmvc/src/main/java/com/eason/springmvc/interceptor/MyInterceptor.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '1180433'}, {'name': 'Java', 'bytes': '134264'}]} |
define(["jquery",
"underscore",
"socket-io",
"office",
"handlebars",
"helpers",
"admin/global-config",
"admin/modules-kinds",
"admin/grid-occupation",
"hbs!templates/modules-dashboard",
"hbs!templates/module-delete",
"hbs!templates/modules-dashboard-module",
"text!templates/modules-dashboard-module.hbs",
"hbsCustomHelpers",
"constants"],
function ($, _, io,
Office,
Handlebars,
Helpers,
globalConfigManager, modulesKindsManager,
gridOccupation,
modulesDashboardTemplate, moduleDeleteTemplate, modulesDashboardModuleTemplate,
modulesDashboardModuleTemplateRaw)
{
// DOM elements
var el = $("#admin");
var topEl = el.find(".top");
var centerEl = el.find(".center");
var bottomEl = el.find(".bottom");
var dashboardEl = centerEl.find(".admin-dashboard-instances");
var adminModule = null; // reference to current admin module (modal window)
var modulesInstances = [];
Handlebars.registerPartial("dashboard-module", modulesDashboardModuleTemplateRaw);
/*
* grid cols & rows changes
*/
globalConfigManager.listenToGridSizeChange(function () {
socket.emit(Events.ADMIN_SAVE_GLOBAL_CONF, globalConfigManager.getConfig());
gridOccupation.setGridSize(globalConfigManager.get("grid"));
resizeDashBoardGrid();
});
/*
*
*/
var addModuleToGrid = function(type, position) {
var moduleConstantConfig = modulesKindsManager.getByType(type);
// we need to clone the config object in order to not alter our modulesList
var moduleConstantConfigClone = _.clone(moduleConstantConfig);
moduleConstantConfigClone["position"] = position;
moduleConstantConfigClone["size"] = { "w": 1, "h": 1 }; // default size
require(["modules/" + type + "/admin/admin"], function (AdminModule) {
el.addClass("fade");
adminModule = new AdminModule(moduleConstantConfigClone, $("body"), socket, function() {
el.removeClass("fade");
adminModule = null;
$(".module-admin").remove();
});
});
};
/*
* Drag & Drop management : enable drop on dashboard
*/
gridOccupation.listenToDrop(function(e, data) {
if (data["operation"]) {
var targetCell = $(e.target);
var position = {
"x": targetCell.data("x"),
"y": targetCell.data("y")
}
// add a new module to the dashboard
if (data["operation"] === "add") {
console.debug("drop a module of type " + data["type"]);
addModuleToGrid(data["type"], position);
}
// move module instance inside the dashboard
else if(data["operation"] === "move") {
var moduleId = data["id"];
var offset = data["offset"];
// apply offset from inside module click coordinates
if(offset) {
position["x"] -= offset["x"];
position["y"] -= offset["y"];
}
if(position["x"] < 1) {
position["x"] = 1;
}
if(position["y"] < 1) {
position["y"] = 1;
}
// update the module instance conf
var moduleConfig = getModule(moduleId);
if(moduleConfig) {
moduleConfig["position"] = position;
}
else {
console.debug("module not found");
}
// push the conf to the server
socket.emit(Events.ADMIN_ADD_OR_UPDATE_MODULE_INSTANCE, moduleConfig);
}
// move module instance inside the dashboard
else if(data["operation"] === "resize") {
// do nothing
}
}
else {
console.debug("no operation to perform");
}
});
/*
* Web Socket events
*/
var socket = io.connect(window.office.node_server_url);
socket.on('connect', function () {
socket.emit(Events.ADMIN_GET_GLOBAL_CONF);
});
socket.on(Events.ADMIN_SEND_GLOBAL_CONF, function (config) {
globalConfigManager.setConfig(config);
gridOccupation.setGridSize(globalConfigManager.get("grid"));
resizeDashBoardGrid();
socket.emit(Events.ADMIN_GET_MODULE_KINDS);
socket.emit(Events.ADMIN_GET_MODULE_INSTANCES);
});
socket.on(Events.ADMIN_SEND_MODULE_KINDS, function (modules) {
console.log("admin received modules kinds");
modulesKindsManager.setModulesList(modules);
modulesKindsManager.listenToDragOperation();
// Handle singleton add by click on + buttons
modulesKindsManager.setAddSingletonHandler(function(e) {
var type = $(e.currentTarget).data("type");
addModuleToGrid(type, {});
});
});
socket.on(Events.ADMIN_SEND_MODULE_INSTANCES, function (modules) {
console.log("admin received modules instances");
modulesInstances = modules;
modulesKindsManager.setSingletonsList(modules.filter(function(mod) {
return mod["singleton"];
}).map(function(mod) {
return mod["type"];
})
);
// display dashboard with regular modules previews
dashboardEl.html(modulesDashboardTemplate({
"modules": modules.filter(function(module) {
return !module["dock"];
})
}));
gridOccupation.setModulesInstances(modules);
// docked modules
centerEl.css("height", "100%");
centerEl.css("top", "0");
topEl.html("");
bottomEl.html("");
modules.forEach(function(module) {
if(module["dock"]) {
if(module["dock"] === "top") {
topEl.html(modulesDashboardModuleTemplate(module));
centerEl.css("height", "90%");
centerEl.css("top", topEl.height() + "px");
}
else if(module["dock"] === "bottom") {
bottomEl.html(modulesDashboardModuleTemplate(module));
centerEl.css("height", "90%");
}
}
});
// resize cursor hover of module borders
var instancesEl = dashboardEl.find(".module");
instancesEl.bind("mouseover", function (e) {
var mod = $(e.target);
if(mod.hasClass("module")) {
if(e.originalEvent.offsetX >= (mod.width() - 10)) {
mod.css("cursor", "w-resize");
}
else if(e.originalEvent.offsetY >= (mod.height() - 10)) {
mod.css("cursor", "n-resize");
}
}
});
// we use drag n drop for module resize
var dragIcon = window.document.getElementById("resize");
var dragOffsetX = 0, dragOffsetY = 0;
var modWidth = 0, modHeight = 0;
var unitWidth = 0, unitHeight = 0;
instancesEl.bind("dragstart", function (e) {
var mod = $(e.target);
if(mod.hasClass("module")) {
e.originalEvent.dataTransfer.setData("text/plain", JSON.stringify({
"id": $(this).attr("id"),
"operation": "resize"
}));
mod.addClass("resize");
e.originalEvent.dataTransfer.setDragImage(dragIcon, -10, -10);
modWidth = mod.width();
modHeight = mod.height();
unitWidth = dashboardEl.width() / globalConfigManager.get("grid")["columns"];
unitHeight = Math.round(modHeight / mod.data("h"));
dragOffsetX = modWidth - e.originalEvent.offsetX;
dragOffsetY = modHeight - e.originalEvent.offsetY;
}
});
// live resizing
instancesEl.bind("drag", function (e) {
var mod = $(e.target);
if(mod.hasClass("module") && mod.hasClass("resize")) {
if(dragOffsetX < 10) {
mod.width(e.originalEvent.offsetX + dragOffsetX);
}
if(dragOffsetY < 10) {
mod.height(e.originalEvent.offsetY + dragOffsetY);
}
}
});
// we compute new size and push the size to the backend
instancesEl.bind("dragend", function (e) {
var mod = $(e.target);
if(mod.hasClass("module") && mod.hasClass("resize")) {
mod.removeClass("resize");
var size = {};
// compute new size dimensions
if(dragOffsetX < 10) {
size["w"] = Math.round((e.originalEvent.offsetX + dragOffsetX) / unitWidth);
if(size["w"] <= 0) {
size["w"] = 1;
}
}
if(dragOffsetY < 10) {
size["h"] = Math.round((e.originalEvent.offsetY + dragOffsetY) / unitHeight);
if(size["h"] <= 0) {
size["h"] = 1;
}
}
// complete size missing dimension of module
if(!size["w"]) {
size["w"] = mod.data("w");
}
if(!size["h"]) {
size["h"] = mod.data("h");
}
// set new module size
var moduleConfig = getModule(mod.attr("id"));
if(moduleConfig) {
moduleConfig["size"] = size;
}
else {
console.debug("module not found");
}
// push the conf to the server
socket.emit(Events.ADMIN_ADD_OR_UPDATE_MODULE_INSTANCE, moduleConfig);
// reset temp vars
dragOffsetX = dragOffsetY = modWidth = modHeight = unitWidth = unitHeight = 0;
}
});
// prevent drop on existing modules
var instancesInnerEl = dashboardEl.find(".module-inner");
instancesInnerEl.unbind("dragover");
instancesInnerEl.bind("dragover", function (e) {
e.stopImmediatePropagation();
e.originalEvent.dataTransfer.effectAllowed = 'none';
e.originalEvent.dataTransfer.dropEffect = 'none';
return false;
});
// enable drag of module instances
instancesInnerEl.unbind("dragstart");
instancesInnerEl.bind("dragstart", function (e) {
var mod = $(e.target).parent();
mod.addClass("move");
// compute local module click x/y
var startX = e.originalEvent.pageX - mod.position()["left"];
var startY = e.originalEvent.pageY - mod.position()["top"];
var insidePosition = computeGridPosition(mod.data("w"), mod.data("h"), mod.width(), mod.height(), startX, startY);
var offset = {
"x": insidePosition["x"] - 1,
"y": insidePosition["y"] - 1
}
mod.data("offsetX", offset["x"]);
mod.data("offsetY", offset["y"]);
e.originalEvent.dataTransfer.setData("text/plain", JSON.stringify({
"id": mod.attr("id"),
"operation": "move",
"offset": offset
}));
});
instancesInnerEl.unbind("dragend");
instancesInnerEl.bind("dragend", function (e) {
var mod = $(e.target);
mod.removeClass("move");
});
// Listener - click on administrate button and display modal
var adminButtons = el.find(".module button.admin");
adminButtons.unbind("click");
adminButtons.click(function () {
if (!adminModule) {
var type = $(this).parents("div.module").data("type");
var id = $(this).parents("div.module").attr("id");
var moduleConfig = getModule(id);
if (moduleConfig) {
require(["modules/" + type + "/admin/admin"], function (AdminModule) {
el.append($("<div/>", { "class": "fade" }));
adminModule = new AdminModule(moduleConfig, $("body"), socket, function() {
el.find(".fade").remove();
adminModule = null;
$(".module-admin").remove();
});
});
}
else {
console.warn("no admin for " + type + " module");
}
}
});
// Listener - click on delete button
var deleteButtons = el.find(".module button.delete");
deleteButtons.unbind("click");
deleteButtons.click(function (e) {
var id = $(this).parents("div.module").attr("id");
el.append($("<div/>", { "class": "fade" }));
var moduleDelete = new Office.ModuleDelete($("body"), id, moduleDeleteTemplate, socket);
moduleDelete.displayModuleDeleteForm(function () {
el.find(".fade").remove();
});
});
// Listener - click on duplicate button
var duplicateButtons = el.find(".module button.duplicate");
duplicateButtons.unbind("click");
duplicateButtons.click(function () {
var id = $(this).parents("div.module").attr("id");
var moduleConfig = getModule(id);
var position = gridOccupation.findFirstEmptyCell();
if(position) {
moduleConfig["position"] = position;
moduleConfig["size"] = { "w": 1, "h": 1 };
moduleConfig["id"] = moduleConfig["type"] + "-" + Math.floor((Math.random() * 10000) + 1);
moduleConfig["label"] = "Copy of " + moduleConfig["label"];
}
socket.emit(Events.ADMIN_ADD_OR_UPDATE_MODULE_INSTANCE, moduleConfig);
});
});
socket.on(Events.DISCONNECT, function () {
console.log("Admin got disconnected");
el.unbind();
el.find("*").unbind();
});
/*
* useful functions
*/
var resizeDashBoardGrid = function () {
var dashboardInstances = el.find(".admin-dashboard-instances");
var gridConfig = globalConfigManager.get("grid");
dashboardInstances.css("grid-template-columns", Helpers.generateGridTemplateProperty(gridConfig["columns"]));
dashboardInstances.css("grid-template-rows", Helpers.generateGridTemplateProperty(gridConfig["rows"]));
};
var computeGridPosition = function (columns, rows, width, height, x, y) {
var gridX = Math.ceil((x / width) * columns);
var gridY = Math.ceil((y / height) * rows);
return {
"x": gridX > 0 ? gridX : 1,
"y": gridY > 0 ? gridY : 1
}
};
var getModule = function(id) {
var module = modulesInstances.filter(function (mod) {
return mod.id === id;
});
return (module.length > 0 ? module[0] : null);
}
}
); | {'content_hash': 'ec43abe596d72067743ffce17ab585eb', 'timestamp': '', 'source': 'github', 'line_count': 419, 'max_line_length': 130, 'avg_line_length': 40.20525059665871, 'alnum_prop': 0.47037872491986227, 'repo_name': 'johanpoirier/office-dashboard', 'id': '3e5a6dd1ee6b259acb58a01e626fee2054fc8262', 'size': '16846', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/js/app-admin.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '107240'}, {'name': 'JavaScript', 'bytes': '137172'}, {'name': 'Shell', 'bytes': '1271'}]} |
#ifndef _ONYX_RISCV_SBI_H
#define _ONYX_RISCV_SBI_H
#include <stdint.h>
struct sbiret
{
long error;
long value;
};
#define SBI_SUCCESS 0
#define SBI_ERR_FAILED -1
#define SBI_ERR_NOT_SUPPORTED -2
#define SBI_ERR_INVALID_PARAM -3
#define SBI_ERR_DENIED -4
#define SBI_ERR_INVALID_ADDRESS -5
#define SBI_ERR_ALREADY_AVAILABLE -6
#define SBI_ERR_ALREADY_STARTED -7
#define SBI_ERR_ALREADY_STOPPED -8
#define SBI_GET_SPEC_VERSION 0
#define SBI_GET_SBI_IMPL_ID 1
#define SBI_GET_SBI_IMPL_VERSION 2
#define SBI_PROBE_EXTENSION 3
#define SBI_GET_MVENDORID 4
#define SBI_GET_MARCHID 5
#define SBI_GET_MIMPID 6
#define SBI_BASE_EXTENSION 0x10
#define SBI_LEGACY_SET_TIMER_EXTENSION 0x00
#define SBI_TIMER_EXTENSION 0x54494d45
#define SBI_SYSTEM_RESET_EXTENSION 0x53525354
// SBI timer extension functions
#define SBI_SET_TIMER 0
struct sbiret sbi_get_spec_version();
struct sbiret sbi_get_spec_impl_id();
struct sbiret sbi_get_spec_impl_version();
struct sbiret sbi_probe_extension(long extension_id);
void sbi_set_timer(uint64_t future);
#define SBI_SYSTEM_RESET_TYPE_SHUTDOWN 0
#define SBI_SYSTEM_RESET_TYPE_COLD_REBOOT 1
#define SBI_SYSTEM_RESET_TYPE_WARM_REBOOT 2
#define SBI_SYSTEM_RESET_REASON_NONE 0
#define SBI_SYSTEM_RESET_REASON_SYSTEM_FAILURE 1
void sbi_init();
long sbi_system_reset(uint32_t type, uint32_t reason);
/**
* @brief Returns a string corresponding to the SBI error
*
* @param error SBI error
* @return Pointer to string
*/
const char *sbi_strerror(long error);
#endif
| {'content_hash': 'e482aa9803fe683f59351ca695ce8122', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 57, 'avg_line_length': 25.625, 'alnum_prop': 0.6951219512195121, 'repo_name': 'heatd/Onyx', 'id': 'c5242dedf5f626a486d8ba0ebb77bcb9b4d4fe47', 'size': '1858', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'kernel/include/onyx/riscv/sbi.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '477578'}, {'name': 'Awk', 'bytes': '12416'}, {'name': 'C', 'bytes': '10315124'}, {'name': 'C++', 'bytes': '3445896'}, {'name': 'CMake', 'bytes': '17965'}, {'name': 'M4', 'bytes': '5825'}, {'name': 'Makefile', 'bytes': '102106'}, {'name': 'Max', 'bytes': '3812'}, {'name': 'Python', 'bytes': '19594'}, {'name': 'Roff', 'bytes': '90442'}, {'name': 'Shell', 'bytes': '37452'}, {'name': 'sed', 'bytes': '451'}]} |
package com.amazonaws.services.rds.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.stream.events.XMLEvent;
import com.amazonaws.services.rds.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* Engine Defaults StAX Unmarshaller
*/
public class EngineDefaultsStaxUnmarshaller implements Unmarshaller<EngineDefaults, StaxUnmarshallerContext> {
public EngineDefaults unmarshall(StaxUnmarshallerContext context) throws Exception {
EngineDefaults engineDefaults = new EngineDefaults();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument()) targetDepth += 2;
if (context.isStartOfDocument()) targetDepth++;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument()) return engineDefaults;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("DBParameterGroupFamily", targetDepth)) {
engineDefaults.setDBParameterGroupFamily(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("Marker", targetDepth)) {
engineDefaults.setMarker(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("Parameters/Parameter", targetDepth)) {
engineDefaults.getParameters().add(ParameterStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return engineDefaults;
}
}
}
}
private static EngineDefaultsStaxUnmarshaller instance;
public static EngineDefaultsStaxUnmarshaller getInstance() {
if (instance == null) instance = new EngineDefaultsStaxUnmarshaller();
return instance;
}
}
| {'content_hash': '7fdb351b1dee090fab6cc5638b5a7be3', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 119, 'avg_line_length': 37.78688524590164, 'alnum_prop': 0.6598698481561822, 'repo_name': 'dump247/aws-sdk-java', 'id': 'a836d8cebe6d5f4e738dec4cc7a4ba01c80c938a', 'size': '2892', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'aws-java-sdk-rds/src/main/java/com/amazonaws/services/rds/model/transform/EngineDefaultsStaxUnmarshaller.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'FreeMarker', 'bytes': '117958'}, {'name': 'Java', 'bytes': '104374753'}, {'name': 'Scilab', 'bytes': '3375'}]} |
#include <aws/inspector/model/DeleteAssessmentTemplateRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Inspector::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DeleteAssessmentTemplateRequest::DeleteAssessmentTemplateRequest() :
m_assessmentTemplateArnHasBeenSet(false)
{
}
Aws::String DeleteAssessmentTemplateRequest::SerializePayload() const
{
JsonValue payload;
if(m_assessmentTemplateArnHasBeenSet)
{
payload.WithString("assessmentTemplateArn", m_assessmentTemplateArn);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DeleteAssessmentTemplateRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "InspectorService.DeleteAssessmentTemplate"));
return headers;
}
| {'content_hash': '55163ce73c22f9558d3eb16c1df32552', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 106, 'avg_line_length': 22.45, 'alnum_prop': 0.7895322939866369, 'repo_name': 'JoyIfBam5/aws-sdk-cpp', 'id': '5a8fc7601943812a6d9b24965c6058f075f7f4f2', 'size': '1471', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-inspector/source/model/DeleteAssessmentTemplateRequest.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '11868'}, {'name': 'C++', 'bytes': '167818064'}, {'name': 'CMake', 'bytes': '591577'}, {'name': 'HTML', 'bytes': '4471'}, {'name': 'Java', 'bytes': '271801'}, {'name': 'Python', 'bytes': '85650'}, {'name': 'Shell', 'bytes': '5277'}]} |
package fi.kapsi.kosmik.sfti
object Chapter14 {
/**
* Using pattern matching, write a function swap that receives a pair of integers
* and returns the pair with the components swapped.
*/
object Ex02 {
def swap(pair: (Int, Int)): (Int, Int) =
pair match {
case (a, b) => (b, a)
}
}
/**
* Using pattern matching, write a function swap that swaps the first two elements
* of an array provided its length is at least two.
*/
object Ex03 {
def swap(array: Array[Int]): Array[Int] =
array match {
case Array(a, b, res@_*) => Array(b, a) ++ res
case _ => array.clone()
}
}
/**
* Add a case class Multiple that is a subclass of the Item class. For example,
* Multiple(10, Article("Blackwell Toaster", 29.95)) describes ten toasters. Of course,
* you should be able to handle any items, such as bundles or multiples, in
* the second argument. Extend the price function to handle this new case.
*/
object Ex04 {
abstract class Item
case class Article(description: String, price: Double) extends Item
case class Bundle(description: String, discount: Double, items: Item*) extends Item
case class Multiple(quantity: Int, item: Item) extends Item
def price(it: Item): Double = it match {
case Article(_, p) => p
case Bundle(_, disc, its@_*) => its.map(price).sum - disc
case Multiple(q, i) => q * price(i)
}
}
/**
* One can use lists to model trees that store values only in the leaves. For
* example, the list ((3 8) 2 (5)) describes the tree
* <pre>
* # •
* # /|\
* # • 2 •
* # / \ |
* # 3 8 5
* </pre>
* However, some of the list elements are numbers and others are lists. In Scala,
* you cannot have heterogeneous lists, so you have to use a List[Any] . Write a
* leafSum function to compute the sum of all elements in the leaves, using pattern
* matching to differentiate between numbers and lists.
*/
object Ex05 {
def leafSum(tree: List[Any]): Int = {
def rec(subTree: Any): Int =
subTree match {
case singleton: Int => singleton
case x :: xs => rec(x) + rec(xs)
case _ => 0
}
tree.foldLeft(0)(_ + rec(_))
}
}
/**
* A better way of modeling such trees is with case classes. Let’s start with binary
* trees.
* <pre>
* sealed abstract class BinaryTree
* case class Leaf(value: Int) extends BinaryTree
* case class Node(left: BinaryTree, right: BinaryTree) extends BinaryTree
* </pre>
* Write a function to compute the sum of all elements in the leaves.
*/
object Ex06 {
sealed abstract class BinaryTree
case class Leaf(value: Int) extends BinaryTree
case class Node(left: BinaryTree, right: BinaryTree) extends BinaryTree
def leafSum(tree: BinaryTree): Int =
tree match {
case Leaf(value) => value
case Node(left, right) => leafSum(left) + leafSum(right)
}
}
/**
* Extend the tree in the preceding exercise so that each node can have an arbi-
* trary number of children, and reimplement the leafSum function. The tree in
* Exercise 5 should be expressible as
* <pre>
* Node(Node(Leaf(3), Leaf(8)), Leaf(2), Node(Leaf(5)))
* </pre>
*/
object Ex07 {
sealed abstract class BinaryTree
case class Leaf(value: Int) extends BinaryTree
case class Node(children: BinaryTree*) extends BinaryTree
def leafSum(tree: BinaryTree): Int =
tree match {
case Leaf(value) => value
case Node(children@_*) => children.map(leafSum).sum
}
}
/**
* Extend the tree in the preceding exercise so that each nonleaf node stores
* an operator in addition to the child nodes. Then write a function eval that
* computes the value. For example, the tree
* <pre>
* # +
* # /|\
* # * 2 -
* # / \ |
* # 3 8 5
* </pre>
* has value (3 × 8) + 2 + (–5) = 21.
* Pay attention to the unary minus.
*/
object Ex08 {
sealed abstract class BinaryTree
case class Leaf(value: Int) extends BinaryTree
case class Node(op: Operation, children: BinaryTree*) extends BinaryTree
sealed abstract class Operation
case class Mul() extends Operation
case class Sum() extends Operation
case class Minus() extends Operation
def eval(tree: BinaryTree): Int =
tree match {
case Leaf(value) => value
case Node(Minus(), singleton) => -eval(singleton)
case Node(op, children@_*) =>
children.map(eval).reduce((a, b) => {
op match {
case Mul() => a * b
case Sum() => a + b
case Minus() => a - b
}
})
}
}
/**
* Write a function that computes the sum of the non- None values in a
* List[Option[Int]] . Don’t use a match statement.
*/
object Ex09 {
def sum(values: List[Option[Int]]): Int =
values.map(_.getOrElse(0)).sum
}
/**
* Write a function that composes two functions of type Double => Option[Double] ,
* yielding another function of the same type. The composition should yield
* None if either function does. For example,
* <pre>
* def f(x: Double) = if (x != 1) Some(1 / (x - 1)) else None
* def g(x: Double) = if (x >= 0) Some(sqrt(x)) else None
* val h = compose(g, f) // h(x) should be g(f(x))
* </pre>
* Then h(2) is Some(1) , and h(1) and h(0) are None .
*/
object Ex10 {
def compose(g: Double => Option[Double], f: Double => Option[Double]): Double => Option[Double] =
(x: Double) => {
val resultF = f(x)
if (resultF.isDefined) g(resultF.get)
else None
}
}
}
| {'content_hash': '5ec6cd62f6873a1929dd5ee20e7e63c6', 'timestamp': '', 'source': 'github', 'line_count': 201, 'max_line_length': 101, 'avg_line_length': 29.0, 'alnum_prop': 0.5922113570080632, 'repo_name': 'suniala/sfti-exercises', 'id': 'b1de8d7e090e431806a307916d609ebf6efbd2e3', 'size': '5842', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/scala/fi/kapsi/kosmik/sfti/Chapter14.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '321'}, {'name': 'Scala', 'bytes': '145514'}]} |
package org.codemucker.jtest.bean.random.a;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.codemucker.jtest.bean.BeanException;
import org.codemucker.jtest.bean.random.BeanRandom;
import org.junit.Test;
public class BeanRandomNonPublicTest {
@Test
public void test_non_public_beans_handled() {
boolean error = false;
try {
new BeanRandom().populate(TstBeanNonPublic.class);
} catch (BeanException e) {
error = true;
}
assertTrue("Expected error", error);
BeanRandom random = new BeanRandom();
random.getOptions().makeAccessible(true);
TstBeanNonPublic bean = random.populate(TstBeanNonPublic.class);
assertNotNull(bean);
assertNotNull(bean.getMyField());
}
}
| {'content_hash': 'd9cc636b0d02007a745a1a00c5044197', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 66, 'avg_line_length': 25.933333333333334, 'alnum_prop': 0.7287917737789203, 'repo_name': 'codemucker/codemucker-jtest', 'id': '1f3666a966001eca7799d5c6f54b2535b00e2552', 'size': '1392', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/org/codemucker/jtest/bean/random/a/BeanRandomNonPublicTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '128431'}]} |
#ifndef itkLeafTreeIterator_h
#define itkLeafTreeIterator_h
#include "itkPreOrderTreeIterator.h"
namespace itk
{
template <typename TTreeType>
class ITK_TEMPLATE_EXPORT LeafTreeIterator : public TreeIteratorBase<TTreeType>
{
public:
/** Typedefs */
using Self = LeafTreeIterator;
using Superclass = TreeIteratorBase<TTreeType>;
using TreeType = TTreeType;
using ValueType = typename TreeType::ValueType;
using TreeNodeType = typename Superclass::TreeNodeType;
using NodeType = typename Superclass::NodeType;
/** Constructor */
LeafTreeIterator(const TreeType * tree);
/** Constructor */
LeafTreeIterator(TreeType * tree);
/** Destructor */
~LeafTreeIterator() override;
/** Return the type of iterator */
NodeType
GetType() const override;
/** Clone function */
TreeIteratorBase<TTreeType> *
Clone() override;
protected:
/** Return the next value */
const ValueType &
Next() override;
/** Return true if the next value exists */
bool
HasNext() const override;
private:
/** Find the next node */
const TreeNodeType *
FindNextNode() const;
};
/** Constructor */
template <typename TTreeType>
LeafTreeIterator<TTreeType>::LeafTreeIterator(const TTreeType * tree)
: TreeIteratorBase<TTreeType>(tree, nullptr)
{
this->m_Begin = const_cast<TreeNodeType *>(this->FindNextNode()); //
//
// Position
// the
//
// iterator
// to
// the
// first
// leaf;
}
/** Constructor */
template <typename TTreeType>
LeafTreeIterator<TTreeType>::LeafTreeIterator(TTreeType * tree)
: TreeIteratorBase<TTreeType>(tree, nullptr)
{
this->m_Begin = const_cast<TreeNodeType *>(this->FindNextNode()); //
//
// Position
// the
//
// iterator
// to
// the
// first
// leaf;
}
/** Destructor */
template <typename TTreeType>
LeafTreeIterator<TTreeType>::~LeafTreeIterator() = default;
/** Return the type of iterator */
template <typename TTreeType>
typename LeafTreeIterator<TTreeType>::NodeType
LeafTreeIterator<TTreeType>::GetType() const
{
return TreeIteratorBaseEnums::TreeIteratorBaseNode::LEAF;
}
/** Return true if the next value exists */
template <typename TTreeType>
bool
LeafTreeIterator<TTreeType>::HasNext() const
{
if (this->m_Position == nullptr)
{
return false;
}
if (const_cast<TreeNodeType *>(FindNextNode()) != nullptr)
{
return true;
}
return false;
}
/** Return the next node */
template <typename TTreeType>
const typename LeafTreeIterator<TTreeType>::ValueType &
LeafTreeIterator<TTreeType>::Next()
{
this->m_Position = const_cast<TreeNodeType *>(FindNextNode());
if (this->m_Position == nullptr)
{
return this->m_Root->Get(); // value irrelevant, but we have to return something
}
return this->m_Position->Get();
}
/** Find the next node given the position */
template <typename TTreeType>
const typename LeafTreeIterator<TTreeType>::TreeNodeType *
LeafTreeIterator<TTreeType>::FindNextNode() const
{
PreOrderTreeIterator<TTreeType> it(this->m_Tree, this->m_Position);
it.m_Root = this->m_Root;
++it; // go next
if (it.IsAtEnd())
{
return nullptr;
}
if (!it.HasChild())
{
return it.GetNode();
}
while (!it.IsAtEnd())
{
if (!it.HasChild())
{
return it.GetNode();
}
++it;
}
return nullptr;
}
/** Clone function */
template <typename TTreeType>
TreeIteratorBase<TTreeType> *
LeafTreeIterator<TTreeType>::Clone()
{
auto * clone = new LeafTreeIterator<TTreeType>(this->m_Tree);
*clone = *this;
return clone;
}
} // end namespace itk
#endif
| {'content_hash': '66654143cfeb00d0e4ee58be1c55867b', 'timestamp': '', 'source': 'github', 'line_count': 169, 'max_line_length': 84, 'avg_line_length': 28.041420118343197, 'alnum_prop': 0.5157206161637476, 'repo_name': 'malaterre/ITK', 'id': 'd8d239fa084a2b7ec80a1b70ed35d2d46fe38939', 'size': '5495', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Modules/Compatibility/Deprecated/include/itkLeafTreeIterator.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '435417'}, {'name': 'C++', 'bytes': '34591024'}, {'name': 'CMake', 'bytes': '1452219'}, {'name': 'CSS', 'bytes': '17428'}, {'name': 'HTML', 'bytes': '8263'}, {'name': 'Java', 'bytes': '28585'}, {'name': 'JavaScript', 'bytes': '1522'}, {'name': 'Objective-C++', 'bytes': '5773'}, {'name': 'Perl', 'bytes': '6029'}, {'name': 'Python', 'bytes': '448031'}, {'name': 'Ruby', 'bytes': '296'}, {'name': 'Shell', 'bytes': '162676'}, {'name': 'Tcl', 'bytes': '72988'}, {'name': 'XSLT', 'bytes': '8634'}]} |
package com.google.gerrit.lucene;
import com.google.common.primitives.Ints;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.index.change.ChangeSchemaDefinitions;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import java.io.IOException;
class GerritIndexStatus {
private static final String SECTION = "index";
private static final String KEY_READY = "ready";
private final FileBasedConfig cfg;
GerritIndexStatus(SitePaths sitePaths)
throws ConfigInvalidException, IOException {
cfg = new FileBasedConfig(
sitePaths.index_dir.resolve("gerrit_index.config").toFile(),
FS.detect());
cfg.load();
convertLegacyConfig();
}
void setReady(String indexName, int version, boolean ready) {
cfg.setBoolean(SECTION, indexDirName(indexName, version), KEY_READY, ready);
}
boolean getReady(String indexName, int version) {
return cfg.getBoolean(SECTION, indexDirName(indexName, version), KEY_READY,
false);
}
void save() throws IOException {
cfg.save();
}
private void convertLegacyConfig() throws IOException {
boolean dirty = false;
// Convert legacy [index "25"] to modern [index "changes_0025"].
for (String subsection : cfg.getSubsections(SECTION)) {
Integer v = Ints.tryParse(subsection);
if (v != null) {
String ready = cfg.getString(SECTION, subsection, KEY_READY);
if (ready != null) {
dirty = false;
cfg.unset(SECTION, subsection, KEY_READY);
cfg.setString(SECTION,
indexDirName(ChangeSchemaDefinitions.NAME, v), KEY_READY, ready);
}
}
}
if (dirty) {
cfg.save();
}
}
private static String indexDirName(String indexName, int version) {
return String.format("%s_%04d", indexName, version);
}
}
| {'content_hash': 'd37930d0cd233a4bfafe9360c5405654', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 80, 'avg_line_length': 30.171875, 'alnum_prop': 0.6882444329363024, 'repo_name': 'MerritCR/merrit', 'id': 'f43e385e1f1f7590f8ea23be325e20c28be256d7', 'size': '2540', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'gerrit-lucene/src/main/java/com/google/gerrit/lucene/GerritIndexStatus.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '52838'}, {'name': 'GAP', 'bytes': '4119'}, {'name': 'Go', 'bytes': '6200'}, {'name': 'Groff', 'bytes': '28221'}, {'name': 'HTML', 'bytes': '380099'}, {'name': 'Java', 'bytes': '10070223'}, {'name': 'JavaScript', 'bytes': '197056'}, {'name': 'Makefile', 'bytes': '1313'}, {'name': 'PLpgSQL', 'bytes': '4202'}, {'name': 'Perl', 'bytes': '9943'}, {'name': 'Prolog', 'bytes': '17904'}, {'name': 'Python', 'bytes': '18218'}, {'name': 'Shell', 'bytes': '48919'}, {'name': 'TypeScript', 'bytes': '1882'}]} |
#include "HASH160.hpp"
#include <crypto/BLAKE.h>
std::vector<uint8_t> ledger::core::HASH160::hash(const std::vector<uint8_t> &data, const HashAlgorithm &hashAlgorithm) {
return RIPEMD160::hash(hashAlgorithm.bytesToBytesHash(data));
}
| {'content_hash': '4a573a1f58bbd08b0ffe51ca7e709369', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 120, 'avg_line_length': 34.285714285714285, 'alnum_prop': 0.7458333333333333, 'repo_name': 'LedgerHQ/lib-ledger-core', 'id': 'af17bd786e99c6664ab442e0eccb92bf2c12735f', 'size': '1462', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'core/src/crypto/HASH160.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ada', 'bytes': '87492'}, {'name': 'Assembly', 'bytes': '95273'}, {'name': 'Batchfile', 'bytes': '49710'}, {'name': 'C', 'bytes': '17901111'}, {'name': 'C++', 'bytes': '136103115'}, {'name': 'CMake', 'bytes': '1117135'}, {'name': 'CSS', 'bytes': '2536'}, {'name': 'DIGITAL Command Language', 'bytes': '312789'}, {'name': 'Dockerfile', 'bytes': '1746'}, {'name': 'Emacs Lisp', 'bytes': '5297'}, {'name': 'HTML', 'bytes': '474505'}, {'name': 'JavaScript', 'bytes': '15286'}, {'name': 'M4', 'bytes': '58734'}, {'name': 'Makefile', 'bytes': '243'}, {'name': 'Nix', 'bytes': '6555'}, {'name': 'Perl', 'bytes': '2222280'}, {'name': 'Prolog', 'bytes': '29177'}, {'name': 'Python', 'bytes': '26175'}, {'name': 'Raku', 'bytes': '34072'}, {'name': 'Roff', 'bytes': '5'}, {'name': 'Scala', 'bytes': '1392'}, {'name': 'Scheme', 'bytes': '4249'}, {'name': 'Shell', 'bytes': '186270'}, {'name': 'XS', 'bytes': '4319'}, {'name': 'eC', 'bytes': '5127'}]} |
module Twilio
module REST
class Conversations < Domain
class V1 < Version
class ServiceContext < InstanceContext
class UserList < ListResource
##
# Initialize the UserList
# @param [Version] version Version that contains the resource
# @param [String] chat_service_sid The SID of the {Conversation
# Service}[https://www.twilio.com/docs/conversations/api/service-resource] the
# User resource is associated with.
# @return [UserList] UserList
def initialize(version, chat_service_sid: nil)
super(version)
# Path Solution
@solution = {chat_service_sid: chat_service_sid}
@uri = "/Services/#{@solution[:chat_service_sid]}/Users"
end
##
# Create the UserInstance
# @param [String] identity The application-defined string that uniquely identifies
# the resource's User within the {Conversation
# Service}[https://www.twilio.com/docs/conversations/api/service-resource]. This
# value is often a username or an email address, and is case-sensitive.
# @param [String] friendly_name The string that you assigned to describe the
# resource.
# @param [String] attributes The JSON Object string that stores
# application-specific data. If attributes have not been set, `{}` is returned.
# @param [String] role_sid The SID of a service-level
# {Role}[https://www.twilio.com/docs/conversations/api/role-resource] to assign to
# the user.
# @param [user.WebhookEnabledType] x_twilio_webhook_enabled The
# X-Twilio-Webhook-Enabled HTTP request header
# @return [UserInstance] Created UserInstance
def create(identity: nil, friendly_name: :unset, attributes: :unset, role_sid: :unset, x_twilio_webhook_enabled: :unset)
data = Twilio::Values.of({
'Identity' => identity,
'FriendlyName' => friendly_name,
'Attributes' => attributes,
'RoleSid' => role_sid,
})
headers = Twilio::Values.of({'X-Twilio-Webhook-Enabled' => x_twilio_webhook_enabled, })
payload = @version.create('POST', @uri, data: data, headers: headers)
UserInstance.new(@version, payload, chat_service_sid: @solution[:chat_service_sid], )
end
##
# Lists UserInstance records from the API as a list.
# Unlike stream(), this operation is eager and will load `limit` records into
# memory before returning.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Array] Array of up to limit results
def list(limit: nil, page_size: nil)
self.stream(limit: limit, page_size: page_size).entries
end
##
# Streams UserInstance records from the API as an Enumerable.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit.
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Enumerable] Enumerable that will yield up to limit results
def stream(limit: nil, page_size: nil)
limits = @version.read_limits(limit, page_size)
page = self.page(page_size: limits[:page_size], )
@version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit])
end
##
# When passed a block, yields UserInstance records from the API.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
def each
limits = @version.read_limits
page = self.page(page_size: limits[:page_size], )
@version.stream(page,
limit: limits[:limit],
page_limit: limits[:page_limit]).each {|x| yield x}
end
##
# Retrieve a single page of UserInstance records from the API.
# Request is executed immediately.
# @param [String] page_token PageToken provided by the API
# @param [Integer] page_number Page Number, this value is simply for client state
# @param [Integer] page_size Number of records to return, defaults to 50
# @return [Page] Page of UserInstance
def page(page_token: :unset, page_number: :unset, page_size: :unset)
params = Twilio::Values.of({
'PageToken' => page_token,
'Page' => page_number,
'PageSize' => page_size,
})
response = @version.page('GET', @uri, params: params)
UserPage.new(@version, response, @solution)
end
##
# Retrieve a single page of UserInstance records from the API.
# Request is executed immediately.
# @param [String] target_url API-generated URL for the requested results page
# @return [Page] Page of UserInstance
def get_page(target_url)
response = @version.domain.request(
'GET',
target_url
)
UserPage.new(@version, response, @solution)
end
##
# Provide a user friendly representation
def to_s
'#<Twilio.Conversations.V1.UserList>'
end
end
class UserPage < Page
##
# Initialize the UserPage
# @param [Version] version Version that contains the resource
# @param [Response] response Response from the API
# @param [Hash] solution Path solution for the resource
# @return [UserPage] UserPage
def initialize(version, response, solution)
super(version, response)
# Path Solution
@solution = solution
end
##
# Build an instance of UserInstance
# @param [Hash] payload Payload response from the API
# @return [UserInstance] UserInstance
def get_instance(payload)
UserInstance.new(@version, payload, chat_service_sid: @solution[:chat_service_sid], )
end
##
# Provide a user friendly representation
def to_s
'<Twilio.Conversations.V1.UserPage>'
end
end
class UserContext < InstanceContext
##
# Initialize the UserContext
# @param [Version] version Version that contains the resource
# @param [String] chat_service_sid The SID of the {Conversation
# Service}[https://www.twilio.com/docs/conversations/api/service-resource] to
# fetch the User resource from.
# @param [String] sid The SID of the User resource to fetch. This value can be
# either the `sid` or the `identity` of the User resource to fetch.
# @return [UserContext] UserContext
def initialize(version, chat_service_sid, sid)
super(version)
# Path Solution
@solution = {chat_service_sid: chat_service_sid, sid: sid, }
@uri = "/Services/#{@solution[:chat_service_sid]}/Users/#{@solution[:sid]}"
# Dependents
@user_conversations = nil
end
##
# Update the UserInstance
# @param [String] friendly_name The string that you assigned to describe the
# resource.
# @param [String] attributes The JSON Object string that stores
# application-specific data. If attributes have not been set, `{}` is returned.
# @param [String] role_sid The SID of a service-level
# {Role}[https://www.twilio.com/docs/conversations/api/role-resource] to assign to
# the user.
# @param [user.WebhookEnabledType] x_twilio_webhook_enabled The
# X-Twilio-Webhook-Enabled HTTP request header
# @return [UserInstance] Updated UserInstance
def update(friendly_name: :unset, attributes: :unset, role_sid: :unset, x_twilio_webhook_enabled: :unset)
data = Twilio::Values.of({
'FriendlyName' => friendly_name,
'Attributes' => attributes,
'RoleSid' => role_sid,
})
headers = Twilio::Values.of({'X-Twilio-Webhook-Enabled' => x_twilio_webhook_enabled, })
payload = @version.update('POST', @uri, data: data, headers: headers)
UserInstance.new(
@version,
payload,
chat_service_sid: @solution[:chat_service_sid],
sid: @solution[:sid],
)
end
##
# Delete the UserInstance
# @param [user.WebhookEnabledType] x_twilio_webhook_enabled The
# X-Twilio-Webhook-Enabled HTTP request header
# @return [Boolean] true if delete succeeds, false otherwise
def delete(x_twilio_webhook_enabled: :unset)
headers = Twilio::Values.of({'X-Twilio-Webhook-Enabled' => x_twilio_webhook_enabled, })
@version.delete('DELETE', @uri, headers: headers)
end
##
# Fetch the UserInstance
# @return [UserInstance] Fetched UserInstance
def fetch
payload = @version.fetch('GET', @uri)
UserInstance.new(
@version,
payload,
chat_service_sid: @solution[:chat_service_sid],
sid: @solution[:sid],
)
end
##
# Access the user_conversations
# @return [UserConversationList]
# @return [UserConversationContext] if conversation_sid was passed.
def user_conversations(conversation_sid=:unset)
raise ArgumentError, 'conversation_sid cannot be nil' if conversation_sid.nil?
if conversation_sid != :unset
return UserConversationContext.new(
@version,
@solution[:chat_service_sid],
@solution[:sid],
conversation_sid,
)
end
unless @user_conversations
@user_conversations = UserConversationList.new(
@version,
chat_service_sid: @solution[:chat_service_sid],
user_sid: @solution[:sid],
)
end
@user_conversations
end
##
# Provide a user friendly representation
def to_s
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Conversations.V1.UserContext #{context}>"
end
##
# Provide a detailed, user friendly representation
def inspect
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Conversations.V1.UserContext #{context}>"
end
end
class UserInstance < InstanceResource
##
# Initialize the UserInstance
# @param [Version] version Version that contains the resource
# @param [Hash] payload payload that contains response from Twilio
# @param [String] chat_service_sid The SID of the {Conversation
# Service}[https://www.twilio.com/docs/conversations/api/service-resource] the
# User resource is associated with.
# @param [String] sid The SID of the User resource to fetch. This value can be
# either the `sid` or the `identity` of the User resource to fetch.
# @return [UserInstance] UserInstance
def initialize(version, payload, chat_service_sid: nil, sid: nil)
super(version)
# Marshaled Properties
@properties = {
'sid' => payload['sid'],
'account_sid' => payload['account_sid'],
'chat_service_sid' => payload['chat_service_sid'],
'role_sid' => payload['role_sid'],
'identity' => payload['identity'],
'friendly_name' => payload['friendly_name'],
'attributes' => payload['attributes'],
'is_online' => payload['is_online'],
'is_notifiable' => payload['is_notifiable'],
'date_created' => Twilio.deserialize_iso8601_datetime(payload['date_created']),
'date_updated' => Twilio.deserialize_iso8601_datetime(payload['date_updated']),
'url' => payload['url'],
'links' => payload['links'],
}
# Context
@instance_context = nil
@params = {'chat_service_sid' => chat_service_sid, 'sid' => sid || @properties['sid'], }
end
##
# Generate an instance context for the instance, the context is capable of
# performing various actions. All instance actions are proxied to the context
# @return [UserContext] UserContext for this UserInstance
def context
unless @instance_context
@instance_context = UserContext.new(@version, @params['chat_service_sid'], @params['sid'], )
end
@instance_context
end
##
# @return [String] The unique string that identifies the resource
def sid
@properties['sid']
end
##
# @return [String] The SID of the Account that created the resource
def account_sid
@properties['account_sid']
end
##
# @return [String] The SID of the Conversation Service that the resource is associated with
def chat_service_sid
@properties['chat_service_sid']
end
##
# @return [String] The SID of a service-level Role assigned to the user
def role_sid
@properties['role_sid']
end
##
# @return [String] The string that identifies the resource's User
def identity
@properties['identity']
end
##
# @return [String] The string that you assigned to describe the resource
def friendly_name
@properties['friendly_name']
end
##
# @return [String] The JSON Object string that stores application-specific data
def attributes
@properties['attributes']
end
##
# @return [Boolean] Whether the User is actively connected to this Conversations Service and online
def is_online
@properties['is_online']
end
##
# @return [Boolean] Whether the User has a potentially valid Push Notification registration for this Conversations Service
def is_notifiable
@properties['is_notifiable']
end
##
# @return [Time] The ISO 8601 date and time in GMT when the resource was created
def date_created
@properties['date_created']
end
##
# @return [Time] The ISO 8601 date and time in GMT when the resource was last updated
def date_updated
@properties['date_updated']
end
##
# @return [String] An absolute URL for this user.
def url
@properties['url']
end
##
# @return [String] The links
def links
@properties['links']
end
##
# Update the UserInstance
# @param [String] friendly_name The string that you assigned to describe the
# resource.
# @param [String] attributes The JSON Object string that stores
# application-specific data. If attributes have not been set, `{}` is returned.
# @param [String] role_sid The SID of a service-level
# {Role}[https://www.twilio.com/docs/conversations/api/role-resource] to assign to
# the user.
# @param [user.WebhookEnabledType] x_twilio_webhook_enabled The
# X-Twilio-Webhook-Enabled HTTP request header
# @return [UserInstance] Updated UserInstance
def update(friendly_name: :unset, attributes: :unset, role_sid: :unset, x_twilio_webhook_enabled: :unset)
context.update(
friendly_name: friendly_name,
attributes: attributes,
role_sid: role_sid,
x_twilio_webhook_enabled: x_twilio_webhook_enabled,
)
end
##
# Delete the UserInstance
# @param [user.WebhookEnabledType] x_twilio_webhook_enabled The
# X-Twilio-Webhook-Enabled HTTP request header
# @return [Boolean] true if delete succeeds, false otherwise
def delete(x_twilio_webhook_enabled: :unset)
context.delete(x_twilio_webhook_enabled: x_twilio_webhook_enabled, )
end
##
# Fetch the UserInstance
# @return [UserInstance] Fetched UserInstance
def fetch
context.fetch
end
##
# Access the user_conversations
# @return [user_conversations] user_conversations
def user_conversations
context.user_conversations
end
##
# Provide a user friendly representation
def to_s
values = @params.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Conversations.V1.UserInstance #{values}>"
end
##
# Provide a detailed, user friendly representation
def inspect
values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Conversations.V1.UserInstance #{values}>"
end
end
end
end
end
end
end | {'content_hash': 'ae367db7066fe14efb4f0cf60e59f553', 'timestamp': '', 'source': 'github', 'line_count': 473, 'max_line_length': 134, 'avg_line_length': 41.6892177589852, 'alnum_prop': 0.5384654394239059, 'repo_name': 'philnash/twilio-ruby', 'id': 'cd77a60cd0766fcfddf726f076fd248b0da83728', 'size': '19859', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'lib/twilio-ruby/rest/conversations/v1/service/user.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '108'}, {'name': 'Makefile', 'bytes': '1003'}, {'name': 'Ruby', 'bytes': '10247081'}]} |
package soot_tests;
public enum MyEnum {
JA,
NEIN;
}
| {'content_hash': '0b3cd3d58956ed42d676f40e64052e9d', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 20, 'avg_line_length': 8.428571428571429, 'alnum_prop': 0.6440677966101694, 'repo_name': 'SRI-CSL/bixie', 'id': 'c5328e16016de0c9994c21d9fcac661922e959bc', 'size': '59', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/resources/soot_tests/MyEnum.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1071935'}, {'name': 'Lex', 'bytes': '7785'}, {'name': 'Python', 'bytes': '10677'}, {'name': 'Shell', 'bytes': '634'}]} |
import time
from director import segmentationroutines
from director import segmentation
from director.timercallback import TimerCallback
from director.visualization import *
class TrackDrillOnTable(object):
def __init__(self):
self.tableCentroid = None
def updateFit(self):
# get and display: .1sec
polyData = segmentation.getDisparityPointCloud()
if (polyData is None):
return
updatePolyData(polyData, 'pointcloud snapshot', colorByName='rgb_colors', visible=False)
t0 = time.time()
if (self.tableCentroid is None):
# initial fit .75 sec
print "Boot Strapping tracker"
self.tableCentroid = segmentation.findAndFitDrillBarrel(polyData)
else:
# refit .07 sec
#print "current centroid"
#print self.tableCentroid
viewFrame = segmentationroutines.SegmentationContext.getGlobalInstance().getViewFrame()
forwardDirection = np.array([1.0, 0.0, 0.0])
viewFrame.TransformVector(forwardDirection, forwardDirection)
robotOrigin = viewFrame.GetPosition()
robotForward =forwardDirection
fitResults = []
drillFrame = segmentation.segmentDrillBarrelFrame(self.tableCentroid, polyData, robotForward)
clusterObj = updatePolyData(polyData, 'surface cluster refit', color=[1,1,0], parent=segmentation.getDebugFolder(), visible=False)
fitResults.append((clusterObj, drillFrame))
segmentation.sortFittedDrills(fitResults, robotOrigin, robotForward)
class PointerTracker(object):
'''
See segmentation.estimatePointerTip() documentation.
'''
def __init__(self, robotModel, stereoPointCloudItem):
self.robotModel = robotModel
self.stereoPointCloudItem = stereoPointCloudItem
self.timer = TimerCallback(targetFps=5)
self.timer.callback = self.updateFit
def start(self):
self.timer.start()
def stop(self):
self.timer.stop()
def cleanup(self):
om.removeFromObjectModel(om.findObjectByName('segmentation'))
def updateFit(self, polyData=None):
#if not self.stereoPointCloudItem.getProperty('Visible'):
# return
if not polyData:
self.stereoPointCloudItem.update()
polyData = self.stereoPointCloudItem.polyData
if not polyData or not polyData.GetNumberOfPoints():
self.cleanup()
return
self.tipPosition = segmentation.estimatePointerTip(self.robotModel, polyData)
if self.tipPosition is None:
self.cleanup()
def getPointerTip(self):
return self.tipPosition
| {'content_hash': 'defc15e72de1f66985574fa449c245ba', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 142, 'avg_line_length': 32.98795180722892, 'alnum_prop': 0.6607012417823228, 'repo_name': 'RobotLocomotion/director', 'id': '68c21f778e4d34e3320b9f2eda5a72ab5ade14cc', 'size': '2738', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/python/director/trackers.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '119759'}, {'name': 'C++', 'bytes': '500237'}, {'name': 'CMake', 'bytes': '52624'}, {'name': 'GLSL', 'bytes': '15443'}, {'name': 'Makefile', 'bytes': '5014'}, {'name': 'Matlab', 'bytes': '161948'}, {'name': 'Python', 'bytes': '2128090'}, {'name': 'Shell', 'bytes': '6481'}]} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '84e64a293353825470310aedd025f086', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': 'cc0059fd81f4c98ee2bf964af56094b53d272bbc', 'size': '192', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Agrostophyllum/Agrostophyllum occidentale/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
package com.example.kdl.coolweather.db;
import org.litepal.crud.DataSupport;
/**
* Created by kdl on 2017/7/29.
*/
public class County extends DataSupport {
private int id;
private String countyName;
private String weatherId;
private int cityId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public String getWeatherId() {
return weatherId;
}
public void setWeatherId(String weatherId) {
this.weatherId = weatherId;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
}
| {'content_hash': '57de6239a0543422ce0d3b6933142b39', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 50, 'avg_line_length': 18.32608695652174, 'alnum_prop': 0.6156583629893239, 'repo_name': 'KongDeli/coolweather', 'id': 'ec85ecae98a12996e0d4239f814ee009eb9e1586', 'size': '843', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/com/coder/kdl/coolweather/db/County.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '32952'}]} |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="da" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="14"/>
<source>About Bitcoin</source>
<translation>Om Bitcoin</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="53"/>
<source><b>Bitcoin</b> version</source>
<translation><b>Bitcoin</b> version</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="85"/>
<source>Copyright © 2009-2011 Bitcoin Developers
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file license.txt 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>Copyright © 2009-2011 Bitcoin Developers
Dette er eksperimentel software.
Distribueret under MIT/X11 softwarelicensen. Se den vedlagte fil, license.txt, eller http://www.opensource.org/licenses/mit-license.php.
Dette produkt indeholder software udviklet af OpenSSL Project til brug i OpenSSL Toolkit (http://www.openssl.org/) og kryptografisk software skrevet af Eric Young ([email protected]) og UPnP software skrevet af Thomas Bernhard.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="14"/>
<source>Address Book</source>
<translation>Adressebog</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="20"/>
<source>These are your Bitcoin 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 Bitcoinadresser for at modtage betalinger. Du kan give en forskellig adresse til hver afsender, så du kan holde styr på hvem der betaler dig.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="33"/>
<source>Double-click to edit address or label</source>
<translation>Dobbeltklik for at redigere adresse eller etiket</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="57"/>
<source>Create a new address</source>
<translation>Opret en ny adresse</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="60"/>
<source>&New Address...</source>
<translation>&Ny adresse ...</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="71"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopier den valgte adresse til systemets udklipsholder</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="74"/>
<source>&Copy to Clipboard</source>
<translation>&Kopier til Udklipsholder</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="85"/>
<source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source>
<translation>Slet den valgte adresse fra listen. Kun adresser brugt til afsendelse kan slettes.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="88"/>
<source>&Delete</source>
<translation>&Slet</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="204"/>
<source>Export Address Book Data</source>
<translation>Eksporter Adressekartoteketsdata</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="206"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommasepareret fil (*. csv)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="219"/>
<source>Error exporting</source>
<translation>Fejl under eksport</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="219"/>
<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="77"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="77"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="113"/>
<source>(no label)</source>
<translation>(ingen etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="26"/>
<source>Dialog</source>
<translation>Dialog</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="32"/>
<source>TextLabel</source>
<translation>TekstEtiket</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="47"/>
<source>Enter passphrase</source>
<translation>Indtast adgangskode</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="61"/>
<source>New passphrase</source>
<translation>Ny adgangskode</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="75"/>
<source>Repeat new passphrase</source>
<translation>Gentag ny adgangskode</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="26"/>
<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>Indtast den nye adgangskode til tegnebogen.<br/>Brug venligst en adgangskode på <b>10 eller flere tilfældige tegn</b>, eller <b>otte eller flere ord</b>.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="27"/>
<source>Encrypt wallet</source>
<translation>Krypter tegnebog</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="30"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Denne funktion har brug for din tegnebogs kodeord for at låse tegnebogen op.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="35"/>
<source>Unlock wallet</source>
<translation>Lås tegnebog op</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="38"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Denne funktion har brug for din tegnebogs kodeord for at dekryptere tegnebogen.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="43"/>
<source>Decrypt wallet</source>
<translation>Dekryptér tegnebog</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="46"/>
<source>Change passphrase</source>
<translation>Skift adgangskode</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="47"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Indtast den gamle og nye adgangskode til tegnebogen.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="91"/>
<source>Confirm wallet encryption</source>
<translation>Bekræft tegnebogskryptering</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="92"/>
<source>WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!
Are you sure you wish to encrypt your wallet?</source>
<translation>ADVARSEL: Hvis du krypterer din tegnebog og mister dit kodeord vil du <b>miste alle dine BITCOINS</b>!
Er du sikker på at du ønsker at kryptere din tegnebog?</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="101"/>
<location filename="../askpassphrasedialog.cpp" line="149"/>
<source>Wallet encrypted</source>
<translation>Tegnebog krypteret</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="102"/>
<source>Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation>Husk, at kryptere din tegnebog vil ikke fuldt ud beskytte dine bitcoins mod at blive stjålet af malware på din computer.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="106"/>
<location filename="../askpassphrasedialog.cpp" line="113"/>
<location filename="../askpassphrasedialog.cpp" line="155"/>
<location filename="../askpassphrasedialog.cpp" line="161"/>
<source>Wallet encryption failed</source>
<translation>Tegnebogskryptering mislykkedes</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="107"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Tegnebogskryptering mislykkedes på grund af en intern fejl. Din tegnebog blev ikke krypteret.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="114"/>
<location filename="../askpassphrasedialog.cpp" line="162"/>
<source>The supplied passphrases do not match.</source>
<translation>De angivne kodeord stemmer ikke overens.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="125"/>
<source>Wallet unlock failed</source>
<translation>Tegnebogsoplåsning mislykkedes</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="126"/>
<location filename="../askpassphrasedialog.cpp" line="137"/>
<location filename="../askpassphrasedialog.cpp" line="156"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Det angivne kodeord for tegnebogsdekrypteringen er forkert.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="136"/>
<source>Wallet decryption failed</source>
<translation>Tegnebogsdekryptering mislykkedes</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="150"/>
<source>Wallet passphrase was succesfully changed.</source>
<translation>Tegnebogskodeord blev ændret.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="63"/>
<source>Bitcoin Wallet</source>
<translation>Bitcoin Tegnebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="132"/>
<source>Synchronizing with network...</source>
<translation>Synkroniserer med netværk ...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="135"/>
<source>Block chain synchronization in progress</source>
<translation>Blokkæde synkronisering i gang</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="164"/>
<source>&Overview</source>
<translation>&Oversigt</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="165"/>
<source>Show general overview of wallet</source>
<translation>Vis generel oversigt over tegnebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="170"/>
<source>&Transactions</source>
<translation>&Transaktioner</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="171"/>
<source>Browse transaction history</source>
<translation>Gennemse transaktionshistorik</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="176"/>
<source>&Address Book</source>
<translation>&Adressebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="177"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Rediger listen over gemte adresser og etiketter</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="182"/>
<source>&Receive coins</source>
<translation>&Modtag coins</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="183"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Vis listen over adresser for at modtage betalinger</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="188"/>
<source>&Send coins</source>
<translation>&Send coins</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="189"/>
<source>Send coins to a bitcoin address</source>
<translation>Send coins til en bitcoinadresse</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="200"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="201"/>
<source>Quit application</source>
<translation>Afslut program</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="204"/>
<source>&About %1</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="205"/>
<source>Show information about Bitcoin</source>
<translation>Vis oplysninger om Bitcoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="207"/>
<source>&Options...</source>
<translation>&Indstillinger ...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="208"/>
<source>Modify configuration options for bitcoin</source>
<translation>Rediger konfigurationsindstillinger af bitcoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="210"/>
<source>Open &Bitcoin</source>
<translation>Åbn &Bitcoin</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="211"/>
<source>Show the Bitcoin window</source>
<translation>Vis Bitcoinvinduet</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="212"/>
<source>&Export...</source>
<translation>&Eksporter...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="213"/>
<source>Export the current view to a file</source>
<translation>Eksportér den aktuelle visning til en fil</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="214"/>
<source>&Encrypt Wallet</source>
<translation>&Kryptér tegnebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="215"/>
<source>Encrypt or decrypt wallet</source>
<translation>Kryptér eller dekryptér tegnebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="217"/>
<source>&Change Passphrase</source>
<translation>&Skift adgangskode</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="218"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Skift kodeord anvendt til tegnebogskryptering</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="239"/>
<source>&File</source>
<translation>&Fil</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="242"/>
<source>&Settings</source>
<translation>&Indstillinger</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="248"/>
<source>&Help</source>
<translation>&Hjælp</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="254"/>
<source>Tabs toolbar</source>
<translation>Faneværktøjslinje</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="262"/>
<source>Actions toolbar</source>
<translation>Handlingsværktøjslinje</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="273"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="355"/>
<source>bitcoin-qt</source>
<translation>bitcoin-qt</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="396"/>
<source>%n active connection(s) to Bitcoin network</source>
<translation><numerusform>%n aktiv(e) forbindelse(r) til Bitcoinnetværket</numerusform><numerusform>%n aktiv(e) forbindelse(r) til Bitcoinnetværket</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="411"/>
<source>Downloaded %1 of %2 blocks of transaction history.</source>
<translation>Downloadet %1 af %2 blokke af transaktionshistorie.</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="417"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Downloadet %1 blokke af transaktionshistorie.</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="428"/>
<source>%n second(s) ago</source>
<translation><numerusform>%n sekund(er) siden</numerusform><numerusform>%n sekund(er) siden</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="432"/>
<source>%n minute(s) ago</source>
<translation><numerusform>%n minut(ter) siden</numerusform><numerusform>%n minut(ter) siden</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="436"/>
<source>%n hour(s) ago</source>
<translation><numerusform>%n time(r) siden</numerusform><numerusform>%n time(r) siden</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="440"/>
<source>%n day(s) ago</source>
<translation><numerusform>%n dag(e) siden</numerusform><numerusform>%n dag(e) siden</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="446"/>
<source>Up to date</source>
<translation>Opdateret</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="451"/>
<source>Catching up...</source>
<translation>Indhenter...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="457"/>
<source>Last received block was generated %1.</source>
<translation>Sidst modtagne blok blev genereret %1.</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="508"/>
<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 transaktion er over størrelsesbegrænsningen. Du kan stadig sende den for et gebyr på %1 som går til de noder der behandler din transaktion, og som hjælper med at støtte netværket. Ønsker du at betale gebyret?</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="513"/>
<source>Sending...</source>
<translation>Sender...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="538"/>
<source>Sent transaction</source>
<translation>Afsendt transaktion</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="539"/>
<source>Incoming transaction</source>
<translation>Indgående transaktion</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="540"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dato: %1
Beløb: %2
Type: %3
Adresse: %4
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="639"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Tegnebog er <b>krypteret</b> og i øjeblikket <b>ulåst</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="647"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Tegnebog er <b>krypteret</b> og i øjeblikket <b>låst</b></translation>
</message>
</context>
<context>
<name>DisplayOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="270"/>
<source>&Unit to show amounts in: </source>
<translation>&Enhed at vise beløb i: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="274"/>
<source>Choose the default subdivision unit to show in the interface, and when sending coins</source>
<translation>Vælg den standard underopdelingsenhed som skal vises i brugergrænsefladen, og når du sender coins</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="281"/>
<source>Display addresses in transaction list</source>
<translation>Vis adresser i transaktionensliste</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 filename="../forms/editaddressdialog.ui" line="25"/>
<source>&Label</source>
<translation>&Etiket</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="35"/>
<source>The label associated with this address book entry</source>
<translation>Etiketten forbundet med denne post i adressekartoteket</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="42"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="52"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Adressen tilknyttet til denne post i adressekartoteket. Dette kan kun ændres for afsendelsesadresser.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="20"/>
<source>New receiving address</source>
<translation>Ny modtagelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="24"/>
<source>New sending address</source>
<translation>Ny afsendelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="27"/>
<source>Edit receiving address</source>
<translation>Rediger modtagelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="31"/>
<source>Edit sending address</source>
<translation>Rediger afsendelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="87"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Den indtastede adresse "%1" er allerede i adressebogen.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="92"/>
<source>The entered address "%1" is not a valid bitcoin address.</source>
<translation>Den indtastede adresse "%1" er ikke en gyldig bitcoinadresse.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="97"/>
<source>Could not unlock wallet.</source>
<translation>Kunne ikke låse tegnebog op.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="102"/>
<source>New key generation failed.</source>
<translation>Ny nøglegenerering mislykkedes.</translation>
</message>
</context>
<context>
<name>MainOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="170"/>
<source>&Start Bitcoin on window system startup</source>
<translation>&Start Bitcoin når systemet startes</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="171"/>
<source>Automatically start Bitcoin after the computer is turned on</source>
<translation>Start Bitcoin automatisk efter at computeren er tændt</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="175"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimer til systembakken i stedet for proceslinjen</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="176"/>
<source>Show only a tray icon after minimizing the window</source>
<translation>Vis kun et systembakkeikon efter minimering af vinduet</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="180"/>
<source>Map port using &UPnP</source>
<translation>Konfigurer port vha. &UPnP</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="181"/>
<source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Åbn Bitcoinklient-porten på routeren automatisk. Dette virker kun når din router understøtter UPnP og UPnP er aktiveret.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="185"/>
<source>M&inimize on close</source>
<translation>M&inimer ved lukning</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="186"/>
<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>Minimer i stedet for at afslutte programmet når vinduet lukkes. Når denne indstilling er valgt vil programmet kun blive lukket når du har valgt Afslut i menuen.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="190"/>
<source>&Connect through SOCKS4 proxy:</source>
<translation>&Forbind gennem SOCKS4 proxy:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="191"/>
<source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source>
<translation>Opret forbindelse til Bitconnetværket via en SOCKS4 proxy (f.eks. ved tilslutning gennem Tor)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="196"/>
<source>Proxy &IP: </source>
<translation>Proxy-&IP:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="202"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-adressen på proxyen (f.eks. 127.0.0.1)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="205"/>
<source>&Port: </source>
<translation>&Port:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="211"/>
<source>Port of the proxy (e.g. 1234)</source>
<translation>Porten på proxyen (f.eks. 1234)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="217"/>
<source>Optional transaction fee per KB that helps make sure your transactions are processed quickly. Most transactions are 1KB. Fee 0.01 recommended.</source>
<translation>Valgfri transaktionsgebyr pr. KB, der hjælper dine transaktioner med at blive behandlet hurtigt. De fleste transaktioner er på 1KB. Gebyr på 0.01 anbefales.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="223"/>
<source>Pay transaction &fee</source>
<translation>Betal transaktions&gebyr</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="226"/>
<source>Optional transaction fee per KB that helps make sure your transactions are processed quickly. Most transactions are 1KB. Fee 0.01 recommended.</source>
<translation>Valgfri transaktionsgebyr pr. KB, der hjælper dine transaktioner med at blive behandlet hurtigt. De fleste transaktioner er på 1KB. Gebyr på 0.01 anbefales.</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../optionsdialog.cpp" line="79"/>
<source>Main</source>
<translation>Generelt</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="84"/>
<source>Display</source>
<translation>Visning</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="104"/>
<source>Options</source>
<translation>Indstillinger</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="14"/>
<source>Form</source>
<translation>Formular</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="40"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="47"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="54"/>
<source>Number of transactions:</source>
<translation>Antal transaktioner:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="61"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="68"/>
<source>Unconfirmed:</source>
<translation>Ubekræftede:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="75"/>
<source>0 BTC</source>
<translation>0 BTC</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="82"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Wallet</span></p></body></html></source>
<translation><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Wallet</span></p></body></html></translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="122"/>
<source><b>Recent transactions</b></source>
<translation><b>Nyeste transaktioner</b></translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="103"/>
<source>Your current balance</source>
<translation>Din aktuelle saldo</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Summen af transaktioner, der endnu ikke er bekræftet, og endnu ikke er inkluderet i den nuværende saldo</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="111"/>
<source>Total number of transactions in wallet</source>
<translation>Samlede antal transaktioner i tegnebogen</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="14"/>
<location filename="../sendcoinsdialog.cpp" line="109"/>
<location filename="../sendcoinsdialog.cpp" line="114"/>
<location filename="../sendcoinsdialog.cpp" line="119"/>
<location filename="../sendcoinsdialog.cpp" line="124"/>
<location filename="../sendcoinsdialog.cpp" line="130"/>
<location filename="../sendcoinsdialog.cpp" line="135"/>
<location filename="../sendcoinsdialog.cpp" line="140"/>
<source>Send Coins</source>
<translation>Send Coins</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="64"/>
<source>Send to multiple recipients at once</source>
<translation>Send til flere modtagere på én gang</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="67"/>
<source>&Add recipient...</source>
<translation>&Tilføj modtager...</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="84"/>
<source>Clear all</source>
<translation>Ryd alle</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="103"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="110"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="141"/>
<source>Confirm the send action</source>
<translation>Bekræft afsendelsen</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="144"/>
<source>&Send</source>
<translation>&Afsend</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="85"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> til %2 (%3)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="88"/>
<source>Confirm send coins</source>
<translation>Bekræft afsendelse af coins</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="89"/>
<source>Are you sure you want to send %1?</source>
<translation>Er du sikker på at du vil sende %1?</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="89"/>
<source> and </source>
<translation> og </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="110"/>
<source>The recepient address is not valid, please recheck.</source>
<translation>Modtagerens adresse er ikke gyldig. Tjek venligst adressen igen.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="115"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Beløbet til betaling skal være større end 0.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="120"/>
<source>Amount exceeds your balance</source>
<translation>Beløbet overstiger din saldo</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="125"/>
<source>Total exceeds your balance when the %1 transaction fee is included</source>
<translation>Totalen overstiger din saldo når %1 transaktionsgebyr er inkluderet</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="131"/>
<source>Duplicate address found, can only send to each address once in one send operation</source>
<translation>Duplikeret adresse fundet. Du kan kun sende til hver adresse en gang pr. afsendelse.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="136"/>
<source>Error: Transaction creation failed </source>
<translation>Fejl: Oprettelse af transaktionen mislykkedes </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="141"/>
<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>Fejl: Transaktionen blev afvist. Dette kan ske hvis nogle af dine coins i din tegnebog allerede var brugt, som hvis du brugte en kopi af wallet.dat og dine coins er blevet brugt i kopien, men ikke er markeret som brugt her.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="14"/>
<source>Form</source>
<translation>Formular</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="29"/>
<source>A&mount:</source>
<translation>B&eløb:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="42"/>
<source>Pay &To:</source>
<translation>Betal &Til:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="66"/>
<location filename="../sendcoinsentry.cpp" line="26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Indtast en etiket for denne adresse for at føje den til din adressebog</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="75"/>
<source>&Label:</source>
<translation>&Etiket:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="93"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Adresse som betalingen skal sendes til (f.eks. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="103"/>
<source>Choose adress from address book</source>
<translation>Vælg adresse fra adressebog</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="113"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="120"/>
<source>Paste address from clipboard</source>
<translation>Indsæt adresse fra udklipsholderen</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="130"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="137"/>
<source>Remove this recipient</source>
<translation>Fjern denne modtager</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="25"/>
<source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Indtast en Bitcoinadresse (f.eks. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="34"/>
<source>Open for %1 blocks</source>
<translation>Åben for %1 blokke</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="36"/>
<source>Open until %1</source>
<translation>Åben indtil %1</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="42"/>
<source>%1/offline?</source>
<translation>%1/offline?</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="44"/>
<source>%1/unconfirmed</source>
<translation>%1/ubekræftet</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="46"/>
<source>%1 confirmations</source>
<translation>%1 bekræftelser</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="63"/>
<source><b>Status:</b> </source>
<translation><b>Status:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="68"/>
<source>, has not been successfully broadcast yet</source>
<translation>, er ikke blevet transmitteret endnu</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="70"/>
<source>, broadcast through %1 node</source>
<translation>, transmitteret via %1 node</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="72"/>
<source>, broadcast through %1 nodes</source>
<translation>, transmitteret via %1 noder</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="76"/>
<source><b>Date:</b> </source>
<translation><b>Dato:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="83"/>
<source><b>Source:</b> Generated<br></source>
<translation><b>Kilde:</b> Genereret<br></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="89"/>
<location filename="../transactiondesc.cpp" line="106"/>
<source><b>From:</b> </source>
<translation><b>Fra:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="106"/>
<source>unknown</source>
<translation>ukendt</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="107"/>
<location filename="../transactiondesc.cpp" line="130"/>
<location filename="../transactiondesc.cpp" line="189"/>
<source><b>To:</b> </source>
<translation><b>Til:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="110"/>
<source> (yours, label: </source>
<translation> (din, etiket:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="112"/>
<source> (yours)</source>
<translation> (din)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="147"/>
<location filename="../transactiondesc.cpp" line="161"/>
<location filename="../transactiondesc.cpp" line="206"/>
<location filename="../transactiondesc.cpp" line="223"/>
<source><b>Credit:</b> </source>
<translation><b>Kredit:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="149"/>
<source>(%1 matures in %2 more blocks)</source>
<translation>(%1 modnes i %2 blokke mere)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="153"/>
<source>(not accepted)</source>
<translation>(ikke accepteret)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="197"/>
<location filename="../transactiondesc.cpp" line="205"/>
<location filename="../transactiondesc.cpp" line="220"/>
<source><b>Debit:</b> </source>
<translation><b>Debet:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="211"/>
<source><b>Transaction fee:</b> </source>
<translation><b>Transaktionsgebyr:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="227"/>
<source><b>Net amount:</b> </source>
<translation><b>Nettobeløb:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="233"/>
<source>Message:</source>
<translation>Besked:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="235"/>
<source>Comment:</source>
<translation>Kommentar:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="238"/>
<source>Generated coins must wait 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, it will change to "not accepted" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Genererede coins skal vente 120 blokke, før de kan blive brugt. Da du genererede denne blok blev det transmitteret til netværket, for at blive føjet til blokkæden. Hvis det mislykkes at komme ind i kæden, vil den skifte til "ikke godkendt", og ikke blive kunne bruges. Dette kan lejlighedsvis ske, hvis en anden node genererer en blok inden for få sekunder af din.</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="14"/>
<source>Transaction details</source>
<translation>Transaktionsdetaljer</translation>
</message>
<message>
<location filename="../forms/transactiondescdialog.ui" line="20"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Denne rude viser en detaljeret beskrivelse af transaktionen</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Amount</source>
<translation>Beløb</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="274"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Åben for %n blok(ke)</numerusform><numerusform>Åben for %n blok(ke)</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="277"/>
<source>Open until %1</source>
<translation>Åben indtil %1</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="280"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 bekræftelser)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="283"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Ubekræftet (%1 af %2 bekræftelser)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="286"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bekræftet (%1 bekræftelser)</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="295"/>
<source>Mined balance will be available in %n more blocks</source>
<translation><numerusform>Minerede balance vil være tilgængelig om %n blok(ke)</numerusform><numerusform>Minerede balance vil være tilgængelig om %n blok(ke)</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="301"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Denne blok blev ikke modtaget af nogen andre noder, og vil formentlig ikke blive accepteret!</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="304"/>
<source>Generated but not accepted</source>
<translation>Genereret, men ikke accepteret</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="347"/>
<source>Received with</source>
<translation>Modtaget med</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="349"/>
<source>Received from IP</source>
<translation>Modtaget fra IP</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="351"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="353"/>
<source>Sent to IP</source>
<translation>Sendt til IP</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="355"/>
<source>Payment to yourself</source>
<translation>Betaling til dig selv</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="357"/>
<source>Mined</source>
<translation>Minerede</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="395"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="594"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transactionsstatus. Hold musen over dette felt for at vise antallet af bekræftelser.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="596"/>
<source>Date and time that the transaction was received.</source>
<translation>Dato og tid for at transaktionen blev modtaget.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="598"/>
<source>Type of transaction.</source>
<translation>Type af transaktion.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="600"/>
<source>Destination address of transaction.</source>
<translation>Destinationsadresse for transaktion.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="602"/>
<source>Amount removed from or added to balance.</source>
<translation>Beløb fjernet eller tilføjet balance.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="55"/>
<location filename="../transactionview.cpp" line="71"/>
<source>All</source>
<translation>Alle</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="56"/>
<source>Today</source>
<translation>I dag</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="57"/>
<source>This week</source>
<translation>Denne uge</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="58"/>
<source>This month</source>
<translation>Denne måned</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="59"/>
<source>Last month</source>
<translation>Sidste måned</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="60"/>
<source>This year</source>
<translation>Dette år</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="61"/>
<source>Range...</source>
<translation>Interval...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="72"/>
<source>Received with</source>
<translation>Modtaget med</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="74"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="76"/>
<source>To yourself</source>
<translation>Til dig selv</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="77"/>
<source>Mined</source>
<translation>Minerede</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="78"/>
<source>Other</source>
<translation>Andet</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="84"/>
<source>Enter address or label to search</source>
<translation>Indtast adresse eller etiket for at søge</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="90"/>
<source>Min amount</source>
<translation>Min. beløb</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="125"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="126"/>
<source>Copy label</source>
<translation>Kopier etiket</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="127"/>
<source>Edit label</source>
<translation>Rediger etiket</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="128"/>
<source>Show details...</source>
<translation>Vis detaljer...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="261"/>
<source>Export Transaction Data</source>
<translation>Eksportér Transaktionsdata</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="263"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommasepareret fil (*.csv)</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="271"/>
<source>Confirmed</source>
<translation>Bekræftet</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="272"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="273"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="274"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="275"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="276"/>
<source>Amount</source>
<translation>Beløb</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="277"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="281"/>
<source>Error exporting</source>
<translation>Fejl under eksport</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="281"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="369"/>
<source>Range:</source>
<translation>Interval:</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="377"/>
<source>to</source>
<translation>til</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="144"/>
<source>Sending...</source>
<translation>Sender...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="3"/>
<source>Bitcoin version</source>
<translation>Bitcoinversion</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="4"/>
<source>Usage:</source>
<translation>Anvendelse:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="5"/>
<source>Send command to -server or bitcoind
</source>
<translation>Send kommando til -server eller bitcoind
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="6"/>
<source>List commands
</source>
<translation>Liste over kommandoer
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="7"/>
<source>Get help for a command
</source>
<translation>Få hjælp til en kommando
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="8"/>
<source>Options:
</source>
<translation>Indstillinger:
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="9"/>
<source>Specify configuration file (default: bitcoin.conf)
</source>
<translation>Angiv konfigurationsfil (standard: bitcoin.conf)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="10"/>
<source>Specify pid file (default: bitcoind.pid)
</source>
<translation>Angiv pid-fil (default: bitcoind.pid)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="11"/>
<source>Generate coins
</source>
<translation>Generér coins
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="12"/>
<source>Don't generate coins
</source>
<translation>Generér ikke coins
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="13"/>
<source>Start minimized
</source>
<translation>Start minimeret
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="14"/>
<source>Specify data directory
</source>
<translation>Angiv databibliotek
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="15"/>
<source>Specify connection timeout (in milliseconds)
</source>
<translation>Angiv tilslutningstimeout (i millisekunder)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="16"/>
<source>Connect through socks4 proxy
</source>
<translation>Tilslut via SOCKS4 proxy
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="17"/>
<source>Allow DNS lookups for addnode and connect
</source>
<translation>Tillad DNS-opslag for addnode og connect
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="18"/>
<source>Add a node to connect to
</source>
<translation>Tilføj en node til at forbinde til
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="19"/>
<source>Connect only to the specified node
</source>
<translation>Tilslut kun til den angivne node
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="20"/>
<source>Don't accept connections from outside
</source>
<translation>Acceptér ikke forbindelser udefra
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="21"/>
<source>Don't attempt to use UPnP to map the listening port
</source>
<translation>Forsøg ikke at bruge UPnP til at konfigurere den lyttende port</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="22"/>
<source>Attempt to use UPnP to map the listening port
</source>
<translation>Forsøg at bruge UPnP til at kofnigurere den lyttende port</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="23"/>
<source>Fee per KB to add to transactions you send
</source>
<translation>Gebyr pr. KB, som skal tilføjes til transaktioner du sender
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="24"/>
<source>Accept command line and JSON-RPC commands
</source>
<translation>Accepter kommandolinje- og JSON-RPC-kommandoer
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="25"/>
<source>Run in the background as a daemon and accept commands
</source>
<translation>Kør i baggrunden som en service, og acceptér kommandoer
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="26"/>
<source>Use the test network
</source>
<translation>Brug test-netværket
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="27"/>
<source>Username for JSON-RPC connections
</source>
<translation>Brugernavn til JSON-RPC-forbindelser
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="28"/>
<source>Password for JSON-RPC connections
</source>
<translation>Password til JSON-RPC-forbindelser
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="29"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332)
</source>
<translation>Lyt til JSON-RPC-forbindelser på <port> (standard: 8332)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="30"/>
<source>Allow JSON-RPC connections from specified IP address
</source>
<translation>Tillad JSON-RPC-forbindelser fra bestemt IP-adresse
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="31"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)
</source>
<translation>Send kommandoer til node, der kører på <ip> (standard: 127.0.0.1)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="32"/>
<source>Set key pool size to <n> (default: 100)
</source>
<translation>Sæt nøglepoolstørrelse til <n> (standard: 100)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="33"/>
<source>Rescan the block chain for missing wallet transactions
</source>
<translation>Gennemsøg blokkæden for manglende tegnebogstransaktioner
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="34"/>
<source>
SSL options: (see the Bitcoin Wiki for SSL setup instructions)
</source>
<translation>
SSL-indstillinger: (se Bitcoin Wiki for SSL opsætningsinstruktioner)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="37"/>
<source>Use OpenSSL (https) for JSON-RPC connections
</source>
<translation>Brug OpenSSL (https) for JSON-RPC-forbindelser
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="38"/>
<source>Server certificate file (default: server.cert)
</source>
<translation>Servercertifikat-fil (standard: server.cert)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="39"/>
<source>Server private key (default: server.pem)
</source>
<translation>Server private nøgle (standard: server.pem)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="40"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</source>
<translation>Acceptabele ciphers (standard: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="43"/>
<source>This help message
</source>
<translation>Denne hjælpebesked
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="44"/>
<source>Cannot obtain a lock on data directory %s. Bitcoin is probably already running.</source>
<translation>Kan låse data-biblioteket %s. Bitcoin kører sikkert allerede.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="47"/>
<source>Loading addresses...</source>
<translation>Indlæser adresser...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="48"/>
<source>Error loading addr.dat
</source>
<translation>Fejl ved indlæsning af addr.dat
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="49"/>
<source>Loading block index...</source>
<translation>Indlæser blok-indeks...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="50"/>
<source>Error loading blkindex.dat
</source>
<translation>Fejl ved indlæsning af blkindex.dat
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="51"/>
<source>Loading wallet...</source>
<translation>Indlæser tegnebog...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="52"/>
<source>Error loading wallet.dat: Wallet corrupted
</source>
<translation>Fejl ved indlæsning af wallet.dat: Tegnebog ødelagt
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="53"/>
<source>Error loading wallet.dat: Wallet requires newer version of Bitcoin
</source>
<translation>Fejl ved indlæsning af wallet.dat: Tegnebog kræver en nyere version af Bitcoin
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="55"/>
<source>Error loading wallet.dat
</source>
<translation>Fejl ved indlæsning af wallet.dat
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="56"/>
<source>Rescanning...</source>
<translation>Genindlæser...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="57"/>
<source>Done loading</source>
<translation>Indlæsning gennemført</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="58"/>
<source>Invalid -proxy address</source>
<translation>Ugyldig -proxy adresse</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="59"/>
<source>Invalid amount for -paytxfee=<amount></source>
<translation>Ugyldigt beløb for -paytxfee=<amount></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="60"/>
<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 sat meget højt. Dette er det gebyr du vil betale, hvis du sender en transaktion.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="63"/>
<source>Error: CreateThread(StartNode) failed</source>
<translation>Fejl: CreateThread(StartNode) mislykkedes</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="64"/>
<source>Warning: Disk space is low </source>
<translation>Advarsel: Diskplads er lav </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="65"/>
<source>Unable to bind to port %d on this computer. Bitcoin is probably already running.</source>
<translation>Kunne ikke binde sig til port %d på denne computer. Bitcoin kører sikkert allerede.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="68"/>
<source>This transaction is over the size limit. You can still send it for a fee of %s, 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 transaktion er over størrelsesbegrænsningen. Du kan stadig sende den for et gebyr på %s som går til de noder der behandler din transaktion, og som hjælper med at støtte netværket. Ønsker du at betale gebyret?</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="72"/>
<source>Enter the current passphrase to the wallet.</source>
<translation>Indtast den nuværende adgangskode til tegnebogen.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="73"/>
<source>Passphrase</source>
<translation>Adgangskode</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="74"/>
<source>Please supply the current wallet decryption passphrase.</source>
<translation>Angiv venligst det nuværende kodeord til dekryptering af tegnebog.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="75"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Det angivne kodeord for tegnebogsdekrypteringen er forkert.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="76"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="77"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="78"/>
<source>Description</source>
<translation>Beskrivelse</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="79"/>
<source>Debit</source>
<translation>Debet</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="80"/>
<source>Credit</source>
<translation>Kredit</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="81"/>
<source>Open for %d blocks</source>
<translation>Åben for %d blokke</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="82"/>
<source>Open until %s</source>
<translation>Åben indtil %s</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="83"/>
<source>%d/offline?</source>
<translation>%d/offline?</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="84"/>
<source>%d/unconfirmed</source>
<translation>%d/ubekræftet</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="85"/>
<source>%d confirmations</source>
<translation>%d bekræftelser</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="86"/>
<source>Generated</source>
<translation>Genereret</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="87"/>
<source>Generated (%s matures in %d more blocks)</source>
<translation>Genereret (%s modnes om %d blokke)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="88"/>
<source>Generated - Warning: This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Genereret - Advarsel: Denne blok blev ikke modtaget af nogen andre noder, og vil formentlig ikke blive accepteret!</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="91"/>
<source>Generated (not accepted)</source>
<translation>Genereret (ikke accepteret)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="92"/>
<source>From: </source>
<translation>Fra: </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="93"/>
<source>Received with: </source>
<translation>Modtaget med: </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="94"/>
<source>Payment to yourself</source>
<translation>Betaling til dig selv</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="95"/>
<source>To: </source>
<translation>Til: </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="96"/>
<source> Generating</source>
<translation> Generering</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="97"/>
<source>(not connected)</source>
<translation>(ikke tilsluttet)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="98"/>
<source> %d connections %d blocks %d transactions</source>
<translation> %d forbindelser %d blokke %d transaktioner</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="99"/>
<source>Wallet already encrypted.</source>
<translation>Tegnebog er allerede krypteret.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="100"/>
<source>Enter the new passphrase to the wallet.
Please use a passphrase of 10 or more random characters, or eight or more words.</source>
<translation>Indtast den nye adgangskode til tegnebogen.
Brug venligst en adgangskode på 10 eller flere tilfældige tegn, eller otte eller flere ord.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="104"/>
<source>Error: The supplied passphrase was too short.</source>
<translation>Fejl: Den angivne kodeord var for kort.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="105"/>
<source>WARNING: If you encrypt your wallet and lose your passphrase, you will LOSE ALL OF YOUR BITCOINS!
Are you sure you wish to encrypt your wallet?</source>
<translation>ADVARSEL: Hvis du krypterer din tegnebog og mister dit kodeord, vil du miste alle dine BITCOINS!
Er du sikker på at du ønsker at kryptere din tegnebog?</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="109"/>
<source>Please re-enter your new wallet passphrase.</source>
<translation>Angiv venligst dit nye tegneborgskodeord igen.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="110"/>
<source>Error: the supplied passphrases didn't match.</source>
<translation>Fejl: de angive kodeord stemte ikke overens.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="111"/>
<source>Wallet encryption failed.</source>
<translation>Tegnebogskryptering mislykkedes.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="112"/>
<source>Wallet Encrypted.
Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation>Tegnebog Krypteret.
Husk at kryptere din tegnebog ikke fuldt ud kan beskytte din bitcoins mod at blive stjålet af malware inficerer din computer.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="116"/>
<source>Wallet is unencrypted, please encrypt it first.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="117"/>
<source>Enter the new passphrase for the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="118"/>
<source>Re-enter the new passphrase for the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="119"/>
<source>Wallet Passphrase Changed.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="120"/>
<source>New Receiving Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="121"/>
<source>You should use a new address for each payment you receive.
Label</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="125"/>
<source><b>Status:</b> </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="126"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="127"/>
<source>, broadcast through %d node</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="128"/>
<source>, broadcast through %d nodes</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="129"/>
<source><b>Date:</b> </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="130"/>
<source><b>Source:</b> Generated<br></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="131"/>
<source><b>From:</b> </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="132"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="133"/>
<source><b>To:</b> </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="134"/>
<source> (yours, label: </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="135"/>
<source> (yours)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="136"/>
<source><b>Credit:</b> </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="137"/>
<source>(%s matures in %d more blocks)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="138"/>
<source>(not accepted)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="139"/>
<source><b>Debit:</b> </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="140"/>
<source><b>Transaction fee:</b> </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="141"/>
<source><b>Net amount:</b> </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="142"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="143"/>
<source>Comment:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="144"/>
<source>Generated coins must wait 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, it will change to "not accepted" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="150"/>
<source>Cannot write autostart/bitcoin.desktop file</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="151"/>
<source>Main</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="152"/>
<source>&Start Bitcoin on window system startup</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="153"/>
<source>&Minimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="154"/>
<source>version %s</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="155"/>
<source>Error in amount </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="156"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="157"/>
<source>Amount exceeds your balance </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="158"/>
<source>Total exceeds your balance when the </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="159"/>
<source> transaction fee is included </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="160"/>
<source>Payment sent </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="161"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="162"/>
<source>Invalid address </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="163"/>
<source>Sending %s to %s</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="164"/>
<source>CANCELLED</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="165"/>
<source>Cancelled</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="166"/>
<source>Transfer cancelled </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="167"/>
<source>Error: </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="168"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="169"/>
<source>Connecting...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="170"/>
<source>Unable to connect</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="171"/>
<source>Requesting public key...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="172"/>
<source>Received public key...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="173"/>
<source>Recipient is not accepting transactions sent by IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="174"/>
<source>Transfer was not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="175"/>
<source>Invalid response received</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="176"/>
<source>Creating transaction...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="177"/>
<source>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 filename="../bitcoinstrings.cpp" line="180"/>
<source>Transaction creation failed</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="181"/>
<source>Transaction aborted</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="182"/>
<source>Lost connection, transaction cancelled</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="183"/>
<source>Sending payment...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="184"/>
<source>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 filename="../bitcoinstrings.cpp" line="188"/>
<source>Waiting for confirmation...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="189"/>
<source>The payment was sent, but the recipient was unable to verify it.
The transaction is recorded and will credit to the recipient,
but the comment information will be blank.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="193"/>
<source>Payment was sent, but an invalid response was received</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="194"/>
<source>Payment completed</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="195"/>
<source>Name</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="196"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="197"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="198"/>
<source>Bitcoin Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="199"/>
<source>This is one of your own addresses for receiving payments and cannot be entered in the address book. </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="202"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="203"/>
<source>Edit Address Label</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="204"/>
<source>Add Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="205"/>
<source>Bitcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="206"/>
<source>Bitcoin - Generating</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="207"/>
<source>Bitcoin - (not connected)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="208"/>
<source>&Open Bitcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="209"/>
<source>&Send Bitcoins</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="210"/>
<source>O&ptions...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="211"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="212"/>
<source>Program has crashed and will terminate. </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="213"/>
<source>Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="216"/>
<source>beta</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>main</name>
<message>
<location filename="../bitcoin.cpp" line="145"/>
<source>Bitcoin Qt</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | {'content_hash': '953ecca8faa9b13b59426f6826c8778f', 'timestamp': '', 'source': 'github', 'line_count': 2333, 'max_line_length': 413, 'avg_line_length': 42.251607372481786, 'alnum_prop': 0.6419202012721537, 'repo_name': 'zhao9jack/bitcoin-0.5.0', 'id': '74928d32c52d53aaa8aa9ed8d0de3e968b58e5a3', 'size': '98761', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/qt/locale/bitcoin_da.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '4311'}, {'name': 'C++', 'bytes': '1002632'}, {'name': 'Groff', 'bytes': '12851'}, {'name': 'Makefile', 'bytes': '3747'}, {'name': 'NSIS', 'bytes': '5629'}, {'name': 'Objective-C++', 'bytes': '2463'}, {'name': 'Python', 'bytes': '31009'}, {'name': 'QMake', 'bytes': '8346'}, {'name': 'Shell', 'bytes': '757'}]} |
'use strict';
// Pros module config
angular.module('pros').run(['Menus',
function (Menus) {
// Set top bar menu items
Menus.addMenuItem('topbar', 'Pros', 'pros', 'dropdown', '/pros(/create)?', true, null, 0);
Menus.addSubMenuItem('topbar', 'pros', 'Search by Pros', 'pros');
Menus.addSubMenuItem('topbar', 'pros', 'Add a new Pro', 'pros/create');
}
]); | {'content_hash': 'a14eef6f12f0cac0f1d6df511527da72', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 98, 'avg_line_length': 35.72727272727273, 'alnum_prop': 0.5903307888040712, 'repo_name': 'cshey15/ProGear', 'id': '2ceef54fc358be1cc3d5f0fc480717eab6e54866', 'size': '393', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/modules/pros/config/pros.client.config.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '3445'}, {'name': 'CSS', 'bytes': '945'}, {'name': 'HTML', 'bytes': '74489'}, {'name': 'JavaScript', 'bytes': '202207'}, {'name': 'Shell', 'bytes': '1366'}]} |
package org.apache.sysml.hops.rewrite;
import java.util.ArrayList;
import org.apache.sysml.hops.Hop;
import org.apache.sysml.hops.Hop.OpOp1;
import org.apache.sysml.hops.UnaryOp;
import org.apache.sysml.parser.Expression.ValueType;
/**
* Rule: RemoveUnnecessaryCasts. For all value type casts check
* if they are really necessary. If both cast input and output
* type are the same, the cast itself is redundant.
*
* There are two use case where this can arise: (1) automatically
* inserted casts on function inlining (in case of unknown value
* types), and (2) explicit script-level value type casts, that
* might be redundant according to the read input data.
*
* The benefit of this rewrite is negligible for scalars. However,
* when we support matrices with different value types, those casts
* might refer to matrices and with that incur large costs.
*
*/
public class RewriteRemoveUnnecessaryCasts extends HopRewriteRule
{
@Override
public ArrayList<Hop> rewriteHopDAGs(ArrayList<Hop> roots, ProgramRewriteStatus state) {
if( roots == null )
return null;
for( Hop h : roots )
rule_RemoveUnnecessaryCasts( h );
return roots;
}
@Override
public Hop rewriteHopDAG(Hop root, ProgramRewriteStatus state) {
if( root == null )
return root;
rule_RemoveUnnecessaryCasts( root );
return root;
}
@SuppressWarnings("unchecked")
private void rule_RemoveUnnecessaryCasts( Hop hop )
{
//check mark processed
if( hop.isVisited() )
return;
//recursively process childs
ArrayList<Hop> inputs = hop.getInput();
for( int i=0; i<inputs.size(); i++ )
rule_RemoveUnnecessaryCasts( inputs.get(i) );
//remove unnecessary value type cast
if( hop instanceof UnaryOp && HopRewriteUtils.isValueTypeCast(((UnaryOp)hop).getOp()) )
{
Hop in = hop.getInput().get(0);
ValueType vtIn = in.getValueType(); //type cast input
ValueType vtOut = hop.getValueType(); //type cast output
//if input/output types match, no need to cast
if( vtIn == vtOut && vtIn != ValueType.UNKNOWN )
{
ArrayList<Hop> parents = hop.getParent();
for( int i=0; i<parents.size(); i++ ) //for all parents
{
Hop p = parents.get(i);
ArrayList<Hop> pin = p.getInput();
for( int j=0; j<pin.size(); j++ ) //for all parent childs
{
Hop pinj = pin.get(j);
if( pinj == hop ) //found parent ref
{
//rehang cast input as child of cast consumer
pin.remove( j ); //remove cast ref
pin.add(j, in); //add ref to cast input
in.getParent().remove(hop); //remove cast from cast input parents
in.getParent().add( p ); //add parent to cast input parents
}
}
}
parents.clear();
}
}
//remove unnecessary data type casts
if( hop instanceof UnaryOp && hop.getInput().get(0) instanceof UnaryOp ) {
UnaryOp uop1 = (UnaryOp) hop;
UnaryOp uop2 = (UnaryOp) hop.getInput().get(0);
if( (uop1.getOp()==OpOp1.CAST_AS_MATRIX && uop2.getOp()==OpOp1.CAST_AS_SCALAR)
|| (uop1.getOp()==OpOp1.CAST_AS_SCALAR && uop2.getOp()==OpOp1.CAST_AS_MATRIX) ) {
Hop input = uop2.getInput().get(0);
//rewire parents
ArrayList<Hop> parents = (ArrayList<Hop>) hop.getParent().clone();
for( Hop p : parents )
HopRewriteUtils.replaceChildReference(p, hop, input);
}
}
//mark processed
hop.setVisited();
}
}
| {'content_hash': 'f3f1bf96c475e751ae5b176b440c2681', 'timestamp': '', 'source': 'github', 'line_count': 106, 'max_line_length': 89, 'avg_line_length': 31.81132075471698, 'alnum_prop': 0.6714116251482799, 'repo_name': 'nakul02/incubator-systemml', 'id': '224affe50350f411a0ef1153e0e1cabfa930d35f', 'size': '4181', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/apache/sysml/hops/rewrite/RewriteRemoveUnnecessaryCasts.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '31285'}, {'name': 'Batchfile', 'bytes': '22265'}, {'name': 'C', 'bytes': '8676'}, {'name': 'C++', 'bytes': '30804'}, {'name': 'CMake', 'bytes': '10312'}, {'name': 'Cuda', 'bytes': '30575'}, {'name': 'Java', 'bytes': '12984038'}, {'name': 'Jupyter Notebook', 'bytes': '36387'}, {'name': 'Makefile', 'bytes': '936'}, {'name': 'Protocol Buffer', 'bytes': '66399'}, {'name': 'Python', 'bytes': '195992'}, {'name': 'R', 'bytes': '668268'}, {'name': 'Scala', 'bytes': '186014'}, {'name': 'Shell', 'bytes': '152940'}]} |
<!-- THIS IS AUTO-GENERATED CONTENT. DO NOT MANUALLY EDIT. -->
This image is part of the [balena.io][balena] base image series for IoT devices. The image is optimized for use with [balena.io][balena] and [balenaOS][balena-os], but can be used in any Docker environment running on the appropriate architecture.
.
Some notable features in `balenalib` base images:
- Helpful package installer script called `install_packages` that abstracts away the specifics of the underlying package managers. It will install the named packages with smallest number of dependencies (ignore optional dependencies), clean up the package manager medata and retry if package install fails.
- Working with dynamically plugged devices: each `balenalib` base image has a default `ENTRYPOINT` which is defined as `ENTRYPOINT ["/usr/bin/entry.sh"]`, it checks if the `UDEV` flag is set to true or not (by adding `ENV UDEV=1`) and if true, it will start `udevd` daemon and the relevant device nodes in the container /dev will appear.
For more details, please check the [features overview](https://www.balena.io/docs/reference/base-images/base-images/#features-overview) in our documentation.
# [Image Variants][variants]
The `balenalib` images come in many flavors, each designed for a specific use case.
## `:<version>` or `:<version>-run`
This is the defacto image. The `run` variant is designed to be a slim and minimal variant with only runtime essentials packaged into it.
## `:<version>-build`
The build variant is a heavier image that includes many of the tools required for building from source. This reduces the number of packages that you will need to manually install in your Dockerfile, thus reducing the overall size of all images on your system.
[variants]: https://www.balena.io/docs/reference/base-images/base-images/#run-vs-build?ref=dockerhub
# About This Repository
This repository contains different flavours of .NET Core platform: .NET Core SDK, ASP.NET Core Runtime and .NET Core Runtime.
- .NET Core Runtime contains runtimes and libraries and is optimized for running .NET Core apps in production.
- ASP.NET Core Runtime contains ASP.NET Core and .NET Core runtimes and libraries and is optimized for running ASP.NET Core apps in production.
- .NET Core SDK is comprised of three parts: .NET Core CLI, .NET Core and ASP.NET Core. Use this variant for your development process (developing, building and testing applications).
## About .NET Core
[.NET Core](https://docs.microsoft.com/dotnet/core/) is a general purpose development platform maintained by Microsoft and the .NET community on [GitHub](https://github.com/dotnet/core). It is cross-platform, supporting Windows, macOS and Linux, and can be used in device, cloud, and embedded/IoT scenarios.
.NET has several capabilities that make development easier, including a utomatic memory management, (runtime) generic types, reflection, asynchrony, concurrency, and native interop. Millions of developers take advantage of these capabilities to efficiently build high-quality applications.
You can use C# to write .NET Core apps. C# is simple, powerful, type-safe, and object-oriented while retaining the expressiveness and elegance of C-style languages. Anyone familiar with C and similar languages will find it straightforward to write in C#.
[.NET Core](https://github.com/dotnet/core) is open source (MIT and Apache 2 licenses) and was contributed to the [.NET Foundation](http://dotnetfoundation.org) by Microsoft in 2014. It can be freely adopted by individuals and companies, including for personal, academic or commercial purposes. Multiple companies use .NET Core as part of apps, tools, new platforms and hosting services.
You are invited to [contribute new features](https://github.com/dotnet/core/blob/master/CONTRIBUTING.md), fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.
> https://docs.microsoft.com/dotnet/core/
Watch [dotnet/announcements](https://github.com/dotnet/announcements/labels/Docker) for Docker-related .NET announcements.
# Supported versions and respective `Dockerfile` links :
[`6.0-sdk`, `6.0-runtime`, `6.0-aspnet`, `5.0-sdk`, `5.0-runtime`, `5.0-aspnet`, `3.1-sdk`, `3.1-runtime`, `3.1-aspnet`](https://github.com/balena-io-library/base-images/tree/master/balena-base-images/dotnet/edison/debian/)
For more information about this image and its history, please see the [relevant manifest file (`edison-debian-dotnet`)](https://github.com/balena-io-library/official-images/blob/master/library/edison-debian-dotnet) in the [`balena-io-library/official-images` GitHub repo](https://github.com/balena-io-library/official-images).
# How to use this image
### Create a `Dockerfile` in your dotnet app project
```dockerfile
# specify the dotnet base image with your desired version dotnet:<version>
FROM balenalib/edison-debian-dotnet:latest
# replace this with your application's default port
EXPOSE 8000
```
You can then build and run the Docker image:
```console
$ docker build -t my-dotnet-app .
$ docker run -it --rm --name my-running-app my-dotnet-app
```
If you prefer Docker Compose:
```yml
version: "2"
services:
dotnet:
image: "balenalib/edison-debian-dotnet:latest"
user: "dotnet"
working_dir: /home/dotnet/app
volumes:
- ./:/home/dotnet/app
expose:
- "8000"
```
You can then run using Docker Compose:
```console
$ docker-compose up -d
```
# User Feedback
## Issues
If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/balena-io-library/base-images/issues).
## Contributing
You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.
Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/balena-io-library/base-images/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing.
## Documentation
Documentation for this image is stored in the [base images documentation][docs]. Check it out for list of all of our base images including many specialised ones for e.g. node, python, go, smaller images, etc.
You can also find more details about new features in `balenalib` base images in this [blog post][migration-docs]
[docs]: https://www.balena.io/docs/reference/base-images/base-images/#balena-base-images?ref=dockerhub
[variants]: https://www.balena.io/docs/reference/base-images/base-images/#run-vs-build?ref=dockerhub
[migration-docs]: https://www.balena.io/blog/new-year-new-balena-base-images/?ref=dockerhub
[balena]: https://balena.io/?ref=dockerhub
[balena-os]: https://www.balena.io/os/?ref=dockerhub | {'content_hash': '9fc07d8674eb1e0aefd53222ea909cae', 'timestamp': '', 'source': 'github', 'line_count': 122, 'max_line_length': 387, 'avg_line_length': 58.51639344262295, 'alnum_prop': 0.7655133772237008, 'repo_name': 'resin-io-library/base-images', 'id': 'a6f3ee6d00fd91a83fbfc0017c68a0cbb6e88c71', 'size': '7139', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'balena-base-images/docs/dockerhub/edison-debian-dotnet-full-description.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '71234697'}, {'name': 'JavaScript', 'bytes': '13096'}, {'name': 'Shell', 'bytes': '12051936'}, {'name': 'Smarty', 'bytes': '59789'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '269c1545f34efb3a96f00d13c4dbd2c4', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '73f468f84976df5ba773bdf720b89a850ce62258', 'size': '191', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Mnesithea/Mnesithea laevis/ Syn. Mnesithea perforata/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
FactoryGirl.define do
factory :news_article do
title "About the Company"
exposure_slug "my-news-article"
publication_date 1.day.ago
end
end
| {'content_hash': 'a9dbf507502e18b34110cf623bfbc79b', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 35, 'avg_line_length': 22.285714285714285, 'alnum_prop': 0.717948717948718, 'repo_name': 'Vizzuality/grid-arendal', 'id': 'e506418165d5e6ff8b78e07b7713eefc3ebfc55b', 'size': '186', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'spec/factories/news_article.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '236064'}, {'name': 'Gherkin', 'bytes': '17927'}, {'name': 'HTML', 'bytes': '27525609'}, {'name': 'JavaScript', 'bytes': '135270'}, {'name': 'Ruby', 'bytes': '352657'}]} |
package main
import (
"time"
)
type Snoozer interface {
Snooze()
}
type MaxSnoozer struct {
Max time.Duration
}
func (instance *MaxSnoozer) Snooze() {
time.Sleep(instance.Max)
}
func NewMaxSnoozer(max time.Duration) *MaxSnoozer {
return &MaxSnoozer{max}
}
type RandomSnoozer struct {
Min time.Duration
Max time.Duration
random Random
}
func (instance *RandomSnoozer) Snooze() {
randomSleep := instance.random.Duration(instance.Min, instance.Max)
time.Sleep(randomSleep)
}
func NewRandomSnoozer(min time.Duration, max time.Duration) *RandomSnoozer {
return &RandomSnoozer{min, max, &RealRandom{}}
}
type FakeSnoozer struct {
duration time.Duration
}
func (instance *FakeSnoozer) Snooze() {
time.Sleep(instance.duration)
}
func (instance *FakeSnoozer) SleepFor(duration time.Duration) {
instance.duration = duration
}
func NewFakeSnoozer() *FakeSnoozer {
return &FakeSnoozer{0}
}
| {'content_hash': '750ddc3ca7a055ede71a3c136038473b', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 76, 'avg_line_length': 17.51923076923077, 'alnum_prop': 0.743139407244786, 'repo_name': 'REAANDREW/enanos', 'id': '172d68504d27fa49133a165bdd7f1cdfc2a55abe', 'size': '911', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Snoozer.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '37860'}, {'name': 'Shell', 'bytes': '723'}]} |
package com.sastix.cms.common.services.hazelcast.config;
import java.util.List;
public class HazelcastProperties {
public String configurationName;
public String groupName;
public String groupPass;
public int networkPort;
public boolean portAutoIncrement;
public boolean multicastEnabled;
public boolean managementEnabled;
public String managementUrl;
public String multicastGroup;
public int multicastPort;
public int multicastTimeout;
public int multicastTTL;
public boolean tcpIpEnabled;
public List<String> tcpIpMembers;
public String mapName;
public int backupCount;
public int maxIdleSeconds;
public int timeToLiveSeconds;
public int maxSize;
public int evictionPercentage;
public boolean readBackupData;
public String evictionPolicy;
public String mergePolicy;
public int customTimeToLiveSeconds;
public HazelcastProperties() {
}
public HazelcastProperties(String configurationName, String groupName, String groupPass, int networkPort,
boolean portAutoIncrement, boolean multicastEnabled, boolean managementEnabled, String managementUrl,
String multicastGroup, int multicastPort, int multicastTimeout, int multicastTTL, boolean tcpIpEnabled,
List<String> tcpIpMembers, String mapName, int backupCount, int maxIdleSeconds, int timeToLiveSeconds,
int maxSize, int evictionPercentage, boolean readBackupData, String evictionPolicy, String mergePolicy,
int customTimeToLiveSeconds) {
this.configurationName = configurationName;
this.groupName = groupName;
this.groupPass = groupPass;
this.networkPort = networkPort;
this.portAutoIncrement = portAutoIncrement;
this.multicastEnabled = multicastEnabled;
this.managementEnabled = managementEnabled;
this.managementUrl = managementUrl;
this.multicastGroup = multicastGroup;
this.multicastPort = multicastPort;
this.multicastTimeout = multicastTimeout;
this.multicastTTL = multicastTTL;
this.tcpIpEnabled = tcpIpEnabled;
this.tcpIpMembers = tcpIpMembers;
this.mapName = mapName;
this.backupCount = backupCount;
this.maxIdleSeconds = maxIdleSeconds;
this.timeToLiveSeconds = timeToLiveSeconds;
this.maxSize = maxSize;
this.evictionPercentage = evictionPercentage;
this.readBackupData = readBackupData;
this.evictionPolicy = evictionPolicy;
this.mergePolicy = mergePolicy;
this.customTimeToLiveSeconds = customTimeToLiveSeconds;
}
public String getConfigurationName() {
return configurationName;
}
public void setConfigurationName(String configurationName) {
this.configurationName = configurationName;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getGroupPass() {
return groupPass;
}
public void setGroupPass(String groupPass) {
this.groupPass = groupPass;
}
public int getNetworkPort() {
return networkPort;
}
public void setNetworkPort(int networkPort) {
this.networkPort = networkPort;
}
public boolean isPortAutoIncrement() {
return portAutoIncrement;
}
public void setPortAutoIncrement(boolean portAutoIncrement) {
this.portAutoIncrement = portAutoIncrement;
}
public boolean isMulticastEnabled() {
return multicastEnabled;
}
public void setMulticastEnabled(boolean multicastEnabled) {
this.multicastEnabled = multicastEnabled;
}
public boolean isManagementEnabled() {
return managementEnabled;
}
public void setManagementEnabled(boolean managementEnabled) {
this.managementEnabled = managementEnabled;
}
public String getManagementUrl() {
return managementUrl;
}
public void setManagementUrl(String managementUrl) {
this.managementUrl = managementUrl;
}
public String getMulticastGroup() {
return multicastGroup;
}
public void setMulticastGroup(String multicastGroup) {
this.multicastGroup = multicastGroup;
}
public int getMulticastPort() {
return multicastPort;
}
public void setMulticastPort(int multicastPort) {
this.multicastPort = multicastPort;
}
public int getMulticastTimeout() {
return multicastTimeout;
}
public void setMulticastTimeout(int multicastTimeout) {
this.multicastTimeout = multicastTimeout;
}
public int getMulticastTTL() {
return multicastTTL;
}
public void setMulticastTTL(int multicastTTL) {
this.multicastTTL = multicastTTL;
}
public boolean isTcpIpEnabled() {
return tcpIpEnabled;
}
public void setTcpIpEnabled(boolean tcpIpEnabled) {
this.tcpIpEnabled = tcpIpEnabled;
}
public List<String> getTcpIpMembers() {
return tcpIpMembers;
}
public void setTcpIpMembers(List<String> tcpIpMembers) {
this.tcpIpMembers = tcpIpMembers;
}
public String getMapName() {
return mapName;
}
public void setMapName(String mapName) {
this.mapName = mapName;
}
public int getBackupCount() {
return backupCount;
}
public void setBackupCount(int backupCount) {
this.backupCount = backupCount;
}
public int getMaxIdleSeconds() {
return maxIdleSeconds;
}
public void setMaxIdleSeconds(int maxIdleSeconds) {
this.maxIdleSeconds = maxIdleSeconds;
}
public int getTimeToLiveSeconds() {
return timeToLiveSeconds;
}
public void setTimeToLiveSeconds(int timeToLiveSeconds) {
this.timeToLiveSeconds = timeToLiveSeconds;
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
public int getEvictionPercentage() {
return evictionPercentage;
}
public void setEvictionPercentage(int evictionPercentage) {
this.evictionPercentage = evictionPercentage;
}
public boolean isReadBackupData() {
return readBackupData;
}
public void setReadBackupData(boolean readBackupData) {
this.readBackupData = readBackupData;
}
public String getEvictionPolicy() {
return evictionPolicy;
}
public void setEvictionPolicy(String evictionPolicy) {
this.evictionPolicy = evictionPolicy;
}
public String getMergePolicy() {
return mergePolicy;
}
public void setMergePolicy(String mergePolicy) {
this.mergePolicy = mergePolicy;
}
public int getCustomTimeToLiveSeconds() {
return customTimeToLiveSeconds;
}
public void setCustomTimeToLiveSeconds(int customTimeToLiveSeconds) {
this.customTimeToLiveSeconds = customTimeToLiveSeconds;
}
}
| {'content_hash': 'c7d30b25c45f425ca333b8bbf93fff6e', 'timestamp': '', 'source': 'github', 'line_count': 284, 'max_line_length': 134, 'avg_line_length': 25.401408450704224, 'alnum_prop': 0.6766010535070696, 'repo_name': 'GiorPan/cms-parent-extend', 'id': '9f4d7155f24ebdbb0980db058e708379d0793dcd', 'size': '7832', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'common/services/src/main/java/com/sastix/cms/common/services/hazelcast/config/HazelcastProperties.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '878'}, {'name': 'HTML', 'bytes': '8173'}, {'name': 'Java', 'bytes': '412906'}]} |
namespace atom {
namespace api {
class MenuGtk : public Menu,
public ::MenuGtk::Delegate {
public:
MenuGtk();
protected:
virtual void Popup(Window* window) OVERRIDE;
private:
scoped_ptr<::MenuGtk> menu_gtk_;
DISALLOW_COPY_AND_ASSIGN(MenuGtk);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_MENU_GTK_H_
| {'content_hash': '5c8134901e3d0dc228f4b56c7758d62a', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 48, 'avg_line_length': 16.130434782608695, 'alnum_prop': 0.6549865229110512, 'repo_name': 'Ex-sabagostar/atom-shell', 'id': '3c39fb730b7bd7939d6f0a7af834eb6d8fe8fe5c', 'size': '710', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'atom/browser/api/atom_api_menu_gtk.h', 'mode': '33188', 'license': 'mit', 'language': []} |
/*
* 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/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudsearch.v1.model;
/**
* An action that describes the behavior when the form is submitted. For example, an Apps Script can
* be invoked to handle the form.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Search API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class AppsDynamiteSharedAction extends com.google.api.client.json.GenericJson {
/**
* Apps Script function to invoke when the containing element is clicked/activated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String function;
/**
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String interaction;
/**
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String loadIndicator;
/**
* List of action parameters.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<AppsDynamiteSharedActionActionParameter> parameters;
/**
* Apps Script function to invoke when the containing element is clicked/activated.
* @return value or {@code null} for none
*/
public java.lang.String getFunction() {
return function;
}
/**
* Apps Script function to invoke when the containing element is clicked/activated.
* @param function function or {@code null} for none
*/
public AppsDynamiteSharedAction setFunction(java.lang.String function) {
this.function = function;
return this;
}
/**
* @return value or {@code null} for none
*/
public java.lang.String getInteraction() {
return interaction;
}
/**
* @param interaction interaction or {@code null} for none
*/
public AppsDynamiteSharedAction setInteraction(java.lang.String interaction) {
this.interaction = interaction;
return this;
}
/**
* @return value or {@code null} for none
*/
public java.lang.String getLoadIndicator() {
return loadIndicator;
}
/**
* @param loadIndicator loadIndicator or {@code null} for none
*/
public AppsDynamiteSharedAction setLoadIndicator(java.lang.String loadIndicator) {
this.loadIndicator = loadIndicator;
return this;
}
/**
* List of action parameters.
* @return value or {@code null} for none
*/
public java.util.List<AppsDynamiteSharedActionActionParameter> getParameters() {
return parameters;
}
/**
* List of action parameters.
* @param parameters parameters or {@code null} for none
*/
public AppsDynamiteSharedAction setParameters(java.util.List<AppsDynamiteSharedActionActionParameter> parameters) {
this.parameters = parameters;
return this;
}
@Override
public AppsDynamiteSharedAction set(String fieldName, Object value) {
return (AppsDynamiteSharedAction) super.set(fieldName, value);
}
@Override
public AppsDynamiteSharedAction clone() {
return (AppsDynamiteSharedAction) super.clone();
}
}
| {'content_hash': '9e2544f41055bf6cb52e224f6585647f', 'timestamp': '', 'source': 'github', 'line_count': 133, 'max_line_length': 182, 'avg_line_length': 30.1203007518797, 'alnum_prop': 0.7139291063404892, 'repo_name': 'googleapis/google-api-java-client-services', 'id': '47cc5d2b6d030d28051ae7fc228160f65d6bb67b', 'size': '4006', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'clients/google-api-services-cloudsearch/v1/2.0.0/com/google/api/services/cloudsearch/v1/model/AppsDynamiteSharedAction.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<!--
~ Copyright 2013 Matt Sicker and Contributors
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<assembly>
<id>bin</id>
<formats>
<format>zip</format>
</formats>
<!-- Include source -->
<fileSets>
<fileSet>
<directory>src/main/java</directory>
<outputDirectory>src/java</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
<fileSet>
<includes>
<include>README*</include>
<include>LICENSE*</include>
</includes>
</fileSet>
</fileSets>
<!-- Dependencies and out jar file should go into lib -->
<dependencySets>
<dependencySet>
<outputDirectory>lib</outputDirectory>
</dependencySet>
</dependencySets>
<baseDirectory>${project.artifactId}</baseDirectory>
</assembly>
| {'content_hash': '6a45aa9cf71eab48c2d82df5a5446a38', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 76, 'avg_line_length': 30.674418604651162, 'alnum_prop': 0.6793025018953753, 'repo_name': 'jvz/dynunit', 'id': 'a34fba6e64f9a0bc399a29a13a9070c643d7c904', 'size': '1319', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/assembly/dep.xml', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '1730'}, {'name': 'Java', 'bytes': '815576'}, {'name': 'Shell', 'bytes': '12537'}]} |
@implementation WeatherDescription
@synthesize weatherID = _weatherID;
@synthesize description = _description;
@synthesize pictureURL = _pictureURL;
// class meta-data method
// note: this method is only for internal use, DO NOT CHANGE!
+(PicoClassSchema *)getClassMetaData {
return nil;
}
// property meta-data method
// note: this method is only for internal use, DO NOT CHANGE!
+(NSMutableDictionary *)getPropertyMetaData {
NSMutableDictionary *map = [OrderedDictionary dictionary];
PicoPropertySchema *ps = nil;
ps = [[PicoPropertySchema alloc] initWithKind:PICO_KIND_ELEMENT xmlName:@"WeatherID" propertyName:@"weatherID" type:PICO_TYPE_SHORT clazz:nil];
[map setObject:ps forKey:@"weatherID"];
ps = [[PicoPropertySchema alloc] initWithKind:PICO_KIND_ELEMENT xmlName:@"Description" propertyName:@"description" type:PICO_TYPE_STRING clazz:nil];
[map setObject:ps forKey:@"description"];
ps = [[PicoPropertySchema alloc] initWithKind:PICO_KIND_ELEMENT xmlName:@"PictureURL" propertyName:@"pictureURL" type:PICO_TYPE_STRING clazz:nil];
[map setObject:ps forKey:@"pictureURL"];
return map;
}
@end
| {'content_hash': '3b836638dff5bd84ead27539ca19f52e', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 152, 'avg_line_length': 39.724137931034484, 'alnum_prop': 0.7421875, 'repo_name': 'maxep/PicoKit', 'id': '616750c13b5f22f3eb5872c12a2b7f68c9ffdf2f', 'size': '1316', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Examples/Weather/Weather/com/cdyne/ws/weatherws/WeatherDescription.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1834'}, {'name': 'JavaScript', 'bytes': '1796'}, {'name': 'Objective-C', 'bytes': '313328'}, {'name': 'Ruby', 'bytes': '2392'}]} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NuKeeper.Abstractions
{
public static class LinqAsync
{
/// <summary>
/// Filter a list by an async operation on each element
/// Code from: https://codereview.stackexchange.com/a/32162
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <param name="predicate"></param>
/// <returns></returns>
public static async Task<IEnumerable<T>> WhereAsync<T>(this IEnumerable<T> items, Func<T, Task<bool>> predicate)
{
var itemTaskList = items
.Select(item => new { Item = item, PredTask = predicate.Invoke(item) })
.ToList();
await Task.WhenAll(itemTaskList.Select(x => x.PredTask));
return itemTaskList
.Where(x => x.PredTask.Result)
.Select(x => x.Item);
}
/// <summary>
/// Async first or default implementation
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <param name="predicate"></param>
/// <returns></returns>
public static async Task<T> FirstOrDefaultAsync<T>(this IEnumerable<T> items, Func<T, Task<bool>> predicate)
{
var itemTaskList = items
.Select(item => new { Item = item, PredTask = predicate.Invoke(item) })
.ToList();
await Task.WhenAll(itemTaskList.Select(x => x.PredTask));
var firstOrDefault = itemTaskList.FirstOrDefault(x => x.PredTask.Result);
if (firstOrDefault == null)
{
return await Task.FromResult(default(T));
}
return firstOrDefault.Item;
}
}
}
| {'content_hash': 'cfc427a0c58f57e911bd0e50f3f8c2e5', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 120, 'avg_line_length': 34.7037037037037, 'alnum_prop': 0.5528281750266809, 'repo_name': 'NuKeeperDotNet/NuKeeper', 'id': '9bfa6b17e3356dbd6f07d51499a91babf90f0ef1', 'size': '1874', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'NuKeeper.Abstractions/LinqAsync.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '420'}, {'name': 'C#', 'bytes': '1085682'}, {'name': 'CSS', 'bytes': '74432'}, {'name': 'Dockerfile', 'bytes': '416'}, {'name': 'HTML', 'bytes': '37761'}, {'name': 'JavaScript', 'bytes': '42225'}, {'name': 'Shell', 'bytes': '422'}]} |
package org.elasticsearch.discovery.zen;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportConnectionListener;
import org.elasticsearch.transport.TransportService;
import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds;
/**
* A base class for {@link MasterFaultDetection} & {@link NodesFaultDetection},
* making sure both use the same setting.
*/
public abstract class FaultDetection extends AbstractComponent {
public static final Setting<Boolean> CONNECT_ON_NETWORK_DISCONNECT_SETTING =
Setting.boolSetting("discovery.zen.fd.connect_on_network_disconnect", false, Property.NodeScope);
public static final Setting<TimeValue> PING_INTERVAL_SETTING =
Setting.positiveTimeSetting("discovery.zen.fd.ping_interval", timeValueSeconds(1), Property.NodeScope);
public static final Setting<TimeValue> PING_TIMEOUT_SETTING =
Setting.timeSetting("discovery.zen.fd.ping_timeout", timeValueSeconds(30), Property.NodeScope);
public static final Setting<Integer> PING_RETRIES_SETTING =
Setting.intSetting("discovery.zen.fd.ping_retries", 3, Property.NodeScope);
public static final Setting<Boolean> REGISTER_CONNECTION_LISTENER_SETTING =
Setting.boolSetting("discovery.zen.fd.register_connection_listener", true, Property.NodeScope);
protected final ThreadPool threadPool;
protected final ClusterName clusterName;
protected final TransportService transportService;
// used mainly for testing, should always be true
protected final boolean registerConnectionListener;
protected final FDConnectionListener connectionListener;
protected final boolean connectOnNetworkDisconnect;
protected final TimeValue pingInterval;
protected final TimeValue pingRetryTimeout;
protected final int pingRetryCount;
public FaultDetection(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterName clusterName) {
super(settings);
this.threadPool = threadPool;
this.transportService = transportService;
this.clusterName = clusterName;
this.connectOnNetworkDisconnect = CONNECT_ON_NETWORK_DISCONNECT_SETTING.get(settings);
this.pingInterval = PING_INTERVAL_SETTING.get(settings);
this.pingRetryTimeout = PING_TIMEOUT_SETTING.get(settings);
this.pingRetryCount = PING_RETRIES_SETTING.get(settings);
this.registerConnectionListener = REGISTER_CONNECTION_LISTENER_SETTING.get(settings);
this.connectionListener = new FDConnectionListener();
if (registerConnectionListener) {
transportService.addConnectionListener(connectionListener);
}
}
public void close() {
transportService.removeConnectionListener(connectionListener);
}
/**
* This method will be called when the {@link org.elasticsearch.transport.TransportService} raised a node disconnected event
*/
abstract void handleTransportDisconnect(DiscoveryNode node);
private class FDConnectionListener implements TransportConnectionListener {
@Override
public void onNodeConnected(DiscoveryNode node) {
}
@Override
public void onNodeDisconnected(DiscoveryNode node) {
handleTransportDisconnect(node);
}
}
}
| {'content_hash': '5d62d5dabe984344d3bd92987ff6e2d3', 'timestamp': '', 'source': 'github', 'line_count': 86, 'max_line_length': 129, 'avg_line_length': 43.2093023255814, 'alnum_prop': 0.7642626480086114, 'repo_name': 'gmarz/elasticsearch', 'id': 'f1f8b28ad09232fbc052eca7b707fcb3625916ec', 'size': '4504', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/org/elasticsearch/discovery/zen/FaultDetection.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '10561'}, {'name': 'Batchfile', 'bytes': '13128'}, {'name': 'Emacs Lisp', 'bytes': '3341'}, {'name': 'FreeMarker', 'bytes': '45'}, {'name': 'Groovy', 'bytes': '269282'}, {'name': 'HTML', 'bytes': '3397'}, {'name': 'Java', 'bytes': '38677838'}, {'name': 'Perl', 'bytes': '7271'}, {'name': 'Python', 'bytes': '52711'}, {'name': 'Shell', 'bytes': '108256'}]} |
import os
import setuptools
from vcloudpy import __version__
setuptools.setup(
name='vcloudpy',
version=__version__,
description='vCloud Python Simple Client',
license='Apache License (2.0)',
author='Patrick Dunnigan',
author_email='[email protected]',
url='https://github.com/cloudsidekick/vcloudpy',
packages=setuptools.find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Environment :: No Input/Output (Daemon)',
],
py_modules=[])
| {'content_hash': '3a115f195dc60994dd5ec7a433589063', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 61, 'avg_line_length': 31.62962962962963, 'alnum_prop': 0.6370023419203747, 'repo_name': 'cloudsidekick/vcloudpy', 'id': 'b0127b79fa6fce9f43072f2073b12dcd07b57447', 'size': '1580', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'setup.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '84888'}]} |
package org.apache.beam.sdk.io.kudu;
import static org.apache.beam.sdk.io.kudu.KuduTestUtils.COL_ID;
import static org.apache.beam.sdk.io.kudu.KuduTestUtils.COL_NAME;
import static org.apache.beam.sdk.io.kudu.KuduTestUtils.GenerateUpsert;
import static org.apache.beam.sdk.io.kudu.KuduTestUtils.SCHEMA;
import static org.apache.beam.sdk.io.kudu.KuduTestUtils.createTableOptions;
import static org.apache.beam.sdk.io.kudu.KuduTestUtils.rowCount;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.util.Arrays;
import java.util.Collections;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.io.GenerateSequence;
import org.apache.beam.sdk.io.common.IOTestPipelineOptions;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Count;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.apache.beam.sdk.values.PCollection;
import org.apache.kudu.client.AsyncKuduClient;
import org.apache.kudu.client.KuduClient;
import org.apache.kudu.client.KuduException;
import org.apache.kudu.client.KuduPredicate;
import org.apache.kudu.client.KuduTable;
import org.apache.kudu.client.RowResult;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* A test of {@link org.apache.beam.sdk.io.kudu.KuduIO} on an independent Kudu instance.
*
* <p>This test requires a running instance of Kudu. Pass in connection information using
* PipelineOptions:
*
* <pre>
* ./gradlew integrationTest -p sdks/java/io/kudu -DintegrationTestPipelineOptions='[
* "--kuduMasterAddresses=127.0.0.1",
* "--kuduTable=beam-integration-test",
* "--numberOfRecords=100000" ]'
* --tests org.apache.beam.sdk.io.kudu.KuduIOIT
* -DintegrationTestRunner=direct
* </pre>
*
* <p>To start a Kudu server in docker you can use the following:
*
* <pre>
* docker pull usuresearch/apache-kudu docker run -d --rm --name apache-kudu -p 7051:7051 \
* -p 7050:7050 -p 8051:8051 -p 8050:8050 usuresearch/apache-kudu ```
* </pre>
*
* <p>See <a href="https://hub.docker.com/r/usuresearch/apache-kudu/">for information about this
* image</a>.
*
* <p>Once running you may need to visit <a href="http://localhost:8051/masters">the masters
* list</a> and copy the host (e.g. <code>host: "e94929167e2a"</code>) adding it to your <code>
* etc/hosts</code> file pointing to localhost e.g.:
*
* <pre>
* 127.0.0.1 localhost e94929167e2a
* </pre>
*/
@RunWith(JUnit4.class)
public class KuduIOIT {
/** KuduIOIT options. */
public interface KuduPipelineOptions extends IOTestPipelineOptions {
@Description("Kudu master addresses (comma separated address list)")
@Default.String("127.0.0.1:7051")
String getKuduMasterAddresses();
void setKuduMasterAddresses(String masterAddresses);
@Description("Kudu table")
@Default.String("beam-integration-test")
String getKuduTable();
void setKuduTable(String name);
}
private static KuduPipelineOptions options;
private static KuduClient client;
private static KuduTable kuduTable;
@Rule public final TestPipeline writePipeline = TestPipeline.create();
@Rule public TestPipeline readPipeline = TestPipeline.create();
@Rule public ExpectedException thrown = ExpectedException.none();
@BeforeClass
public static void setUp() throws KuduException {
PipelineOptionsFactory.register(KuduPipelineOptions.class);
options = TestPipeline.testingPipelineOptions().as(KuduPipelineOptions.class);
// synchronous operations
client =
new AsyncKuduClient.AsyncKuduClientBuilder(options.getKuduMasterAddresses())
.build()
.syncClient();
if (client.tableExists(options.getKuduTable())) {
client.deleteTable(options.getKuduTable());
}
kuduTable =
client.createTable(options.getKuduTable(), KuduTestUtils.SCHEMA, createTableOptions());
}
@AfterClass
public static void tearDown() throws Exception {
try {
if (client.tableExists(options.getKuduTable())) {
client.deleteTable(options.getKuduTable());
}
} finally {
client.close();
}
}
@Test
public void testWriteThenRead() throws Exception {
runWrite();
runReadAll();
readPipeline = TestPipeline.create();
runReadProjectedColumns();
readPipeline = TestPipeline.create();
runReadWithPredicates();
}
private void runReadAll() {
// Lambdas erase too much type information so specify the coder
PCollection<String> output =
readPipeline.apply(
KuduIO.<String>read()
.withMasterAddresses(options.getKuduMasterAddresses())
.withTable(options.getKuduTable())
.withParseFn(
(SerializableFunction<RowResult, String>) input -> input.getString(COL_NAME))
.withCoder(StringUtf8Coder.of()));
PAssert.thatSingleton(output.apply("Count", Count.globally()))
.isEqualTo((long) options.getNumberOfRecords());
readPipeline.run().waitUntilFinish();
}
private void runReadWithPredicates() {
PCollection<String> output =
readPipeline.apply(
"Read with predicates",
KuduIO.<String>read()
.withMasterAddresses(options.getKuduMasterAddresses())
.withTable(options.getKuduTable())
.withParseFn(
(SerializableFunction<RowResult, String>) input -> input.getString(COL_NAME))
.withPredicates(
Arrays.asList(
KuduPredicate.newComparisonPredicate(
SCHEMA.getColumn(COL_ID), KuduPredicate.ComparisonOp.GREATER_EQUAL, 2),
KuduPredicate.newComparisonPredicate(
SCHEMA.getColumn(COL_ID), KuduPredicate.ComparisonOp.LESS, 7)))
.withCoder(StringUtf8Coder.of()));
output.apply(Count.globally());
PAssert.thatSingleton(output.apply("Count", Count.globally())).isEqualTo((long) 5);
readPipeline.run().waitUntilFinish();
}
/**
* Tests that the projected columns are passed down to the Kudu scanner by attempting to read the
* {@value KuduTestUtils#COL_NAME} in the parse function when it is omitted.
*/
private void runReadProjectedColumns() {
thrown.expect(IllegalArgumentException.class);
readPipeline
.apply(
"Read with projected columns",
KuduIO.<String>read()
.withMasterAddresses(options.getKuduMasterAddresses())
.withTable(options.getKuduTable())
.withParseFn(
(SerializableFunction<RowResult, String>) input -> input.getString(COL_NAME))
.withProjectedColumns(Collections.singletonList(COL_ID))) // COL_NAME excluded
.setCoder(StringUtf8Coder.of());
readPipeline.run().waitUntilFinish();
}
private void runWrite() throws Exception {
writePipeline
.apply("Generate sequence", GenerateSequence.from(0).to(options.getNumberOfRecords()))
.apply(
"Write records to Kudu",
KuduIO.write()
.withMasterAddresses(options.getKuduMasterAddresses())
.withTable(options.getKuduTable())
.withFormatFn(new GenerateUpsert()));
writePipeline.run().waitUntilFinish();
assertThat(
"Wrong number of records in table",
rowCount(kuduTable),
equalTo(options.getNumberOfRecords()));
}
}
| {'content_hash': '1b810352901fec994e76cae2be83d6cc', 'timestamp': '', 'source': 'github', 'line_count': 214, 'max_line_length': 99, 'avg_line_length': 36.88317757009346, 'alnum_prop': 0.6931458254149246, 'repo_name': 'lukecwik/incubator-beam', 'id': '1add8f2940ae34565173540a92a79835070f0eed', 'size': '8698', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'sdks/java/io/kudu/src/test/java/org/apache/beam/sdk/io/kudu/KuduIOIT.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '1598'}, {'name': 'C', 'bytes': '3869'}, {'name': 'CSS', 'bytes': '4957'}, {'name': 'Cython', 'bytes': '70760'}, {'name': 'Dart', 'bytes': '830463'}, {'name': 'Dockerfile', 'bytes': '54446'}, {'name': 'FreeMarker', 'bytes': '7933'}, {'name': 'Go', 'bytes': '5375910'}, {'name': 'Groovy', 'bytes': '923345'}, {'name': 'HCL', 'bytes': '101921'}, {'name': 'HTML', 'bytes': '182819'}, {'name': 'Java', 'bytes': '40844089'}, {'name': 'JavaScript', 'bytes': '120093'}, {'name': 'Jupyter Notebook', 'bytes': '55818'}, {'name': 'Kotlin', 'bytes': '215314'}, {'name': 'Lua', 'bytes': '3620'}, {'name': 'Python', 'bytes': '10573729'}, {'name': 'SCSS', 'bytes': '318158'}, {'name': 'Sass', 'bytes': '25936'}, {'name': 'Scala', 'bytes': '1429'}, {'name': 'Shell', 'bytes': '362995'}, {'name': 'Smarty', 'bytes': '2618'}, {'name': 'Thrift', 'bytes': '3260'}, {'name': 'TypeScript', 'bytes': '1955893'}]} |
namespace settings {
// The base class handler of Javascript messages of settings pages.
class SettingsPageUIHandler : public content::WebUIMessageHandler {
public:
SettingsPageUIHandler();
~SettingsPageUIHandler() override;
protected:
// Helper method for responding to JS requests initiated with
// cr.sendWithPromise(), for the case where the returned promise should be
// resolved (request succeeded).
void ResolveJavascriptCallback(const base::Value& callback_id,
const base::Value& response);
// Helper method for responding to JS requests initiated with
// cr.sendWithPromise(), for the case where the returned promise should be
// rejected (request failed).
void RejectJavascriptCallback(const base::Value& callback_id,
const base::Value& response);
private:
// SettingsPageUIHandler subclasses must be JavaScript-lifecycle safe.
void OnJavascriptAllowed() override = 0;
void OnJavascriptDisallowed() override = 0;
DISALLOW_COPY_AND_ASSIGN(SettingsPageUIHandler);
};
} // namespace settings
#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_SETTINGS_PAGE_UI_HANDLER_H_
| {'content_hash': '256f96347af1ba09c63558dc2e85d3b0', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 76, 'avg_line_length': 36.71875, 'alnum_prop': 0.7251063829787234, 'repo_name': 'heke123/chromium-crosswalk', 'id': 'b359130dd9df467c350b6b048981060b0af1d9bd', 'size': '1590', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'chrome/browser/ui/webui/settings/settings_page_ui_handler.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
var MenuOption = require('./menuoption');
function CheckBox(title, textOptions){
this.menuOption = new MenuOption(title, textOptions);
this.container = this.menuOption.container;
this.uncheckedTex = null;
this.checkedTex = null;
this.checkBoxSprite = new PIXI.Sprite(null);
this.menuOption.graphic.addChild(this.checkBoxSprite);
this.checkBoxSprite.x = -32 - 4;
this.isChecked = false;
this.checkBoxAction = null;
var self = this;
this.menuOption.setPressAction(function(){
self.setCheck(!self.isChecked);
});
}
CheckBox.prototype.setCheckTextures = function(uncheckedTex, checkedTex){
this.uncheckedTex = uncheckedTex;
this.checkedTex = checkedTex;
this.checkBoxSprite.texture = (this.isChecked) ? this.checkedTex : this.uncheckedTex;
}
CheckBox.prototype.setCheckBoxAction = function(action){
this.checkBoxAction = action;
}
CheckBox.prototype.setCheck = function(expression){
if (typeof(this.checkBoxAction) == "function") this.checkBoxAction(expression);
this.checkBoxSprite.texture = (expression) ? this.checkedTex : this.uncheckedTex;
this.isChecked = expression;
}
module.exports = CheckBox;
| {'content_hash': '0311e7d1b63dd1ce55c3e3135910e457', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 89, 'avg_line_length': 33.94285714285714, 'alnum_prop': 0.7272727272727273, 'repo_name': 'Coteh/MinesweeperClone', 'id': '20fbb2ce726413070b96ea5b9cfe7c47668d450d', 'size': '1188', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'client/gui/checkbox.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '62'}, {'name': 'HTML', 'bytes': '397'}, {'name': 'JavaScript', 'bytes': '46099'}, {'name': 'Shell', 'bytes': '131'}]} |
# clog
a super-simple c logging library
I got tired of littering my C code with printf statements, so I wrote a little library for logging.
## Compiling
`cc -c -o clog.o clog.c` (or simply use `make`)
## Using
```
/* initialize clog to log to stdout using the default timestamp format */
clog_init(0, CLOG_DEFAULT, 0);
clog_warn("this is a %s message", "warning");
clog_debug("this message won't show if I don't have log level set to at least CLOG_DEBUG");
```
Supports 7 log levels, in order from least to most verbose:
- CLOG_NONE
- CLOG_FATAL
- CLOG_ERROR
- CLOG_WARN
- CLOG_INFO
- CLOG_DEBUG
- CLOG_TRACE
The default is CLOG_WARN.
| {'content_hash': '20a67afa427d50b156290dfc0b4bf7f4', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 100, 'avg_line_length': 22.066666666666666, 'alnum_prop': 0.6888217522658611, 'repo_name': 'cliffeh/clog', 'id': '10bfd9d65a85771c6c1d4e534f19fd5221dce305', 'size': '662', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '3718'}, {'name': 'Makefile', 'bytes': '117'}]} |
package samples.expert;
import java.io.*;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.*;
import water.util.Utils;
import com.google.gson.*;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonWriter;
/**
* Invokes H2O functionality through the Web API.
*/
public class WebAPI {
static final String URL = "http://127.0.0.1:54321";
static final File JSON_FILE = new File(Utils.tmp(), "model.json");
public static void main(String[] args) throws Exception {
listJobs();
exportModel();
importModel();
}
/**
* Lists jobs currently running.
*/
static void listJobs() throws Exception {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(URL + "/Jobs.json");
int status = client.executeMethod(get);
if( status != 200 )
throw new Exception(get.getStatusText());
Gson gson = new Gson();
JobsRes res = gson.fromJson(new InputStreamReader(get.getResponseBodyAsStream()), JobsRes.class);
System.out.println("Running jobs:");
for( Job job : res.jobs )
System.out.println(job.description + " " + job.destination_key);
get.releaseConnection();
}
public static class JobsRes {
Job[] jobs;
}
public static class Job {
String key;
String description;
String destination_key;
String end_time;
String exception;
}
/**
* Exports a model to a JSON file.
*/
static void exportModel() throws Exception {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(URL + "/2/ExportModel.json?model=MyInitialNeuralNet");
int status = client.executeMethod(get);
if( status != 200 )
throw new Exception(get.getStatusText());
JsonObject response = (JsonObject) new JsonParser().parse(new InputStreamReader(get.getResponseBodyAsStream()));
JsonElement model = response.get("model");
JsonWriter writer = new JsonWriter(new FileWriter(JSON_FILE));
writer.setLenient(true);
writer.setIndent(" ");
Streams.write(model, writer);
writer.close();
get.releaseConnection();
}
/**
* Imports a model from a JSON file.
*/
public static void importModel() throws Exception {
// Upload file to H2O
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(URL + "/Upload.json?key=" + JSON_FILE.getName());
Part[] parts = { new FilePart(JSON_FILE.getName(), JSON_FILE) };
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
if( 200 != client.executeMethod(post) )
throw new RuntimeException("Request failed: " + post.getStatusLine());
post.releaseConnection();
// Parse the key into a model
GetMethod get = new GetMethod(URL + "/2/ImportModel.json?" //
+ "destination_key=MyImportedNeuralNet&" //
+ "type=NeuralNetModel&" //
+ "json=" + JSON_FILE.getName());
if( 200 != client.executeMethod(get) )
throw new RuntimeException("Request failed: " + get.getStatusLine());
get.releaseConnection();
}
}
| {'content_hash': '358237cfe9284221379351f792e9ce7f', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 116, 'avg_line_length': 32.27272727272727, 'alnum_prop': 0.6801251956181533, 'repo_name': 'woobe/h2o', 'id': '0e89fc75c5986677325dce52d63b33903e879d96', 'size': '3195', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'h2o-samples/src/main/java/samples/expert/WebAPI.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
import rospy
import random
from airbus_ssm_core import ssm_state
class Test1(ssm_state.ssmState):
'''@SSM
Description : Test skill that add +1 to a user data test and return sucess.
User-data :
- test : an int (if not created in the datamodel will be init to 0)
Outcome :
- success : sucessfully add +1 or created the data test
'''
def __init__(self):
ssm_state.ssmState.__init__(self,outcomes=["success"], io_keys=["test"])
def execution(self, ud):
rospy.sleep(2)
if("test" in ud):
ud.test = int(ud.test) + 1
else:
ud.test = 0
print("Test : " + str(ud.test))
return "success"
class Test2(ssm_state.ssmState):
'''@SSM
Description : A test state with a random outcomes using an inside counter
User-data : None
Outcome :
- success : test if the counter inside the state is above 10
- retry : test if the counter inside the state is above 5 and below 10
- next : test if the counter inside the state is above 0 and below 5
'''
def __init__(self):
ssm_state.ssmState.__init__(self,outcomes=["success","retry","next"])
self.cpt_ = 0
def execution(self, ud):
rospy.sleep(1)
choice = random.randint(1,3)
self.cpt_ = self.cpt_ + choice
if(self.cpt_ > 10):
print("Test2 : success")
return "success"
elif(self.cpt_ > 5):
print("Test2 : Retry")
return "retry"
elif(self.cpt_> 0):
print("Test2 : Next")
return "next"
else:
print("Test2 : success")
return "success"
class Test3(ssm_state.ssmState):
'''@SSM
Description : A test state with a random outcomes with a 50/50.
User-data : None
Outcome :
- success : if the random int is equal to 1
- failed : otherwise
'''
def __init__(self):
ssm_state.ssmState.__init__(self,outcomes=["success","failed"])
def execution(self, ud):
rospy.sleep(1)
choice = random.randint(1,2)
if(choice == 1):
print("Test3 : success")
return "success"
else:
print("Test3 : failed")
return "failed"
| {'content_hash': '143b30965f6337f9dea5f74a35f2003f', 'timestamp': '', 'source': 'github', 'line_count': 82, 'max_line_length': 80, 'avg_line_length': 28.134146341463413, 'alnum_prop': 0.5491980927611617, 'repo_name': 'ipa-led/airbus_coop', 'id': 'be572e130ace29dabdbe6b7d2e851276fb7ee2e6', 'size': '2990', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'airbus_ssm_tutorial/src/ssm_test_skills/skills.py', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CMake', 'bytes': '4285'}, {'name': 'CSS', 'bytes': '33266'}, {'name': 'HTML', 'bytes': '2608207'}, {'name': 'JavaScript', 'bytes': '3265'}, {'name': 'Python', 'bytes': '631283'}, {'name': 'Shell', 'bytes': '518'}]} |
@class OTPAuthURL;
@class Decoder;
@protocol OTPAuthURLEntryControllerDelegate;
@interface OTPAuthURLEntryController : UIViewController
<UITextFieldDelegate,
UINavigationControllerDelegate,
DecoderDelegate,
UIAlertViewDelegate,
AVCaptureVideoDataOutputSampleBufferDelegate> {
@private
dispatch_queue_t queue_;
}
@property(nonatomic, readwrite, assign) id<OTPAuthURLEntryControllerDelegate> delegate;
@property(nonatomic, readwrite, retain) IBOutlet UITextField *accountName;
@property(nonatomic, readwrite, retain) IBOutlet UITextField *accountKey;
@property(nonatomic, readwrite, retain) IBOutlet UILabel *accountNameLabel;
@property(nonatomic, readwrite, retain) IBOutlet UILabel *accountKeyLabel;
@property(nonatomic, readwrite, retain) IBOutlet UISegmentedControl *accountType;
@property(nonatomic, readwrite, retain) IBOutlet UIButton *scanBarcodeButton;
@property(nonatomic, readwrite, retain) IBOutlet UIScrollView *scrollView;
- (IBAction)accountNameDidEndOnExit:(id)sender;
- (IBAction)accountKeyDidEndOnExit:(id)sender;
- (IBAction)cancel:(id)sender;
- (IBAction)done:(id)sender;
- (IBAction)scanBarcode:(id)sender;
@end
@protocol OTPAuthURLEntryControllerDelegate
- (void)authURLEntryController:(OTPAuthURLEntryController*)controller
didCreateAuthURL:(OTPAuthURL *)authURL;
@end
| {'content_hash': '2ac28af58dd53edc1a5448bf600e327a', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 87, 'avg_line_length': 35.23684210526316, 'alnum_prop': 0.8043315907393578, 'repo_name': 'fargly/google-authenticator', 'id': '5b772c56c1b37daed3b9a55787b3153cd0fc502c', 'size': '2068', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'mobile/ios/Classes/OTPAuthURLEntryController.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '119312'}, {'name': 'Java', 'bytes': '192759'}, {'name': 'Objective-C', 'bytes': '137774'}, {'name': 'Python', 'bytes': '300'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_31) on Wed Dec 17 20:48:30 PST 2014 -->
<title>Uses of Class javax.security.sasl.AuthorizeCallback (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class javax.security.sasl.AuthorizeCallback (Java Platform SE 8 )";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../javax/security/sasl/AuthorizeCallback.html" title="class in javax.security.sasl">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><strong>Java™ Platform<br>Standard Ed. 8</strong></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?javax/security/sasl/class-use/AuthorizeCallback.html" target="_top">Frames</a></li>
<li><a href="AuthorizeCallback.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 javax.security.sasl.AuthorizeCallback" class="title">Uses of Class<br>javax.security.sasl.AuthorizeCallback</h2>
</div>
<div class="classUseContainer">No usage of javax.security.sasl.AuthorizeCallback</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../javax/security/sasl/AuthorizeCallback.html" title="class in javax.security.sasl">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><strong>Java™ Platform<br>Standard Ed. 8</strong></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?javax/security/sasl/class-use/AuthorizeCallback.html" target="_top">Frames</a></li>
<li><a href="AuthorizeCallback.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><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://download.oracle.com/javase/8/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../legal/cpyr.html">Copyright</a> © 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p>
</body>
</html>
| {'content_hash': 'be32285ab28b44624e4a93fc33a8729b', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 603, 'avg_line_length': 40.90551181102362, 'alnum_prop': 0.6392685274302213, 'repo_name': 'fbiville/annotation-processing-ftw', 'id': '5e414921fa9ec5ee7551fdcab7181e58774d4e56', 'size': '5195', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/java/jdk8/javax/security/sasl/class-use/AuthorizeCallback.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '191178'}, {'name': 'HTML', 'bytes': '63904'}, {'name': 'Java', 'bytes': '107042'}, {'name': 'JavaScript', 'bytes': '246677'}]} |
package au.gov.dva.sopapi.sopsupport;
import au.gov.dva.sopapi.dtos.ReasoningFor;
import au.gov.dva.sopapi.dtos.StandardOfProof;
import au.gov.dva.sopapi.interfaces.CaseTrace;
import au.gov.dva.sopapi.interfaces.model.Factor;
import com.google.common.collect.ImmutableList;
import scala.util.Properties;
import java.util.*;
public class SopSupportCaseTrace implements CaseTrace {
private StringBuilder sb = new StringBuilder();
private Optional<Integer> requiredCftsDays = Optional.empty();
private Optional<Integer> requiredCftsDaysForRh = Optional.empty();
private Optional<Integer> requiredCftsDaysForBop = Optional.empty();
private Optional<Integer> actualCftsDays = Optional.empty();
private Optional<Integer> requiredRhOperationalDays = Optional.empty();
private Optional<Integer> actualOperationalDays = Optional.empty();
private Optional<StandardOfProof> applicableStandardOfProof = Optional.empty();
private Map<ReasoningFor, List<String>> reasonings = new HashMap<>();
private Optional<String> conditionName = Optional.empty();
private ImmutableList<Factor> _rhFactors = ImmutableList.of();
private ImmutableList<Factor> _bopFactors = ImmutableList.of();
public SopSupportCaseTrace() {
}
public SopSupportCaseTrace(String conditionName)
{
setConditionName(conditionName);
}
@Override
public void setConditionName(String name) {
conditionName = Optional.of(name);
}
@Override
public Optional<String> getConditionName() {
return conditionName;
}
@Override
public void addReasoningFor(ReasoningFor type, String msg) {
if (!reasonings.containsKey(type)) {
reasonings.put(type, new ArrayList<>());
}
reasonings.get(type).add(msg);
this.addLoggingTrace(msg);
}
@Override
public ImmutableList<String> getReasoningFor(ReasoningFor type) {
if (reasonings.containsKey(type)) {
return ImmutableList.copyOf(reasonings.get(type));
}
else {
return ImmutableList.of();
}
}
@Override
public Map<ReasoningFor, List<String>> getReasonings() {
return reasonings;
}
public void addLoggingTrace(String msg) {
sb.append(msg + Properties.lineSeparator());
}
@Override
public String getLoggingTraces() {
return sb.toString();
}
@Override
public void setApplicableStandardOfProof(StandardOfProof standardOfProof) {
assert !applicableStandardOfProof.isPresent();
applicableStandardOfProof = Optional.of(standardOfProof);
}
@Override
public Optional<StandardOfProof> getApplicableStandardOfProof() {
return applicableStandardOfProof;
}
@Override
public void setRequiredCftsDaysForRh(int days) {
assert !requiredCftsDaysForRh.isPresent();
requiredCftsDaysForRh = Optional.of(days);
}
@Override
public Optional<Integer> getRequiredCftsDaysForRh() {
return requiredCftsDaysForRh;
}
@Override
public void setRequiredCftsDaysForBop(int days) {
assert !requiredCftsDaysForBop.isPresent();
requiredCftsDaysForBop = Optional.of(days);
}
@Override
public Optional<Integer> getRequiredCftsDaysForBop() {
return requiredCftsDaysForBop;
}
@Override
public void setRequiredCftsDays(int days) {
assert !requiredCftsDays.isPresent();
requiredCftsDays = Optional.of(days);
}
@Override
public Optional<Integer> getRequiredCftsDays() {
return requiredCftsDays;
}
@Override
public void setActualCftsDays(int days) {
assert !actualCftsDays.isPresent();
actualCftsDays = Optional.of(days);
}
@Override
public Optional<Integer> getActualCftsDays() {
return actualCftsDays;
}
@Override
public void setRequiredOperationalDaysForRh(int days) {
assert !requiredRhOperationalDays.isPresent();
requiredRhOperationalDays = Optional.of(days);
}
@Override
public Optional<Integer> getRequiredOperationalDaysForRh() {
return requiredRhOperationalDays;
}
@Override
public void setActualOperationalDays(int days) {
assert !actualOperationalDays.isPresent();
actualOperationalDays = Optional.of(days);
}
@Override
public Optional<Integer> getActualOperationalDays() {
return actualOperationalDays;
}
@Override
public void setRhFactors(ImmutableList<Factor> rhFactors) {
_rhFactors = rhFactors;
}
@Override
public ImmutableList<Factor> getRhFactors() {
return _rhFactors;
}
@Override
public void setBopFactors(ImmutableList<Factor> bopFactors) {
_bopFactors = bopFactors;
}
@Override
public ImmutableList<Factor> getBopFactors() {
return _bopFactors;
}
@Override
public String toString() {
return "SopSupportCaseTrace{" +
"sb=" + sb +
", requiredCftsDays=" + requiredCftsDays +
", requiredCftsDaysForRh=" + requiredCftsDaysForRh +
", requiredCftsDaysForBop=" + requiredCftsDaysForBop +
", actualCftsDays=" + actualCftsDays +
", requiredRhOperationalDays=" + requiredRhOperationalDays +
", actualOperationalDays=" + actualOperationalDays +
", applicableStandardOfProof=" + applicableStandardOfProof +
", reasonings=" + reasonings +
", conditionName=" + conditionName +
", _rhFactors=" + _rhFactors +
", _bopFactors=" + _bopFactors +
'}';
}
}
| {'content_hash': 'a6dca117a2cee3affac490a86c664eab', 'timestamp': '', 'source': 'github', 'line_count': 195, 'max_line_length': 83, 'avg_line_length': 29.54871794871795, 'alnum_prop': 0.664179104477612, 'repo_name': 'govlawtech/dva-sop-api', 'id': '6fec2e3122eb26291566c2edc385a034cbf7b45a', 'size': '5762', 'binary': False, 'copies': '1', 'ref': 'refs/heads/devtest', 'path': 'app/src/main/java/au/gov/dva/sopapi/sopsupport/SopSupportCaseTrace.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '703510'}, {'name': 'Java', 'bytes': '739411'}, {'name': 'JavaScript', 'bytes': '2746180'}, {'name': 'Mustache', 'bytes': '48'}, {'name': 'PowerShell', 'bytes': '2035'}, {'name': 'Scala', 'bytes': '221722'}, {'name': 'Shell', 'bytes': '1724'}]} |
package com.android.volley.toolbox;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.google.gson.Gson;
import org.json.JSONArray;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.List;
/**
* A request for retrieving a {@link JSONArray} response body at a given URL.
*/
public class JsonArrayRequest extends JsonRequest<List<Object>> {
private Type type;
/**
* Creates a new request.
*
* @param url URL to fetch the JSON from
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public JsonArrayRequest(String url, Listener<List<Object>> listener, ErrorListener errorListener, Type type) {
super(Method.GET, url, null, listener, errorListener);
this.type = type;
}
/**
* Creates a new request.
*
* @param method the HTTP method to use
* @param url URL to fetch the JSON from
* @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public JsonArrayRequest(int method, String url, JSONArray jsonRequest,
Listener<List<Object>> listener, ErrorListener errorListener, Type type) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
this.type = type;
}
@Override
protected Response<List<Object>> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
Gson gson = new Gson();
List<Object> objects = gson.fromJson(jsonString, type);
return Response.success(objects,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
}
| {'content_hash': 'dfe470aa47ed3cb9ddc54e80685e31b2', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 114, 'avg_line_length': 36.59701492537314, 'alnum_prop': 0.6590538336052202, 'repo_name': 'Subhash1987/ObjectVollyMaster', 'id': 'b0abb7acf0dcf2774d1fdf82463513a12db41728', 'size': '3071', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ObjetVolley/src/main/java/com/android/volley/toolbox/JsonArrayRequest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '330545'}, {'name': 'Makefile', 'bytes': '1048'}]} |
package com.google.api.ads.dfp.jaxws.v201403;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for AdSenseSettings.FontFamily.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="AdSenseSettings.FontFamily">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="DEFAULT"/>
* <enumeration value="ARIAL"/>
* <enumeration value="TAHOMA"/>
* <enumeration value="GEORGIA"/>
* <enumeration value="TIMES"/>
* <enumeration value="VERDANA"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "AdSenseSettings.FontFamily")
@XmlEnum
public enum AdSenseSettingsFontFamily {
DEFAULT,
ARIAL,
TAHOMA,
GEORGIA,
TIMES,
VERDANA;
public String value() {
return name();
}
public static AdSenseSettingsFontFamily fromValue(String v) {
return valueOf(v);
}
}
| {'content_hash': 'e70184afad55854ca140d76668bbd449', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 95, 'avg_line_length': 23.0, 'alnum_prop': 0.6597353497164461, 'repo_name': 'nafae/developer', 'id': '212a53f70c2dcfe3e8f6910eb81f0856d0a14484', 'size': '1058', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201403/AdSenseSettingsFontFamily.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '127846798'}, {'name': 'Perl', 'bytes': '28418'}]} |
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<com.gh4a.widget.StyleableTextView
android:id="@+id/plus_one"
style="@style/ReactionBarButton"
android:drawableLeft="@drawable/reaction_plus_one" />
<com.gh4a.widget.StyleableTextView
android:id="@+id/minus_one"
style="@style/ReactionBarButton"
android:drawableLeft="@drawable/reaction_minus_one" />
<com.gh4a.widget.StyleableTextView
android:id="@+id/laugh"
style="@style/ReactionBarButton"
android:drawableLeft="@drawable/reaction_laugh" />
<com.gh4a.widget.StyleableTextView
android:id="@+id/hooray"
style="@style/ReactionBarButton"
android:drawableLeft="@drawable/reaction_hooray" />
<com.gh4a.widget.StyleableTextView
android:id="@+id/confused"
style="@style/ReactionBarButton"
android:drawableLeft="@drawable/reaction_confused" />
<com.gh4a.widget.StyleableTextView
android:id="@+id/heart"
style="@style/ReactionBarButton"
android:drawableLeft="@drawable/reaction_heart" />
<com.gh4a.widget.StyleableTextView
android:id="@+id/rocket"
style="@style/ReactionBarButton"
android:drawableLeft="@drawable/reaction_rocket" />
<com.gh4a.widget.StyleableTextView
android:id="@+id/eyes"
style="@style/ReactionBarButton"
android:drawableLeft="@drawable/reaction_eyes" />
<ImageView
android:id="@+id/react"
style="@style/SelectableBorderlessItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:src="@drawable/overflow" />
</merge> | {'content_hash': '9ba37528c4c68f11a55a348820c37268', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 67, 'avg_line_length': 34.37735849056604, 'alnum_prop': 0.6569703622392975, 'repo_name': 'slapperwan/gh4a', 'id': 'fd1799b3ab63c0e190ac0d5021e66b3ea25b8215', 'size': '1822', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/reaction_bar.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '19767'}, {'name': 'Java', 'bytes': '1508911'}, {'name': 'JavaScript', 'bytes': '99721'}]} |
@interface VVAlertBanner ()
@property(nonatomic, assign) VVAlertBannerStyle style;
+ (VVAlertBanner *)bannerView;
- (void)showTransition;
@end
@implementation VVAlertBanner
@synthesize style = alertStyle;
@synthesize bannerTitle, bannerDetail, bannerImage, activity;
//Static vvBanner to check if alert already in view to dismiss it
static VVAlertBanner *vvBanner = nil;
#pragma mark - Lifecycle
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
}
return self;
}
#pragma mark - Setter
- (void)setStyle:(VVAlertBannerStyle)style
{
self.bannerImage.contentMode = UIViewContentModeScaleToFill;
if (style == VVAlertBannerStyleDefault)
{
self.activity.hidden = YES;
self.bannerImage.image = [UIImage imageNamed:@"bannerTick.png"];
}
else if (style == VVAlertBannerStyleConnection)
{
self.activity.hidden = NO;
// self.bannerImage.image = [UIImage imageNamed:@"VVAlertBanner.bundle/metal.png"];
}
else if (style == VVAlertBannerStyleError)
{
self.activity.hidden = YES;
self.bannerImage.image = [UIImage imageNamed:@"bannerCross.png"];
}
}
#pragma mark - View methods
+ (VVAlertBanner *)bannerInView:(UIView *)view
ofStyle:(VVAlertBannerStyle)style
withTitle:(NSString *)title
andDetail:(NSString *)detail
hideAfter:(NSTimeInterval)interval
{
//check if alert already in view to dismiss it
if (vvBanner)
{
[vvBanner dismissAlert];
}
VVAlertBanner *alertBannerView = [VVAlertBanner bannerView];
vvBanner = alertBannerView;
if (style == VVAlertBannerStyleError)
{
alertBannerView.backgroundColor = [UIColor colorWithRed:1.00f green:0.61f blue:0.54f alpha:0.70f];
}
else if (style == VVAlertBannerStyleConnection) {
alertBannerView.backgroundColor = [UIColor colorWithRed:0.90f green:0.74f blue:0.45f alpha:0.7f];
}
else
{
alertBannerView.backgroundColor = [UIColor colorWithRed:0.18 green:1 blue:0. alpha:0.7];
}
alertBannerView.bannerTitle.textColor = [UIColor whiteColor];
alertBannerView.bannerTitle.text = title;
alertBannerView.frame = CGRectMake(0, 0, view.bounds.size.width, 46);
[alertBannerView setStyle:style];
//Check if detail for alert
if (detail)
{
alertBannerView.bannerDetail.textColor = [UIColor whiteColor];
alertBannerView.bannerDetail.text = detail;
[alertBannerView.bannerDetail sizeToFit];
}
else
{
alertBannerView.bannerDetail.hidden = YES;
alertBannerView.bannerImage.frame = CGRectMake(15, 5, 35, 35);
alertBannerView.bannerTitle.frame = CGRectMake(57, 12, 240, 21);
}
//Add alert to view
[view addSubview:alertBannerView];
//Add delay to dismiss alert
if (interval != 0)
{
[alertBannerView performSelector:@selector(dismissAlert) withObject:view afterDelay:interval];
}
//Show alert in view
return alertBannerView;
}
+ (VVAlertBanner *)bannerInView:(UIView *)view
ofStyle:(VVAlertBannerStyle)style
withTitle:(NSString *)title
andDetail:(NSString *)detail
hideWith:(SEL)selector
{
//check if alert already in view to dismiss it
if (vvBanner)
{
[vvBanner dismissAlert];
}
VVAlertBanner *alertBannerView = [VVAlertBanner bannerView];
vvBanner = alertBannerView;
if (style == VVAlertBannerStyleError)
{
alertBannerView.backgroundColor = [UIColor colorWithRed:1.00f green:0.61f blue:0.54f alpha:0.90f];
}
else if (style == VVAlertBannerStyleConnection) {
alertBannerView.backgroundColor = [UIColor colorWithRed:0.90f green:0.74f blue:0.45f alpha:0.9f];
}
else
{
alertBannerView.backgroundColor = [UIColor colorWithRed:0.48 green:0.71 blue:0.42 alpha:0.9];
}
alertBannerView.bannerTitle.textColor = [UIColor whiteColor];
alertBannerView.bannerTitle.text = title;
alertBannerView.frame = CGRectMake(0, 0, view.bounds.size.width, 50);
[alertBannerView setStyle:style];
//Check if detail for alert
if (detail)
{
alertBannerView.bannerDetail.textColor = [UIColor whiteColor];
alertBannerView.bannerDetail.text = detail;
[alertBannerView.bannerDetail sizeToFit];
}
else
{
alertBannerView.bannerDetail.hidden = YES;
alertBannerView.bannerImage.frame = CGRectMake(15, 5, 35, 35);
alertBannerView.bannerTitle.frame = CGRectMake(57, 12, 240, 21);
}
//Add alert to view
[view addSubview:alertBannerView];
//
//Code to dismiss alert with a define selector
//
//Show alert in view
return alertBannerView;
}
#pragma mark - Window methods
+ (VVAlertBanner *)bannerInWindow:(UIWindow *)window
ofStyle:(VVAlertBannerStyle)style
withTitle:(NSString *)title
andDetail:(NSString *)detail
hideAfter:(NSTimeInterval)interval
{
//check if alert already in view to dismiss it
if (vvBanner)
{
[vvBanner dismissAlert];
}
VVAlertBanner *alertBannerView = [VVAlertBanner bannerView];
vvBanner = alertBannerView;
alertBannerView = [self bannerInView:window ofStyle:style withTitle:title andDetail:detail hideAfter:interval];
//Define alert's frame
if (![UIApplication sharedApplication].statusBarHidden)
{
CGRect frame = alertBannerView.frame;
frame.origin.y += [UIApplication sharedApplication].statusBarFrame.size.height;
alertBannerView.frame = frame;
}
[window addSubview:alertBannerView];
if (interval != 0)
{
[alertBannerView performSelector:@selector(dismissAlert) withObject:window afterDelay:interval];
}
//Show alert in window
return alertBannerView;
}
+ (VVAlertBanner *)bannerInWindow:(UIWindow *)window
ofStyle:(VVAlertBannerStyle)style
withTitle:(NSString *)title
andDetail:(NSString *)detail
hideWith:(SEL)selector
{
//check if alert already in view to dismiss it
if (vvBanner)
{
[vvBanner dismissAlert];
}
VVAlertBanner *alertBannerView = [VVAlertBanner bannerView];
vvBanner = alertBannerView;
alertBannerView = [self bannerInView:window ofStyle:style withTitle:title andDetail:detail hideWith:selector];
//Define alert's frame
if (![UIApplication sharedApplication].statusBarHidden)
{
CGRect frame = alertBannerView.frame;
frame.origin.y += [UIApplication sharedApplication].statusBarFrame.size.height;
alertBannerView.frame = frame;
}
[window addSubview:alertBannerView];
//
//Code to Dismiss alert with a define selector
//
//Show alert in window
return alertBannerView;
}
#pragma mark - Touches Events
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//If alert is touched, it dismiss
[self dismissAlert];
}
#pragma mark - Dismiss Alert
- (void)dismissTransition
{
CATransition *hideAlertTransition = [CATransition animation];
[hideAlertTransition setDuration:TIME_TRANSITON];
[hideAlertTransition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[hideAlertTransition setType:kCATransitionPush];
[hideAlertTransition setSubtype:kCATransitionFromTop];
[self.layer addAnimation:hideAlertTransition forKey:nil];
self.frame = CGRectMake(0, -self.frame.size.height, self.frame.size.width, self.frame.size.height);
}
- (void)dismissAlert
{
[self dismissTransition];
vvBanner = nil;
//Remove alert from view
[self performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:TIME_TRANSITON];
}
#pragma mark - Pivate Method
- (void)showTransition
{
CATransition *transition = [CATransition animation];
transition.duration = TIME_TRANSITON;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromBottom;
[vvBanner.layer addAnimation:transition forKey:nil];
}
+ (VVAlertBanner *)bannerView
{
//Check nib file
vvBanner = (VVAlertBanner *) [[[UINib nibWithNibName:@"VVAlertBanner" bundle:nil]
instantiateWithOwner:self options:nil]
objectAtIndex:0];
[vvBanner showTransition];
return vvBanner;
}
@end
| {'content_hash': 'f0ad988ade005f3c81e9e0f689a52b72', 'timestamp': '', 'source': 'github', 'line_count': 310, 'max_line_length': 121, 'avg_line_length': 28.57741935483871, 'alnum_prop': 0.6723106445422734, 'repo_name': 'onevcat/VVAlertBanner', 'id': '6995c91e8c3715aaabdb84fd4b9c722db4d23029', 'size': '9161', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'VVAlertBanner/VVAlertBanner.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '18633'}]} |
using System;
using System.Text;
namespace Potato.Net.Shared.Test.Mocks {
public class MockPacketSerializer : IPacketSerializer {
public uint PacketHeaderSize { get; set; }
public MockPacketSerializer() {
this.PacketHeaderSize = 16;
}
public IPacketWrapper Deserialize(byte[] packetData) {
int length = BitConverter.ToInt32(packetData, 12);
MockPacket wrapper = new MockPacket {
Packet = {
Origin = (PacketOrigin)BitConverter.ToInt32(packetData, 0),
Type = (PacketType)BitConverter.ToInt32(packetData, 4),
RequestId = BitConverter.ToInt32(packetData, 8)
},
Text = Encoding.ASCII.GetString(packetData, (int)this.PacketHeaderSize, length)
};
wrapper.Packet.DebugText = String.Format("{0} {1} {2} {3}", wrapper.Packet.Origin, wrapper.Packet.Type, wrapper.Packet.RequestId, wrapper.Packet.Text);
return wrapper;
}
public byte[] Serialize(IPacketWrapper wrapper) {
MockPacket mockPacket = wrapper as MockPacket;
byte[] serialized = null;
if (mockPacket != null) {
if (mockPacket.Packet.RequestId == null)
mockPacket.Packet.RequestId = 111;
serialized = new byte[this.PacketHeaderSize + mockPacket.Text.Length];
BitConverter.GetBytes((int)mockPacket.Packet.Origin).CopyTo(serialized, 0);
BitConverter.GetBytes((int)mockPacket.Packet.Type).CopyTo(serialized, 4);
BitConverter.GetBytes(mockPacket.Packet.RequestId.Value).CopyTo(serialized, 8);
BitConverter.GetBytes(mockPacket.Text.Length).CopyTo(serialized, 12);
Encoding.ASCII.GetBytes(mockPacket.Text).CopyTo(serialized, this.PacketHeaderSize);
mockPacket.Packet.DebugText = String.Format("{0} {1} {2} {3}", mockPacket.Packet.Origin, mockPacket.Packet.Type, mockPacket.Packet.RequestId, mockPacket.Packet.Text);
}
return serialized;
}
public long ReadPacketSize(byte[] packetData) {
long length = 0;
if (packetData.Length >= this.PacketHeaderSize) {
length = BitConverter.ToUInt32(packetData, 12) + this.PacketHeaderSize;
}
return length;
}
}
}
| {'content_hash': 'a8420026c91f32e9c142434055391429', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 182, 'avg_line_length': 39.32258064516129, 'alnum_prop': 0.6062346185397867, 'repo_name': 'phogue/Potato', 'id': '27dd0853e981a865527f976cd10369a29e9ce2e8', 'size': '3064', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Potato.Net.Shared.Test/Mocks/MockPacketSerializer.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '3865563'}, {'name': 'CSS', 'bytes': '63'}, {'name': 'JavaScript', 'bytes': '4406'}, {'name': 'Python', 'bytes': '15262'}]} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Svensk bot. Tidskr. 25: 307 (1903)
#### Original name
Pleospora gigantasca Rostr.
### Remarks
null | {'content_hash': '3cb30fb72e3a0d6bc2b01acadd2d785d', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 34, 'avg_line_length': 12.461538461538462, 'alnum_prop': 0.7037037037037037, 'repo_name': 'mdoering/backbone', 'id': '6b230ce49567e61f02056d02fc1ba80a7ce3a051', 'size': '213', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Pleosporaceae/Pleospora/Pleospora gigantasca/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
using Google.Apis.Download;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Object = Google.Apis.Storage.v1.Data.Object;
namespace Google.Cloud.Storage.V1.IntegrationTests
{
[Collection(nameof(StorageFixture))]
public class DownloadObjectTest
{
private readonly StorageFixture _fixture;
public DownloadObjectTest(StorageFixture fixture)
{
_fixture = fixture;
}
[Fact]
public async Task SimpleDownload()
{
using (var stream = new MemoryStream())
{
await _fixture.Client.DownloadObjectAsync(_fixture.ReadBucket, _fixture.SmallObject, stream);
Assert.Equal(_fixture.SmallContent, stream.ToArray());
}
}
[Fact]
public void WrongObjectName()
{
using (var stream = new MemoryStream())
{
Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(_fixture.ReadBucket, "doesntexist", stream));
}
}
[Fact]
public async Task WrongObjectName_Async()
{
using (var stream = new MemoryStream())
{
await Assert.ThrowsAsync<GoogleApiException>(() => _fixture.Client.DownloadObjectAsync(_fixture.ReadBucket, "doesntexist", stream));
}
}
[Fact]
public void WrongBucketName()
{
using (var stream = new MemoryStream())
{
Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(_fixture.BucketPrefix + "doesntexist", "doesntexist", stream));
}
}
[Fact]
public async Task WrongBucketName_Async()
{
using (var stream = new MemoryStream())
{
await Assert.ThrowsAsync<GoogleApiException>(() => _fixture.Client.DownloadObjectAsync(_fixture.BucketPrefix + "doesntexist", "doesntexist", stream));
}
}
[Fact]
public async Task ChunkSize()
{
int chunks = 0;
var progress = new Progress<IDownloadProgress> (p => chunks++);
using (var stream = new MemoryStream())
{
await _fixture.Client.DownloadObjectAsync(
_fixture.ReadBucket, _fixture.LargeObject, stream,
new DownloadObjectOptions { ChunkSize = 2 * 1024 },
CancellationToken.None,
progress);
Assert.Equal(_fixture.LargeContent, stream.ToArray());
Assert.True(chunks >= 5);
}
}
[Fact]
public async Task Cancellation()
{
var cts = new CancellationTokenSource();
var progress = new Progress<IDownloadProgress>(p =>
{
if (p.BytesDownloaded > 5000)
{
cts.Cancel();
}
});
using (var stream = new MemoryStream())
{
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _fixture.Client.DownloadObjectAsync(
_fixture.ReadBucket, _fixture.LargeObject, stream,
new DownloadObjectOptions { ChunkSize = 2 * 1024 },
cts.Token,
progress));
}
}
[Fact]
public void DownloadObjectFromInvalidBucket()
{
Assert.Throws<ArgumentException>(() => _fixture.Client.DownloadObject("!!!", _fixture.LargeObject, new MemoryStream()));
}
[Fact]
public void DownloadObjectWrongGeneration()
{
var existing = GetLatestVersionOfMultiversionObject();
var stream = new MemoryStream();
var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream,
new DownloadObjectOptions { Generation = existing.Generation + 1 }, null));
Assert.Equal(HttpStatusCode.NotFound, exception.HttpStatusCode);
Assert.Equal(0, stream.Length);
}
[Fact]
public void DownloadDifferentGenerations()
{
var bucket = _fixture.ReadBucket;
var name = _fixture.SmallThenLargeObject;
var objects = _fixture.Client.ListObjects(bucket, name, new ListObjectsOptions { Versions = true }).ToList();
Assert.Equal(2, objects.Count);
// Fetch them by generation and check size matches
foreach (var obj in objects)
{
var stream = new MemoryStream();
_fixture.Client.DownloadObject(bucket, name, stream, new DownloadObjectOptions { Generation = obj.Generation }, null);
Assert.Equal((long) obj.Size, stream.Length);
}
}
[Fact]
public void SpecifyingObjectSourceIgnoredGeneration()
{
var bucket = _fixture.ReadBucket;
var name = _fixture.SmallThenLargeObject;
var objects = _fixture.Client.ListObjects(bucket, name, new ListObjectsOptions { Versions = true })
.OrderBy(x => x.Generation)
.ToList();
Assert.Equal(2, objects.Count);
Assert.NotEqual(objects[0].Size, objects[1].Size);
var stream = new MemoryStream();
_fixture.Client.DownloadObject(objects[0], stream);
Assert.Equal((long) objects[1].Size, stream.Length);
}
[Fact]
public void DownloadObjectIfGenerationMatch_Matching()
{
var existing = GetLatestVersionOfMultiversionObject();
var stream = new MemoryStream();
_fixture.Client.DownloadObject(existing, stream,
new DownloadObjectOptions { IfGenerationMatch = existing.Generation}, null);
Assert.NotEqual(0, stream.Length);
}
[Fact]
public void DownloadObjectIfGenerationMatch_NotMatching()
{
var existing = GetLatestVersionOfMultiversionObject();
var stream = new MemoryStream();
var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream,
new DownloadObjectOptions { IfGenerationMatch = existing.Generation + 1 }, null));
Assert.Equal(HttpStatusCode.PreconditionFailed, exception.HttpStatusCode);
Assert.Equal(0, stream.Length);
}
[Fact]
public void DownloadObjectIfGenerationNotMatch_Matching()
{
var existing = GetLatestVersionOfMultiversionObject();
var stream = new MemoryStream();
var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream,
new DownloadObjectOptions { IfGenerationNotMatch = existing.Generation }, null));
Assert.Equal(HttpStatusCode.NotModified, exception.HttpStatusCode);
Assert.Equal(0, stream.Length);
}
[Fact]
public void DownloadObjectIfGenerationNotMatch_NotMatching()
{
var existing = GetLatestVersionOfMultiversionObject();
var stream = new MemoryStream();
_fixture.Client.DownloadObject(existing, stream,
new DownloadObjectOptions { IfGenerationNotMatch = existing.Generation + 1 }, null);
Assert.NotEqual(0, stream.Length);
}
[Fact]
public void DownloadObject_IfGenerationMatchAndNotMatch()
{
Assert.Throws<ArgumentException>(() => _fixture.Client.DownloadObject(
_fixture.ReadBucket, _fixture.SmallThenLargeObject, new MemoryStream(),
new DownloadObjectOptions { IfGenerationMatch = 1, IfGenerationNotMatch = 2 },
null));
}
[Fact]
public void DownloadObjectIfMetagenerationMatch_Matching()
{
var existing = GetLatestVersionOfMultiversionObject();
var stream = new MemoryStream();
_fixture.Client.DownloadObject(existing, stream,
new DownloadObjectOptions { IfMetagenerationMatch = existing.Metageneration}, null);
Assert.NotEqual(0, stream.Length);
}
[Fact]
public void DownloadObjectIfMetagenerationMatch_NotMatching()
{
var existing = GetLatestVersionOfMultiversionObject();
var stream = new MemoryStream();
var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream,
new DownloadObjectOptions { IfMetagenerationMatch = existing.Metageneration + 1 }, null));
Assert.Equal(HttpStatusCode.PreconditionFailed, exception.HttpStatusCode);
Assert.Equal(0, stream.Length);
}
[Fact]
public void DownloadObjectIfMetagenerationNotMatch_Matching()
{
var existing = GetLatestVersionOfMultiversionObject();
var stream = new MemoryStream();
var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream,
new DownloadObjectOptions { IfMetagenerationNotMatch = existing.Metageneration }, null));
Assert.Equal(HttpStatusCode.NotModified, exception.HttpStatusCode);
Assert.Equal(0, stream.Length);
}
[Fact]
public void DownloadObjectIfMetagenerationNotMatch_NotMatching()
{
var existing = GetLatestVersionOfMultiversionObject();
var stream = new MemoryStream();
_fixture.Client.DownloadObject(existing, stream,
new DownloadObjectOptions { IfMetagenerationNotMatch = existing.Metageneration + 1 }, null);
Assert.NotEqual(0, stream.Length);
}
[Fact]
public void DownloadObject_IfMetagenerationMatchAndNotMatch()
{
Assert.Throws<ArgumentException>(() => _fixture.Client.DownloadObject(
_fixture.ReadBucket, _fixture.SmallThenLargeObject, new MemoryStream(),
new DownloadObjectOptions { IfMetagenerationMatch = 1, IfMetagenerationNotMatch = 2 },
null));
}
[Fact]
public void DownloadObject_Range()
{
var stream = new MemoryStream();
_fixture.Client.DownloadObject(_fixture.ReadBucket, _fixture.LargeObject, stream,
new DownloadObjectOptions { Range = new RangeHeaderValue(2000, 2999) });
var expected = _fixture.LargeContent.Skip(2000).Take(1000).ToArray();
var actual = stream.ToArray();
Assert.Equal(expected, actual);
}
private Object GetLatestVersionOfMultiversionObject()
{
var service = _fixture.Client.Service;
return service.Objects.Get(_fixture.ReadBucket, _fixture.SmallThenLargeObject).Execute();
}
}
}
| {'content_hash': '1062c8989f9e419f74d2a7b4a27e3705', 'timestamp': '', 'source': 'github', 'line_count': 278, 'max_line_length': 166, 'avg_line_length': 40.118705035971225, 'alnum_prop': 0.5950865238052542, 'repo_name': 'mbrukman/gcloud-dotnet', 'id': '073453ff5a222880b89914f8b704a5869d77f109', 'size': '11766', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'apis/Google.Cloud.Storage.V1/Google.Cloud.Storage.V1.IntegrationTests/DownloadObjectTest.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
package org.boilit.bsl;
import org.boilit.bsl.core.sxs.FragDefine;
import org.boilit.bsl.xio.IResource;
import java.util.concurrent.ConcurrentMap;
/**
* @author Boilit
* @see
*/
public final class Fragment extends AbstractTemplate {
private final ITemplate template;
private FragDefine fragDefine;
public Fragment(final ITemplate template) {
super(template.getEngine());
this.template = template;
}
public ITemplate getTemplate() {
return template;
}
@Override
public IResource getResource() {
return null;
}
@Override
public final ConcurrentMap<String, Fragment> getFragments() {
return null;
}
@Override
public Object execute(final Context context) throws Exception {
return null;
}
public final FragDefine getFragDefine() {
return fragDefine;
}
public final void setFragDefine(final FragDefine fragDefine) {
this.fragDefine = fragDefine;
}
public final void appendToTemplate() {
this.template.getFragments().put(this.fragDefine.getLabel(), this);
}
}
| {'content_hash': '1792e3fa8c4e2415e7c2f8bc935a134d', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 75, 'avg_line_length': 22.03921568627451, 'alnum_prop': 0.6681494661921709, 'repo_name': 'boilit/bsl', 'id': 'd993ea0dc35dce6c51e5d17d9d857b9a5b55c437', 'size': '1124', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/boilit/bsl/Fragment.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1324'}, {'name': 'HTML', 'bytes': '2975'}, {'name': 'Java', 'bytes': '932216'}, {'name': 'Lex', 'bytes': '7177'}]} |
package com.example.hotel.desktop.controller;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.hotel.desktop.model.Building;
import com.example.hotel.desktop.model.Context;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
public class AddRoomController {
@FXML
private Button buttonAddRoom;
@FXML
private TextField textNumber;
@FXML
private TextField textUnits;
@FXML
private ComboBox<String> comboType;
@FXML
private TextField textDescription;
@FXML
private TextField textPrice;
@FXML
private ComboBox<String> comboBuilding;
@FXML
Button buttonRefresh;
public ObservableList<Building> buildingList = FXCollections.observableArrayList();
public AddRoomController() {
}
@FXML
private void initialize() {
comboType.getItems().add("Studio");
comboType.getItems().add("Room");
comboType.getItems().add("Apartment");
getBuildings();
}
@FXML
private void buttonRefreshClicked() {
buttonRefresh.setDisable(true);
getBuildings();
}
private void getBuildings() {
Task<Void> backgroundTask = new Task<Void>() {
// here you can add local attributes that can
// be used in both succeeded() and call() methods
@Override
protected Void call() throws Exception {
Context.setMessage("Trwa pobieranie danych budynków", "orange");
buildingList.clear();
JSONArray data = (JSONArray) Context.getInstance().getServer().getRequest("/api/owner/buildings", false,
true);
if (data != null) {
for (int i = 0; i < data.length(); i++) {
JSONObject building = data.getJSONObject(i);
Building bld = new Building(building.getLong("id"), null,
building.getString("name") == null ? "" : building.getString("name"),
building.getString("description") == null ? "" : building.getString("description"),
null, null, null, null, null);
buildingList.add(bld);
}
Context.clearMessage();
}
return null;
}
@Override
protected void succeeded() {
comboBuilding.getItems().clear();
for (Building building : buildingList) {
comboBuilding.getItems().add(building.getName());
}
buttonRefresh.setDisable(false);
}
};
new Thread(backgroundTask).start();
}
@FXML
private boolean validate() {
if (textNumber.getText().equals("") || textUnits.getText().equals("") || textDescription.getText().equals("")
|| textPrice.getText().equals("") || comboType.getSelectionModel().getSelectedIndex() == -1
|| comboBuilding.getSelectionModel().getSelectedIndex() == -1)
return false;
return true;
}
@FXML
public void buttonAddRoomClicked() {
if (!validate())
return;
JSONObject data = new JSONObject();
data.put("number", textNumber.getText());
data.put("capacity", textUnits.getText());
data.put("note", textDescription.getText());
data.put("cost", textPrice.getText());
data.put("type", comboType.getSelectionModel().getSelectedItem());
data.put("buildingID", buildingList.get(comboBuilding.getSelectionModel().getSelectedIndex()).getId());
data.put("availability", "true"); // new room always available
String post = data.toString();
Context.getInstance().getServer().postRequest("/api/owner/buildings/rooms/add", post, true, false);
}
}
| {'content_hash': '579ea5be39c57ead0e6c0b670177a9ae', 'timestamp': '', 'source': 'github', 'line_count': 135, 'max_line_length': 111, 'avg_line_length': 25.62962962962963, 'alnum_prop': 0.7031791907514451, 'repo_name': 'marcin-pwr/hotel', 'id': 'bd4a944f35e3c7c5390acca2a23856a33d450f1b', 'size': '3461', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'desktop/client/src/com/example/hotel/desktop/controller/AddRoomController.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '147'}, {'name': 'CSS', 'bytes': '2085'}, {'name': 'HTML', 'bytes': '37581'}, {'name': 'Java', 'bytes': '99474'}, {'name': 'JavaScript', 'bytes': '21129'}]} |
NS_INLINE CGRect JGProgressHUD_CGRectIntegral(CGRect rect) {
CGFloat scale = [[UIScreen mainScreen] scale];
return (CGRect){{((CGFloat)floor(rect.origin.x*scale))/scale, ((CGFloat)floor(rect.origin.y*scale))/scale}, {((CGFloat)ceil(rect.size.width*scale))/scale, ((CGFloat)ceil(rect.size.height*scale))/scale}};
}
@interface JGProgressHUD () {
BOOL _transitioning;
BOOL _updateAfterAppear;
BOOL _dismissAfterTransitionFinished;
BOOL _dismissAfterTransitionFinishedWithAnimation;
CFAbsoluteTime _displayTimestamp;
JGProgressHUDIndicatorView *_indicatorViewAfterTransitioning;
}
@end
@interface JGProgressHUDAnimation (Private)
@property (nonatomic, weak) JGProgressHUD *progressHUD;
@end
@implementation JGProgressHUD
@synthesize HUDView = _HUDView;
@synthesize textLabel = _textLabel;
@synthesize detailTextLabel = _detailTextLabel;
@synthesize indicatorView = _indicatorView;
@synthesize animation = _animation;
@dynamic visible, contentView;
#pragma mark - Keyboard
static CGRect keyboardFrame = (CGRect){{0.0f, 0.0f}, {0.0f, 0.0f}};
+ (void)keyboardFrameWillChange:(NSNotification *)notification {
keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
if (CGRectIsEmpty(keyboardFrame)) {
keyboardFrame = [notification.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
}
}
+ (void)keyboardFrameDidChange:(NSNotification *)notification {
keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
}
+ (CGRect)currentKeyboardFrame {
return keyboardFrame;
}
+ (void)load {
[super load];
@autoreleasepool {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardDidChangeFrameNotification object:nil];
}
}
#pragma mark - Initializers
- (instancetype)init {
return [self initWithStyle:JGProgressHUDStyleExtraLight];
}
- (instancetype)initWithFrame:(CGRect __unused)frame {
return [self initWithStyle:JGProgressHUDStyleExtraLight];
}
- (instancetype)initWithStyle:(JGProgressHUDStyle)style {
self = [super initWithFrame:CGRectZero];
if (self) {
_style = style;
self.hidden = YES;
self.backgroundColor = [UIColor clearColor];
self.contentInsets = UIEdgeInsetsMake(20.0f, 20.0f, 20.0f, 20.0f);
self.marginInsets = UIEdgeInsetsMake(20.0f, 20.0f, 20.0f, 20.0f);
self.layoutChangeAnimationDuration = 0.3;
[self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]];
_indicatorView = [[JGProgressHUDIndeterminateIndicatorView alloc] initWithHUDStyle:self.style];
_cornerRadius = 10.0f;
}
return self;
}
+ (instancetype)progressHUDWithStyle:(JGProgressHUDStyle)style {
return [(JGProgressHUD *)[self alloc] initWithStyle:style];
}
#pragma mark - Layout
- (void)setHUDViewFrameCenterWithSize:(CGSize)size {
CGRect frame = CGRectZero;
frame.size = size;
CGRect viewBounds = self.bounds;
CGPoint center = CGPointMake(viewBounds.origin.x+viewBounds.size.width/2.0f, viewBounds.origin.y+viewBounds.size.height/2.0f);
switch (self.position) {
case JGProgressHUDPositionTopLeft:
frame.origin.x = self.marginInsets.left;
frame.origin.y = self.marginInsets.top;
break;
case JGProgressHUDPositionTopCenter:
frame.origin.x = center.x-frame.size.width/2.0f;
frame.origin.y = self.marginInsets.top;
break;
case JGProgressHUDPositionTopRight:
frame.origin.x = viewBounds.size.width-self.marginInsets.right-frame.size.width;
frame.origin.y = self.marginInsets.top;
break;
case JGProgressHUDPositionCenterLeft:
frame.origin.x = self.marginInsets.left;
frame.origin.y = center.y-frame.size.height/2.0f;
break;
case JGProgressHUDPositionCenter:
frame.origin.x = center.x-frame.size.width/2.0f;
frame.origin.y = center.y-frame.size.height/2.0f;
break;
case JGProgressHUDPositionCenterRight:
frame.origin.x = viewBounds.size.width-self.marginInsets.right-frame.size.width;
frame.origin.y = center.y-frame.size.height/2.0f;
break;
case JGProgressHUDPositionBottomLeft:
frame.origin.x = self.marginInsets.left;
frame.origin.y = viewBounds.size.height-self.marginInsets.bottom-frame.size.height;
break;
case JGProgressHUDPositionBottomCenter:
frame.origin.x = center.x-frame.size.width/2.0f;
frame.origin.y = viewBounds.size.height-self.marginInsets.bottom-frame.size.height;
break;
case JGProgressHUDPositionBottomRight:
frame.origin.x = viewBounds.size.width-self.marginInsets.right-frame.size.width;
frame.origin.y = viewBounds.size.height-self.marginInsets.bottom-frame.size.height;
break;
}
self.HUDView.frame = JGProgressHUD_CGRectIntegral(frame);
}
- (void)updateHUDAnimated:(BOOL)animated animateIndicatorViewFrame:(BOOL)animateIndicator {
if (_transitioning) {
_updateAfterAppear = YES;
return;
}
if (!self.superview) {
return;
}
CGRect indicatorFrame = self.indicatorView.frame;
indicatorFrame.origin.y = self.contentInsets.top;
CGFloat maxContentWidth = self.frame.size.width-self.marginInsets.left-self.marginInsets.right-self.contentInsets.left-self.contentInsets.right;
CGFloat maxContentHeight = self.frame.size.height-self.marginInsets.top-self.marginInsets.bottom-self.contentInsets.top-self.contentInsets.bottom;
CGSize maxContentSize = (CGSize){maxContentWidth, maxContentHeight};
//Label size
CGRect labelFrame = CGRectZero;
CGRect detailFrame = CGRectZero;
if (_textLabel) {
if (iOS7) {
NSDictionary *attributes = @{NSFontAttributeName : self.textLabel.font};
labelFrame.size = [self.textLabel.text boundingRectWithSize:maxContentSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
}
else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
labelFrame.size = [self.textLabel.text sizeWithFont:self.textLabel.font constrainedToSize:maxContentSize lineBreakMode:self.textLabel.lineBreakMode];
#pragma clang diagnostic pop
}
labelFrame.origin.y = CGRectGetMaxY(indicatorFrame);
if (!CGRectIsEmpty(labelFrame) && !CGRectIsEmpty(indicatorFrame)) {
labelFrame.origin.y += 10.0f;
}
}
if (_detailTextLabel) {
if (iOS7) {
NSDictionary *attributes = @{NSFontAttributeName : self.detailTextLabel.font};
detailFrame.size = [self.detailTextLabel.text boundingRectWithSize:maxContentSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
}
else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
detailFrame.size = [self.detailTextLabel.text sizeWithFont:self.detailTextLabel.font constrainedToSize:maxContentSize lineBreakMode:self.detailTextLabel.lineBreakMode];
#pragma clang diagnostic pop
}
detailFrame.origin.y = CGRectGetMaxY(labelFrame)+5.0f;
if (!CGRectIsEmpty(detailFrame) && !CGRectIsEmpty(indicatorFrame) && CGRectIsEmpty(labelFrame)) {
detailFrame.origin.y += 5.0f;
}
}
//HUD size
CGSize size = CGSizeZero;
CGFloat width = MIN(self.contentInsets.left+MAX(indicatorFrame.size.width, MAX(labelFrame.size.width, detailFrame.size.width))+self.contentInsets.right, self.frame.size.width-self.marginInsets.left-self.marginInsets.right);
CGFloat height = MAX(CGRectGetMaxY(labelFrame), MAX(CGRectGetMaxY(detailFrame), CGRectGetMaxY(indicatorFrame)))+self.contentInsets.bottom;
if (self.square) {
CGFloat uniSize = MAX(width, height);
size.width = uniSize;
size.height = uniSize;
CGFloat heightDelta = (uniSize-height)/2.0f;
labelFrame.origin.y += heightDelta;
detailFrame.origin.y += heightDelta;
indicatorFrame.origin.y += heightDelta;
}
else {
size.width = width;
size.height = height;
}
CGPoint center = CGPointMake(size.width/2.0f, size.height/2.0f);
indicatorFrame.origin.x = center.x-indicatorFrame.size.width/2.0f;
labelFrame.origin.x = center.x-labelFrame.size.width/2.0f;
detailFrame.origin.x = center.x-detailFrame.size.width/2.0f;
void (^updates)(void) = ^{
[self setHUDViewFrameCenterWithSize:size];
if (animateIndicator) {
self.indicatorView.frame = indicatorFrame;
}
_textLabel.frame = JGProgressHUD_CGRectIntegral(labelFrame);
_detailTextLabel.frame = JGProgressHUD_CGRectIntegral(detailFrame);
};
if (!animateIndicator) {
self.indicatorView.frame = JGProgressHUD_CGRectIntegral(indicatorFrame);
}
if (self.layoutChangeAnimationDuration > 0.0f && animated && !_transitioning) {
[UIView animateWithDuration:self.layoutChangeAnimationDuration delay:0.0 options:UIViewAnimationOptionAllowAnimatedContent | UIViewAnimationOptionCurveEaseInOut animations:updates completion:nil];
}
else {
updates();
}
}
- (CGRect)fullFrameInView:(UIView *)view {
CGRect _keyboardFrame = [view convertRect:[[self class] currentKeyboardFrame] fromView:nil];
CGRect frame = view.bounds;
if (!CGRectIsEmpty(_keyboardFrame) && CGRectIntersectsRect(frame, _keyboardFrame)) {
frame.size.height = MIN(frame.size.height, CGRectGetMinY(_keyboardFrame));
}
return frame;
}
- (void)applyCornerRadius {
self.HUDView.layer.cornerRadius = self.cornerRadius;
if (iOS8) {
for (UIView *sub in self.HUDView.subviews) {
sub.layer.cornerRadius = self.cornerRadius;
}
};
}
#pragma mark - Showing
- (void)cleanUpAfterPresentation {
self.hidden = NO;
_transitioning = NO;
_displayTimestamp = CFAbsoluteTimeGetCurrent(); //Correct timestamp to the current time for animated presentations
if (_indicatorViewAfterTransitioning) {
self.indicatorView = _indicatorViewAfterTransitioning;
_indicatorViewAfterTransitioning = nil;
_updateAfterAppear = NO;
}
else if (_updateAfterAppear) {
[self updateHUDAnimated:YES animateIndicatorViewFrame:YES];
_updateAfterAppear = NO;
}
if ([self.delegate respondsToSelector:@selector(progressHUD:didPresentInView:)]){
[self.delegate progressHUD:self didPresentInView:self.targetView];
}
if (_dismissAfterTransitionFinished) {
[self dismissAnimated:_dismissAfterTransitionFinishedWithAnimation];
_dismissAfterTransitionFinished = NO;
_dismissAfterTransitionFinishedWithAnimation = NO;
}
if (UIAccessibilityIsVoiceOverRunning()) {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, self);
}
}
- (void)showInView:(UIView *)view {
[self showInView:view animated:YES];
}
- (void)showInView:(UIView *)view animated:(BOOL)animated {
CGRect frame = [self fullFrameInView:view];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged) name:UIDeviceOrientationDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChanged:) name:UIKeyboardDidChangeFrameNotification object:nil];
[self showInRect:frame inView:view animated:animated];
}
- (void)showInRect:(CGRect)rect inView:(UIView *)view {
[self showInRect:rect inView:view animated:YES];
}
- (void)showInRect:(CGRect)rect inView:(UIView *)view animated:(BOOL)animated {
if (_transitioning) {
return;
}
else if (self.targetView != nil) {
#if DEBUG
NSLog(@"[Warning] The HUD is already visible! Ignoring.");
#endif
return;
}
_targetView = view;
self.frame = rect;
[view addSubview:self];
[self updateHUDAnimated:NO animateIndicatorViewFrame:YES];
_transitioning = YES;
_displayTimestamp = CFAbsoluteTimeGetCurrent();
if ([self.delegate respondsToSelector:@selector(progressHUD:willPresentInView:)]) {
[self.delegate progressHUD:self willPresentInView:view];
}
if (animated && self.animation) {
[self.animation show];
}
else {
[self cleanUpAfterPresentation];
}
}
#pragma mark - Hiding
- (void)cleanUpAfterDismissal {
self.hidden = YES;
[self removeFromSuperview];
[self removeObservers];
_transitioning = NO;
_dismissAfterTransitionFinished = NO;
_dismissAfterTransitionFinishedWithAnimation = NO;
if ([self.delegate respondsToSelector:@selector(progressHUD:didDismissFromView:)]) {
[self.delegate progressHUD:self didDismissFromView:self.targetView];
}
_targetView = nil;
}
- (void)dismiss {
[self dismissAnimated:YES];
}
- (void)dismissAnimated:(BOOL)animated {
if (_transitioning) {
_dismissAfterTransitionFinished = YES;
_dismissAfterTransitionFinishedWithAnimation = animated;
return;
}
if (self.targetView == nil) {
return;
}
if (self.minimumDisplayTime > 0.0 && _displayTimestamp > 0.0) {
CFAbsoluteTime displayedTime = CFAbsoluteTimeGetCurrent()-_displayTimestamp;
if (displayedTime < self.minimumDisplayTime) {
NSTimeInterval delta = self.minimumDisplayTime-displayedTime;
[self dismissAfterDelay:delta animated:animated];
return;
}
}
_transitioning = YES;
if ([self.delegate respondsToSelector:@selector(progressHUD:willDismissFromView:)]) {
[self.delegate progressHUD:self willDismissFromView:self.targetView];
}
if (animated && self.animation) {
[self.animation hide];
}
else {
[self cleanUpAfterDismissal];
}
}
- (void)dismissAfterDelay:(NSTimeInterval)delay {
[self dismissAfterDelay:delay animated:YES];
}
- (void)dismissAfterDelay:(NSTimeInterval)delay animated:(BOOL)animated {
__weak __typeof(self) weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (weakSelf) {
__strong __typeof(weakSelf) strongSelf = weakSelf;
if (strongSelf.visible) {
[strongSelf dismissAnimated:animated];
}
}
});
}
#pragma mark - Callbacks
- (void)tapped:(UITapGestureRecognizer *)t {
if (CGRectContainsPoint(self.contentView.bounds, [t locationInView:self.contentView])) {
if (self.tapOnHUDViewBlock) {
self.tapOnHUDViewBlock(self);
}
}
else if (self.tapOutsideBlock) {
self.tapOutsideBlock(self);
}
}
- (void)keyboardFrameChanged:(NSNotification *)notification {
CGRect frame = [self fullFrameInView:self.targetView];
if (CGRectEqualToRect(self.frame, frame)) {
return;
}
NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
UIViewAnimationCurve curve = (UIViewAnimationCurve)[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue];
[UIView beginAnimations:@"de.j-gessner.jgprogresshud.keyboardframechange" context:NULL];
[UIView setAnimationCurve:curve];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:duration];
self.frame = frame;
[self updateHUDAnimated:NO animateIndicatorViewFrame:YES];
[UIView commitAnimations];
}
- (void)orientationChanged {
if (self.targetView && !CGRectEqualToRect(self.bounds, self.targetView.bounds)) {
[UIView animateWithDuration:(iPad ? 0.4 : 0.3) delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
self.frame = [self fullFrameInView:self.targetView];
[self updateHUDAnimated:NO animateIndicatorViewFrame:YES];
} completion:nil];
}
}
- (void)animationDidFinish:(BOOL)presenting {
if (presenting) {
[self cleanUpAfterPresentation];
}
else {
[self cleanUpAfterDismissal];
}
}
#pragma mark - Getters
- (BOOL)isVisible {
return (self.superview != nil);
}
- (UIView *)HUDView {
if (!_HUDView) {
if (iOS8) {
UIBlurEffectStyle effect = 0;
if (self.style == JGProgressHUDStyleDark) {
effect = UIBlurEffectStyleDark;
}
else if (self.style == JGProgressHUDStyleLight) {
effect = UIBlurEffectStyleLight;
}
else {
effect = UIBlurEffectStyleExtraLight;
}
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:effect];
_HUDView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
}
else {
_HUDView = [[UIView alloc] init];
if (self.style == JGProgressHUDStyleDark) {
_HUDView.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.8f];
}
else if (self.style == JGProgressHUDStyleLight) {
_HUDView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.75f];
}
else {
_HUDView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.95f];
}
}
if (iOS7) {
UIInterpolatingMotionEffect *x = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
CGFloat maxMovement = 20.0f;
x.minimumRelativeValue = @(-maxMovement);
x.maximumRelativeValue = @(maxMovement);
UIInterpolatingMotionEffect *y = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
y.minimumRelativeValue = @(-maxMovement);
y.maximumRelativeValue = @(maxMovement);
_HUDView.motionEffects = @[x, y];
}
[self applyCornerRadius];
[self addSubview:_HUDView];
if (self.indicatorView) {
[self.contentView addSubview:self.indicatorView];
}
[self.contentView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]];
}
return _HUDView;
}
- (UIView *)contentView {
if (iOS8) {
return ((UIVisualEffectView *)self.HUDView).contentView;
}
else {
return self.HUDView;
}
}
- (UILabel *)textLabel {
if (!_textLabel) {
_textLabel = [[UILabel alloc] init];
_textLabel.backgroundColor = [UIColor clearColor];
_textLabel.textColor = (self.style == JGProgressHUDStyleDark ? [UIColor whiteColor] : [UIColor blackColor]);
_textLabel.textAlignment = NSTextAlignmentCenter;
_textLabel.font = [UIFont boldSystemFontOfSize:15.0f];
_textLabel.numberOfLines = 0;
[_textLabel addObserver:self forKeyPath:@"text" options:(NSKeyValueObservingOptions)kNilOptions context:NULL];
[_textLabel addObserver:self forKeyPath:@"font" options:(NSKeyValueObservingOptions)kNilOptions context:NULL];
_textLabel.isAccessibilityElement = YES;
[self.contentView addSubview:_textLabel];
}
return _textLabel;
}
- (UILabel *)detailTextLabel {
if (!_detailTextLabel) {
_detailTextLabel = [[UILabel alloc] init];
_detailTextLabel.backgroundColor = [UIColor clearColor];
_detailTextLabel.textColor = (self.style == JGProgressHUDStyleDark ? [UIColor whiteColor] : [UIColor blackColor]);
_detailTextLabel.textAlignment = NSTextAlignmentCenter;
_detailTextLabel.font = [UIFont systemFontOfSize:13.0f];
_detailTextLabel.numberOfLines = 0;
[_detailTextLabel addObserver:self forKeyPath:@"text" options:(NSKeyValueObservingOptions)kNilOptions context:NULL];
[_detailTextLabel addObserver:self forKeyPath:@"font" options:(NSKeyValueObservingOptions)kNilOptions context:NULL];
_detailTextLabel.isAccessibilityElement = YES;
[self.contentView addSubview:_detailTextLabel];
}
return _detailTextLabel;
}
- (JGProgressHUDAnimation *)animation {
if (!_animation) {
self.animation = [JGProgressHUDFadeAnimation animation];
}
return _animation;
}
#pragma mark - Setters
- (void)setCornerRadius:(CGFloat)cornerRadius {
if (fequal(self.cornerRadius, cornerRadius)) {
return;
}
_cornerRadius = cornerRadius;
[self applyCornerRadius];
}
- (void)setAnimation:(JGProgressHUDAnimation *)animation {
if (_animation == animation) {
return;
}
_animation.progressHUD = nil;
_animation = animation;
_animation.progressHUD = self;
}
- (void)setPosition:(JGProgressHUDPosition)position {
if (self.position == position) {
return;
}
_position = position;
[self updateHUDAnimated:YES animateIndicatorViewFrame:YES];
}
- (void)setSquare:(BOOL)square {
if (self.square == square) {
return;
}
_square = square;
[self updateHUDAnimated:YES animateIndicatorViewFrame:YES];
}
- (void)setIndicatorView:(JGProgressHUDIndicatorView *)indicatorView {
if (self.indicatorView == indicatorView) {
return;
}
if (_transitioning) {
_indicatorViewAfterTransitioning = indicatorView;
return;
}
[_indicatorView removeFromSuperview];
_indicatorView = indicatorView;
if (self.indicatorView) {
[self.contentView addSubview:self.indicatorView];
}
[self updateHUDAnimated:YES animateIndicatorViewFrame:NO];
}
- (void)setMarginInsets:(UIEdgeInsets)marginInsets {
if (UIEdgeInsetsEqualToEdgeInsets(self.marginInsets, marginInsets)) {
return;
}
_marginInsets = marginInsets;
[self updateHUDAnimated:YES animateIndicatorViewFrame:YES];
}
- (void)setContentInsets:(UIEdgeInsets)contentInsets {
if (UIEdgeInsetsEqualToEdgeInsets(self.contentInsets, contentInsets)) {
return;
}
_contentInsets = contentInsets;
[self updateHUDAnimated:YES animateIndicatorViewFrame:YES];
}
- (void)setProgress:(float)progress {
[self setProgress:progress animated:NO];
}
- (void)setProgress:(float)progress animated:(BOOL)animated {
if (fequal(self.progress, progress)) {
return;
}
_progress = progress;
[self.indicatorView setProgress:progress animated:animated];
}
#pragma mark - Overrides
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if (self.interactionType == JGProgressHUDInteractionTypeBlockNoTouches) {
return nil;
}
else {
UIView *view = [super hitTest:point withEvent:event];
if (self.interactionType == JGProgressHUDInteractionTypeBlockAllTouches) {
return view;
}
else if (self.interactionType == JGProgressHUDInteractionTypeBlockTouchesOnHUDView && view != self) {
return view;
}
return nil;
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == _textLabel || object == _detailTextLabel) {
[self updateHUDAnimated:YES animateIndicatorViewFrame:YES];
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)dealloc {
[self removeObservers];
[_textLabel removeObserver:self forKeyPath:@"text"];
[_textLabel removeObserver:self forKeyPath:@"font"];
[_detailTextLabel removeObserver:self forKeyPath:@"text"];
[_detailTextLabel removeObserver:self forKeyPath:@"font"];
}
- (void)removeObservers {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidChangeFrameNotification object:nil];
}
@end
@implementation JGProgressHUD (HUDManagement)
+ (NSArray *)allProgressHUDsInView:(UIView *)view {
NSMutableArray *HUDs = [NSMutableArray array];
for (UIView *v in view.subviews) {
if ([v isKindOfClass:[JGProgressHUD class]]) {
[HUDs addObject:v];
}
}
return HUDs.copy;
}
+ (NSMutableArray *)_allProgressHUDsInViewHierarchy:(UIView *)view {
NSMutableArray *HUDs = [NSMutableArray array];
for (UIView *v in view.subviews) {
if ([v isKindOfClass:[JGProgressHUD class]]) {
[HUDs addObject:v];
}
else {
[HUDs addObjectsFromArray:[self _allProgressHUDsInViewHierarchy:v]];
}
}
return HUDs;
}
+ (NSArray *)allProgressHUDsInViewHierarchy:(UIView *)view {
return [self _allProgressHUDsInViewHierarchy:view].copy;
}
@end
| {'content_hash': 'c1ef7d38353561d8b24ce86c73da2eed', 'timestamp': '', 'source': 'github', 'line_count': 817, 'max_line_length': 227, 'avg_line_length': 32.342717258261935, 'alnum_prop': 0.6664396003633061, 'repo_name': 'LiuDeng/ChatRoom', 'id': '2235cf689a0964ba6eab99d6f09c8cafc456518e', 'size': '27285', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'ChatRoom/ChatRoom/Pods/JGProgressHUD/JGProgressHUD/JGProgressHUD/JGProgressHUD.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '96666'}, {'name': 'C++', 'bytes': '126269'}, {'name': 'DTrace', 'bytes': '412'}, {'name': 'Objective-C', 'bytes': '1587105'}, {'name': 'Objective-C++', 'bytes': '102451'}, {'name': 'Ruby', 'bytes': '279'}, {'name': 'Shell', 'bytes': '7051'}]} |
ambodi.com
==========
My personal website: www.ambodi.com
| {'content_hash': 'e60a6e348a5cd61931c289c3d1cecd38', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 35, 'avg_line_length': 14.75, 'alnum_prop': 0.6440677966101694, 'repo_name': 'ambodi/ambodi.com', 'id': 'b252859696de8065337f7255f7c3fac64a36cddf', 'size': '59', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '14056'}, {'name': 'HTML', 'bytes': '338289'}, {'name': 'JavaScript', 'bytes': '4893'}]} |
namespace LibRbxl.Instances
{
public class CornerWedgePart : BasePart
{
public override string ClassName => "CornerWedgePart";
}
}
| {'content_hash': 'fa75d6cce95f6351113a51ffa1487f4d', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 62, 'avg_line_length': 21.714285714285715, 'alnum_prop': 0.6776315789473685, 'repo_name': 'GregoryComer/LibRbxl', 'id': '6fac6825172966b9c9cc2e355e6813feb8ea475e', 'size': '154', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LibRbxl/Instances/CornerWedgePart.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '303881'}]} |
package com.linkedin.pinot.core.plan;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.linkedin.pinot.common.request.AggregationInfo;
import com.linkedin.pinot.common.request.BrokerRequest;
import com.linkedin.pinot.core.common.Operator;
import com.linkedin.pinot.core.indexsegment.IndexSegment;
import com.linkedin.pinot.core.operator.MProjectionOperator;
import com.linkedin.pinot.core.operator.query.BAggregationFunctionOperator;
import com.linkedin.pinot.core.operator.query.MAggregationOperator;
import com.linkedin.pinot.core.query.aggregation.AggregationFunctionUtils;
/**
* AggregationPlanNode takes care of how to apply an aggregation query to an IndexSegment.
*
*
*/
public class AggregationPlanNode implements PlanNode {
private static final Logger LOGGER = LoggerFactory.getLogger("QueryPlanLog");
private final IndexSegment _indexSegment;
private final BrokerRequest _brokerRequest;
private final List<AggregationFunctionPlanNode> _aggregationFunctionPlanNodes =
new ArrayList<AggregationFunctionPlanNode>();
private final ProjectionPlanNode _projectionPlanNode;
public AggregationPlanNode(IndexSegment indexSegment, BrokerRequest query) {
_indexSegment = indexSegment;
_brokerRequest = query;
_projectionPlanNode =
new ProjectionPlanNode(_indexSegment, getAggregationRelatedColumns(), new DocIdSetPlanNode(_indexSegment,
_brokerRequest, 5000));
for (int i = 0; i < _brokerRequest.getAggregationsInfo().size(); ++i) {
AggregationInfo aggregationInfo = _brokerRequest.getAggregationsInfo().get(i);
boolean hasDictionary = AggregationFunctionUtils.isAggregationFunctionWithDictionary(aggregationInfo, _indexSegment);
_aggregationFunctionPlanNodes.add(new AggregationFunctionPlanNode(aggregationInfo, _projectionPlanNode, hasDictionary));
}
}
private String[] getAggregationRelatedColumns() {
Set<String> aggregationRelatedColumns = new HashSet<String>();
for (AggregationInfo aggregationInfo : _brokerRequest.getAggregationsInfo()) {
if (!aggregationInfo.getAggregationType().equalsIgnoreCase("count")) {
String columns = aggregationInfo.getAggregationParams().get("column").trim();
aggregationRelatedColumns.addAll(Arrays.asList(columns.split(",")));
}
}
return aggregationRelatedColumns.toArray(new String[0]);
}
@Override
public Operator run() {
List<BAggregationFunctionOperator> aggregationFunctionOperatorList = new ArrayList<BAggregationFunctionOperator>();
for (AggregationFunctionPlanNode aggregationFunctionPlanNode : _aggregationFunctionPlanNodes) {
aggregationFunctionOperatorList.add((BAggregationFunctionOperator) aggregationFunctionPlanNode.run());
}
return new MAggregationOperator(_indexSegment, _brokerRequest.getAggregationsInfo(),
(MProjectionOperator) _projectionPlanNode.run(), aggregationFunctionOperatorList);
}
@Override
public void showTree(String prefix) {
LOGGER.debug(prefix + "Inner-Segment Plan Node :");
LOGGER.debug(prefix + "Operator: MAggregationOperator");
LOGGER.debug(prefix + "Argument 0: Projection - ");
_projectionPlanNode.showTree(prefix + " ");
for (int i = 0; i < _brokerRequest.getAggregationsInfo().size(); ++i) {
LOGGER.debug(prefix + "Argument " + (i + 1) + ": Aggregation - ");
_aggregationFunctionPlanNodes.get(i).showTree(prefix + " ");
}
}
}
| {'content_hash': 'd736e3a2afbd47094a0cfe5f6cd05791', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 126, 'avg_line_length': 43.08433734939759, 'alnum_prop': 0.7639821029082774, 'repo_name': 'jzmq/pinot', 'id': '7afcd9f8c0ba419673ccecd2fe0d6b78567e2970', 'size': '4213', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'pinot-core/src/main/java/com/linkedin/pinot/core/plan/AggregationPlanNode.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '4272'}, {'name': 'CSS', 'bytes': '633742'}, {'name': 'FreeMarker', 'bytes': '85448'}, {'name': 'GAP', 'bytes': '121494'}, {'name': 'HTML', 'bytes': '19007'}, {'name': 'Java', 'bytes': '5913188'}, {'name': 'JavaScript', 'bytes': '1774678'}, {'name': 'Python', 'bytes': '22994'}, {'name': 'R', 'bytes': '2430'}, {'name': 'Shell', 'bytes': '1204'}, {'name': 'TSQL', 'bytes': '637'}, {'name': 'Thrift', 'bytes': '6018'}]} |
var Key = require('../');
var sha256 = require('satoshi-hash').sha256;
var valid = require('./fixtures/valid.json');
var invalid = require('./fixtures/invalid.json');
describe('key', function () {
it('should throw \'invalid public key\' when the public key is not on the curve', function () {
expect(function () {
new Key({ pub: new Buffer('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81700', 'hex') });
}).to.throw('invalid public key');
});
describe('from private key (valid sigs)', function () {
valid.forEach(function (fixture) {
var key = new Key({ prv: new Buffer(fixture.prv, 'hex') });
describe('private key: ' + fixture.prv, function () {
it('generate public keys', function () {
expect(key.pub.toString('hex')).to.equal(fixture.pub);
expect(key.pubUncompressed.toString('hex')).to.equal(fixture.pubUncompressed);
});
it('generate correct address', function () {
expect(key.getAddress().toString()).to.equal(fixture.address);
});
if (fixture.signatures) {
fixture.signatures.forEach(function (signature, i) {
var hash = sha256(signature.data);
it('generate correct k #' + i, function () {
expect(Key.generateK(new Buffer(fixture.prv, 'hex'), hash).toString('hex')).to.equal(signature.k);
});
it('generate correct signature of \'' + signature.data.substring(0, 10) + '...\'', function () {
expect(key.sign(hash).toString('hex')).to.equal(signature.sig);
});
it('verify signature of \'' + signature.data.substring(0, 10) + '...\'', function () {
expect(key.verify(hash, new Buffer(signature.sig, 'hex'))).to.be.true;
});
});
}
});
});
});
describe('from private key (invalid sigs)', function () {
invalid.forEach(function (fixture) {
var key = new Key({ prv: new Buffer(fixture.prv, 'hex') });
if (fixture.signatures) {
fixture.signatures.forEach(function (signature, i) {
var hash = sha256(signature.data);
if (signature.change === 'data') {
it('generate incorrect k #' + i + ' for ' + fixture.prv, function () {
expect(Key.generateK(new Buffer(fixture.prv, 'hex'), hash).toString('hex')).to.not.equal(signature.k);
});
}
it('generate incorrect signature of \'' + signature.data.substring(0, 10) + '...\' for ' + fixture.prv, function () {
expect(key.sign(hash).toString('hex')).to.not.equal(signature.sig);
});
it('not verify signature of \'' + signature.data.substring(0, 10) + '...\' for ' + fixture.prv, function () {
expect(key.verify(hash, new Buffer(signature.sig, 'hex'))).to.be.false;
});
});
}
});
});
describe('from public key (compressed, valid sigs)', function () {
valid.forEach(function (fixture) {
var key = new Key({ pub: new Buffer(fixture.pub, 'hex') });
if (fixture.signatures) {
fixture.signatures.forEach(function (signature, i) {
var hash = sha256(signature.data);
it('verify signature of \'' + signature.data.substring(0, 10) + '...\' for ' + fixture.prv, function () {
expect(key.verify(hash, new Buffer(signature.sig, 'hex'))).to.be.true;
});
});
}
});
});
describe('from public key (compressed, invalid sigs)', function () {
invalid.forEach(function (fixture) {
var key = new Key({ pub: new Buffer(fixture.pub, 'hex') });
if (fixture.signatures) {
fixture.signatures.forEach(function (signature, i) {
var hash = sha256(signature.data);
it('not verify signature of \'' + signature.data.substring(0, 10) + '...\' for ' + fixture.prv, function () {
expect(key.verify(hash, new Buffer(signature.sig, 'hex'))).to.be.false;
});
});
}
});
});
describe('from public key (uncompressed, valid sigs)', function () {
valid.forEach(function (fixture) {
var key = new Key({ pub: new Buffer(fixture.pubUncompressed, 'hex') });
if (fixture.signatures) {
fixture.signatures.forEach(function (signature, i) {
var hash = sha256(signature.data);
it('verify signature of \'' + signature.data.substring(0, 10) + '...\' for ' + fixture.prv, function () {
expect(key.verify(hash, new Buffer(signature.sig, 'hex'))).to.be.true;
});
});
}
});
});
describe('from public key (uncompressed, invalid sigs)', function () {
invalid.forEach(function (fixture) {
var key = new Key({ pub: new Buffer(fixture.pubUncompressed, 'hex') });
if (fixture.signatures) {
fixture.signatures.forEach(function (signature, i) {
var hash = sha256(signature.data);
it('not verify signature of \'' + signature.data.substring(0, 10) + '...\' for ' + fixture.prv, function () {
expect(key.verify(hash, new Buffer(signature.sig, 'hex'))).to.be.false;
});
});
}
});
});
});
| {'content_hash': '23321dc814724c41106049333462d7e2', 'timestamp': '', 'source': 'github', 'line_count': 138, 'max_line_length': 127, 'avg_line_length': 37.67391304347826, 'alnum_prop': 0.5683785343335257, 'repo_name': 'coinative/satoshi-key', 'id': '98b49bac737886b54e5c9b9621154e07042aa553', 'size': '5199', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '9075'}, {'name': 'JavaScript', 'bytes': '12105'}, {'name': 'Python', 'bytes': '2149'}]} |
using System;
namespace TrackableEntities.Client
{
/// <summary>
/// Interface implemented by entities, 1-1 and M-1 properties of which have
/// non-standard names or locations of the corresponding change trackers.
/// </summary>
public interface IRefPropertyChangeTrackerResolver
{
/// <summary>
/// Get change tracker corresponding to a given 1-1 or M-1 property.
/// <param name="propertyName">Name of 1-1 or M-1 property</param>
/// </summary>
ITrackingCollection GetRefPropertyChangeTracker(string propertyName);
}
}
| {'content_hash': 'f293c5539e984d6eb65296cb79b8c4c2', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 79, 'avg_line_length': 34.8235294117647, 'alnum_prop': 0.6706081081081081, 'repo_name': 'edi0177/trackable-entities', 'id': '8e1a2b731a5d5a89ed10dd9a96a460d1b11169fc', 'size': '594', 'binary': False, 'copies': '5', 'ref': 'refs/heads/develop', 'path': 'Source/TrackableEntities.Client/IRefPropertyChangeTrackerResolver.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '555'}, {'name': 'Batchfile', 'bytes': '17390'}, {'name': 'C#', 'bytes': '1691565'}, {'name': 'CSS', 'bytes': '27320'}, {'name': 'Gherkin', 'bytes': '2481'}, {'name': 'HTML', 'bytes': '20268'}, {'name': 'JavaScript', 'bytes': '118089'}, {'name': 'PowerShell', 'bytes': '540076'}]} |
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, disconnect
from datetime import datetime
import tbapy
# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best option based on installed packages.
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
TEAM = 1418
tba = tbapy.TBA('%s:watchvictis:0.1' % TEAM)
current_data = None
def get_tba_data(debug=False):
"""
Fetch required data from The Blue Alliance and compile it.
:param debug: When True, provide data for a predefined event. For debugging when an event isn't going on.
:returns: Single JSON object with all data necessary for operation.
"""
if debug:
data = tba.event('2016vahay')
else:
data = {}
now = datetime.now()
for i in tba.team_events(TEAM, now.year):
start = list(map(int, i['start_date'].split('-')))
end = list(map(int, i['end_date'].split('-')))
if datetime(start[0], start[1], start[2]) < now and now < datetime(end[0], end[1], end[2]):
data = i
break
if data is not {}:
matches = sorted(tba.team_matches(TEAM, data['key']), key=lambda match: (['qm', 'qf', 'sf', 'f'].index(match['comp_level']), match['match_number']))
for i in range(0, len(matches)):
matches[i] = {
'comp_level': matches[i]['comp_level'],
'match_number': matches[i]['match_number'],
'teams': {
'red': list(map(lambda key: key[3:], matches[i]['alliances']['red']['teams'])),
'blue': list(map(lambda key: key[3:], matches[i]['alliances']['blue']['teams']))
}
}
data = {
'matches': matches,
'webcast': data['webcast'],
}
return data
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
global current_data
while True:
count += 1
current_data = get_tba_data(True)
socketio.emit('data',
current_data,
namespace='/req')
socketio.sleep(30)
@app.route('/')
def index():
return render_template('index.html', async_mode=socketio.async_mode)
@socketio.on('connect', namespace='/req')
def connect():
global thread
# Prevent opening of multiple threads at one time.
# This is annoying for the end-user, but we don't want to be fetching redundant TBA data for every single person viewing the app.
if thread is None:
thread = socketio.start_background_task(target=background_thread)
emit('data', current_data)
@socketio.on('disconnect', namespace='/req')
def disconnect():
print('Client disconnected', request.sid)
if __name__ == '__main__':
socketio.run(app, debug=True)
| {'content_hash': '6663ff4ec6c73067ac7830cce4d7dd51', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 156, 'avg_line_length': 33.043010752688176, 'alnum_prop': 0.5938821998047511, 'repo_name': 'ErikBoesen/watchvictis', 'id': '92fd8d4b0ff9e4e3d9ecf692e9807a1d74d82fc9', 'size': '3073', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/app.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1333'}, {'name': 'HTML', 'bytes': '990'}, {'name': 'JavaScript', 'bytes': '1609'}, {'name': 'Python', 'bytes': '3073'}]} |
package org.wso2.carbon.tools;
/**
* A Java class which defines tool specific constants.
*
* @since 5.0.0
*/
public class Constants {
// Carbon tool constants
public static final String CARBON_TOOL_SYSTEM_PROPERTY = "wso2.carbon.tool";
// OSGi Bundle manifest constants
public static final String MANIFEST_VERSION = "Manifest-Version";
public static final String BUNDLE_MANIFEST_VERSION = "Bundle-ManifestVersion";
public static final String BUNDLE_NAME = "Bundle-Name";
public static final String BUNDLE_SYMBOLIC_NAME = "Bundle-SymbolicName";
public static final String BUNDLE_ACTIVATOR = "Bundle-Activator";
public static final String BUNDLE_VERSION = "Bundle-Version";
public static final String EXPORT_PACKAGE = "Export-Package";
public static final String BUNDLE_CLASSPATH = "Bundle-ClassPath";
public static final String DYNAMIC_IMPORT_PACKAGE = "DynamicImport-Package";
// file path name and extension constants
public static final String JAR_TO_BUNDLE_TEMP_DIRECTORY_NAME = "temp";
public static final String JAR_MANIFEST_FOLDER = "META-INF";
public static final String MANIFEST_FILE_NAME = "MANIFEST.MF";
public static final String P2_INF_FILE_NAME = "p2";
public static final String P2_INF_FILE_EXTENSION = ".inf";
public static final String JAR_FILE_EXTENSION = ".jar";
public static final String ZIP_FILE_EXTENSION = ".zip";
// create zip file system properties
public static final String CREATE_NEW_ZIP_FILE_PROPERTY = "create";
public static final String ENCODING_TYPE_PROPERTY = "encoding";
/**
* Prevents instantiating this class.
*/
private Constants() {
}
}
| {'content_hash': '02113bb09ec84b6beaf2a0023d9a4ecb', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 82, 'avg_line_length': 40.57142857142857, 'alnum_prop': 0.7153755868544601, 'repo_name': 'wso2/carbon-kernel', 'id': '304444509b1b00907d9cd86fd0abdd8cd99deb86', 'size': '2350', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'tools/tools-core/src/main/java/org/wso2/carbon/tools/Constants.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '21107'}, {'name': 'HTML', 'bytes': '4878'}, {'name': 'Java', 'bytes': '754213'}, {'name': 'Shell', 'bytes': '33020'}]} |
<?php
require_once 'Zend/Gdata/Health.php';
require_once 'Zend/Gdata/Health/Query.php';
require_once 'Zend/Gdata/ClientLogin.php';
/**
* @category Zend
* @package Zend_Gdata_Health
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @group Zend_Gdata
* @group Zend_Gdata_Health
*/
class Zend_Gdata_HealthOnlineTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->user = constant('TESTS_ZEND_GDATA_CLIENTLOGIN_EMAIL');
$this->pass = constant('TESTS_ZEND_GDATA_CLIENTLOGIN_PASSWORD');
$serviceName = Zend_Gdata_Health::HEALTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($this->user, $this->pass, $serviceName);
$this->health = new Zend_Gdata_Health($client, 'google-MyPHPApp-v1.0');
}
private function setupProfileID()
{
$profileListFeed = $this->health->getHealthProfileListFeed();
$profileID = $profileListFeed->entry[0]->getProfileID();
$this->health->setProfileID($profileID);
}
public function testSetProfileID()
{
$this->health->setProfileID('123456790');
$this->assertEquals('123456790', $this->health->getProfileID());
}
public function testGetHealthProfileListFeedWithoutUsingClientLogin()
{
$client = new Zend_Gdata_HttpClient();
$this->health = new Zend_Gdata_Health($client);
try {
$feed = $this->health->getHealthProfileListFeed();
$this->fail('Expecting to catch Zend_Gdata_App_AuthException');
} catch (Exception $e) {
$this->assertThat($e, $this->isInstanceOf('Zend_Gdata_App_AuthException'),
'Expecting Zend_Gdata_App_AuthException, got '.get_class($e));
}
}
public function testGetHealthProfileFeedWithoutUsingClientLogin()
{
try {
$feed = $this->health->getHealthProfileFeed();
$this->fail('Expecting to catch Zend_Gdata_App_AuthException');
} catch (Exception $e) {
$this->assertThat($e, $this->isInstanceOf('Zend_Gdata_App_AuthException'),
'Expecting Zend_Gdata_App_AuthException, got '.get_class($e));
}
}
public function testUseH9()
{
$serviceName = Zend_Gdata_Health::H9_SANDBOX_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($this->user, $this->pass, $serviceName);
$h9 = new Zend_Gdata_Health($client, 'google-MyPHPApp-v1.0', true);
$profileListFeed = $h9->getHealthProfileListFeed();
$profileID = $profileListFeed->entry[0]->getProfileID();
$h9->setProfileID($profileID);
// query profile feed
$feed1 = $h9->getHealthProfileFeed();
$this->assertTrue($feed1 instanceof Zend_Gdata_Health_ProfileFeed);
foreach ($feed1->getEntries() as $entry) {
$this->assertTrue($entry instanceof Zend_Gdata_Health_ProfileEntry);
$this->assertEquals($entry->getHttpClient(), $feed1->getHttpClient());
}
// send CCR
$subject = "Title of your notice goes here";
$body = "Notice body can contain <b>html</b> entities";
$type = "html";
$ccrXML = file_get_contents('Zend/Gdata/Health/_files/ccr_notice_sample.xml', true);
$responseEntry = $h9->sendHealthNotice($subject, $body, $type, $ccrXML);
$this->assertTrue($responseEntry instanceof Zend_Gdata_Health_ProfileEntry);
$this->assertEquals($subject, $responseEntry->title->text);
$this->assertEquals($body, $responseEntry->content->text);
$this->assertEquals($type, $responseEntry->content->type);
$this->assertXmlStringEqualsXmlString($responseEntry->getCcr()->saveXML(), $ccrXML);
}
public function testGetHealthProfileListFeed()
{
// no query
$feed1 = $this->health->getHealthProfileListFeed();
$this->assertTrue($feed1 instanceof Zend_Gdata_Health_ProfileListFeed);
foreach ($feed1->getEntries() as $entry) {
$this->assertTrue($entry instanceof Zend_Gdata_Health_ProfileListEntry);
$this->assertEquals($entry->getHttpClient(), $feed1->getHttpClient());
}
// with query object
$query = new Zend_Gdata_Health_Query('https://www.google.com/health/feeds/profile/list');
$feed2 = $this->health->getHealthProfileListFeed($query);
$this->assertTrue($feed2 instanceof Zend_Gdata_Health_ProfileListFeed);
foreach ($feed2->entry as $entry) {
$this->assertTrue($entry instanceof Zend_Gdata_Health_ProfileListEntry);
$this->assertEquals($entry->getHttpClient(), $feed2->getHttpClient());
}
// with direct query string
$feed3 = $this->health->getHealthProfileListFeed('https://www.google.com/health/feeds/profile/list');
$this->assertTrue($feed3 instanceof Zend_Gdata_Health_ProfileListFeed);
foreach ($feed3->entry as $entry) {
$this->assertTrue($entry instanceof Zend_Gdata_Health_ProfileListEntry);
$this->assertEquals($entry->getHttpClient(), $feed3->getHttpClient());
}
$this->assertEquals($feed1->saveXML(), $feed2->saveXML());
$this->assertEquals($feed1->saveXML(), $feed3->saveXML());
$this->assertEquals($feed2->saveXML(), $feed3->saveXML());
}
public function testGetProfileFeedNoQuery()
{
$this->setupProfileID();
// no query, digest=false
$profileFeed = $this->health->getHealthProfileFeed();
$this->assertTrue($profileFeed instanceof Zend_Gdata_Health_ProfileFeed);
$this->assertTrue(count($profileFeed->entry) > 1, 'digest=false, should have multiple <entry> elements');
foreach ($profileFeed->entry as $entry) {
$this->assertTrue($entry instanceof Zend_Gdata_Health_ProfileEntry);
$ccr = $entry->getCcr();
$this->assertTrue($ccr instanceof Zend_Gdata_Health_Extension_Ccr);
$this->assertEquals($entry->getHttpClient(), $profileFeed->getHttpClient());
}
}
public function testGetProfileFeedByQuery()
{
$this->setupProfileID();
$profileID = $this->health->getProfileID();
// with direct query string
$feed1 = $this->health->getHealthProfileFeed(
"https://www.google.com/health/feeds/profile/ui/{$profileID}?digest=true");
$this->assertTrue($feed1 instanceof Zend_Gdata_Health_ProfileFeed);
$this->assertTrue(count($feed1->entry) === 1, 'digest=true, expected a single <entry> element');
foreach ($feed1->entry as $entry) {
$this->assertTrue($entry instanceof Zend_Gdata_Health_ProfileEntry);
$ccr = $entry->getCcr();
$this->assertTrue($ccr instanceof Zend_Gdata_Health_Extension_Ccr);
$this->assertEquals($entry->getHttpClient(), $feed1->getHttpClient());
}
// with query object
$query = new Zend_Gdata_Health_Query("https://www.google.com/health/feeds/profile/ui/{$profileID}");
$query->setDigest('true');
$feed2 = $this->health->getHealthProfileFeed($query);
$this->assertTrue($feed2 instanceof Zend_Gdata_Health_ProfileFeed);
$this->assertTrue(count($feed2->entry) === 1, 'digest=true, expected a single <entry> element');
foreach ($feed2->entry as $entry) {
$this->assertTrue($entry instanceof Zend_Gdata_Health_ProfileEntry);
$ccr = $entry->getCcr();
$this->assertTrue($ccr instanceof Zend_Gdata_Health_Extension_Ccr);
$this->assertEquals($entry->getHttpClient(), $feed2->getHttpClient());
}
$this->assertEquals($feed1->saveXML(), $feed2->saveXML());
}
public function testGetProfileEntryNoQuery()
{
try {
$entry = $this->health->getHealthProfileEntry();
$this->fail('Expecting to catch Zend_Gdata_App_InvalidArgumentException');
} catch (Exception $e) {
$this->assertThat($e, $this->isInstanceOf('Zend_Gdata_App_InvalidArgumentException'),
'Expecting Zend_Gdata_App_InvalidArgumentException, got '.get_class($e));
}
}
public function testGetProfileEntry()
{
$this->setupProfileID();
$profileID = $this->health->getProfileID();
$feed = $this->health->getHealthProfileFeed();
$entryFromProfileQuery = $feed->entry[0];
$this->assertTrue($entryFromProfileQuery instanceof Zend_Gdata_Health_ProfileEntry);
// direct query string
$entry1 = $this->health->getHealthProfileEntry($entryFromProfileQuery->id->text);
$this->assertTrue($entry1 instanceof Zend_Gdata_Health_ProfileEntry);
// query object
$query = new Zend_Gdata_Health_Query("https://www.google.com/health/feeds/profile/ui/{$profileID}");
$entry2 = $this->health->getHealthProfileEntry($query);
$this->assertTrue($entry2 instanceof Zend_Gdata_Health_ProfileEntry);
$this->assertEquals($entryFromProfileQuery->getHttpClient(), $entry1->getHttpClient());
$this->assertEquals($entryFromProfileQuery->getHttpClient(), $entry2->getHttpClient());
$this->assertEquals($entry1->getHttpClient(), $entry2->getHttpClient());
$this->assertXmlStringEqualsXmlString($entryFromProfileQuery->getCcr()->saveXML(), $entry1->getCcr()->saveXML());
$this->assertXmlStringEqualsXmlString($entryFromProfileQuery->getCcr()->saveXML(), $entry2->getCcr()->saveXML());
$this->assertXmlStringEqualsXmlString($entry1->getCcr()->saveXML(), $entry2->getCcr()->saveXML());
}
public function testSendNoticeWithoutUsingClientLogin()
{
try {
$responseEntry = $this->health->sendHealthNotice("", "");
$this->fail('Expecting to catch Zend_Gdata_App_AuthException');
} catch (Exception $e) {
$this->assertThat($e, $this->isInstanceOf('Zend_Gdata_App_AuthException'),
'Expecting Zend_Gdata_App_AuthException, got '.get_class($e));
}
}
public function testSendNoticeWithoutCcr()
{
$this->setupProfileID();
$profileID = $this->health->getProfileID();
$subject = "Title of your notice goes here";
$body = "Notice body goes here";
$responseEntry = $this->health->sendHealthNotice($subject, $body);
$this->assertTrue($responseEntry instanceof Zend_Gdata_Health_ProfileEntry);
$this->assertEquals($subject, $responseEntry->title->text);
$this->assertEquals($body, $responseEntry->content->text);
$this->assertNull($responseEntry->getCcr());
}
public function testSendNoticeWithoutCcrUsingDirectInsert()
{
$this->setupProfileID();
$profileID = $this->health->getProfileID();
$subject = "Title of your notice goes here";
$body = "Notice body goes here";
$entry = new Zend_Gdata_Health_ProfileEntry();
$author = $this->health->newAuthor();
$author->name = $this->health->newName('John Doe');
$author->email = $this->health->newEmail('[email protected]');
$entry->setAuthor(array(0 => $author));
$entry->title = $this->health->newTitle($subject);
$entry->content = $this->health->newContent($body);
$entry->content->type = 'text';
$ccrXML = file_get_contents('Zend/Gdata/Health/_files/ccr_notice_sample.xml', true);
$entry->setCcr($ccrXML);
$uri = "https://www.google.com/health/feeds/register/ui/{$profileID}";
$responseEntry = $this->health->insertEntry($entry, $uri, 'Zend_Gdata_Health_ProfileEntry');
$this->assertTrue($responseEntry instanceof Zend_Gdata_Health_ProfileEntry);
$this->assertEquals($subject, $responseEntry->title->text);
$this->assertEquals($author->name->text, 'John Doe');
$this->assertEquals($author->email->text, '[email protected]');
$this->assertEquals($body, $responseEntry->content->text);
}
public function testSendNoticeWithCcr()
{
$this->setupProfileID();
$profileID = $this->health->getProfileID();
$subject = "Title of your notice goes here";
$body = "Notice body can contain <b>html</b> entities";
$type = "html";
$ccrXML = file_get_contents('Zend/Gdata/Health/_files/ccr_notice_sample.xml', true);
$responseEntry = $this->health->sendHealthNotice($subject, $body, $type, $ccrXML);
$this->assertTrue($responseEntry instanceof Zend_Gdata_Health_ProfileEntry);
$this->assertEquals($subject, $responseEntry->title->text);
$this->assertEquals($body, $responseEntry->content->text);
$this->assertEquals($type, $responseEntry->content->type);
$this->assertXmlStringEqualsXmlString($responseEntry->getCcr()->saveXML(), $ccrXML);
}
}
| {'content_hash': '00c3ce74cbccda303c1ebd4b55c1d09c', 'timestamp': '', 'source': 'github', 'line_count': 298, 'max_line_length': 121, 'avg_line_length': 43.711409395973156, 'alnum_prop': 0.6363426992169507, 'repo_name': 'karthiksekarnz/educulas', 'id': 'ff87ac3818c7f22f6d91e4af914738a2a3422694', 'size': '13750', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tests/Zend/Gdata/HealthOnlineTest.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ActionScript', 'bytes': '19954'}, {'name': 'Java', 'bytes': '123492'}, {'name': 'JavaScript', 'bytes': '8306153'}, {'name': 'PHP', 'bytes': '32985843'}, {'name': 'Ruby', 'bytes': '911'}, {'name': 'Shell', 'bytes': '20173'}]} |
import { expect } from 'chai';
import parser from '~/lib/modules/variable-parser';
describe('Variable Parser', () => {
var options = {
parsers: {
sass: 'sass',
scss: 'scss',
less: 'less',
postcss: 'postcss'
}
};
it('should not fail on empty files', (done) => {
var files = {
'empty.css': ''
};
parser.parseVariableDeclarationsFromFiles(files, options).then((variables) => {
expect(variables).to.eql([]);
}).then(done).catch(done);
});
it('should handle plain CSS files', (done) => {
var files = {
'aaa.css': `.test {}`
};
parser.parseVariableDeclarationsFromFiles(files, options).then((variables) => {
expect(variables).to.eql([]);
}).then(done).catch(done);
});
it('should handle unknown file types', (done) => {
var files = {
'aaa.foobar': `.test {}`
};
parser.parseVariableDeclarationsFromFiles(files, options).then((variables) => {
expect(variables).to.eql([]);
}).then(done).catch(done);
});
it('should detect file format from extension', (done) => {
var files = {
'file.sass': `
$color: red
.foo
color: $color;`,
'file.scss': `
$color: red
.foo {
color: $color;
}`,
'file.less': `
@foo: red;
.foo {
color: @foo;
}`,
'file.postcss': `
--color: red;
.foo {
color: var(--color);
}`
};
parser.parseVariableDeclarationsFromFiles(files, options).then((variables) => {
expect(variables.length).to.eql(4);
}).then(done).catch(done);
});
describe('finding variable declarations from multiple files', () => {
var files;
beforeEach(() => {
files = {
'ccc.scss': `
$var4: value1;
$same: file3;`,
'aaa.scss': `
$var2: value2;
$var1: value1;
$same: file1;`,
'bbb.scss': `
$var3: value3;`
};
});
it('should sort variables by filename', (done) => {
parser.parseVariableDeclarationsFromFiles(files, options).then((variables) => {
expect(variables[0].file).to.eql('aaa.scss');
expect(variables[1].file).to.eql('aaa.scss');
expect(variables[2].file).to.eql('aaa.scss');
expect(variables[3].file).to.eql('bbb.scss');
expect(variables[4].file).to.eql('ccc.scss');
expect(variables[5].file).to.eql('ccc.scss');
}).then(done).catch(done);
});
it('should not sort variables inside a single file', (done) => {
parser.parseVariableDeclarationsFromFiles(files, options).then((variables) => {
expect(variables[0].name).to.eql('var2');
expect(variables[1].name).to.eql('var1');
expect(variables[2].name).to.eql('same');
}).then(done).catch(done);
});
it('should allow same variable name inside multiple files', (done) => {
parser.parseVariableDeclarationsFromFiles(files, options).then((variables) => {
expect(variables[2].name).to.eql('same');
expect(variables[5].name).to.eql('same');
}).then(done).catch(done);
});
it('should add hex encoded hash of file path to each variable', (done) => {
var hex = /[a-h0-9]/;
parser.parseVariableDeclarationsFromFiles(files, options).then((variables) => {
variables.forEach((variable) => {
expect(variable.fileHash).to.match(hex);
});
}).then(done).catch(done);
});
});
describe('modifier variable finding', () => {
it('should detect SCSS variables correctly', () => {
var input = [
{
name: '$var1'
},
{
name: '.modifier'
},
{
name: '$var2'
}
];
expect(parser.findModifierVariables(input)).to.eql(['var1', 'var2']);
});
it('should detect LESS variables correctly', () => {
var input = [
{
name: '@var1'
},
{
name: '.modifier'
},
{
name: '@var2'
}
];
expect(parser.findModifierVariables(input)).to.eql(['var1', 'var2']);
});
it('should return empty array when no variables are found', () => {
var input = [
{
name: '.modifier'
}
];
expect(parser.findModifierVariables(input)).to.eql([]);
});
it('should return empty array with undefined input', () => {
expect(parser.findModifierVariables()).to.eql([]);
});
});
});
| {'content_hash': '286ace1ee6d33879a57a47e02862bf5a', 'timestamp': '', 'source': 'github', 'line_count': 169, 'max_line_length': 85, 'avg_line_length': 26.928994082840237, 'alnum_prop': 0.5288947484069435, 'repo_name': 'junaidrsd/sc5-styleguide', 'id': '40cc120fa2ec6327a54b16fab2f080bc3718e6f8', 'size': '4551', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'test/unit/modules/variable-parser.test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '89211'}, {'name': 'HTML', 'bytes': '25935'}, {'name': 'JavaScript', 'bytes': '306201'}]} |
<?php
namespace Doctrine\ODM\MongoDB\Mapping\Types;
/**
* The BinDataFunc type.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 1.0
* @author Jonathan H. Wage <[email protected]>
* @author Roman Borschel <[email protected]>
*/
class BinDataFuncType extends Type
{
public function convertToDatabaseValue($value)
{
return $value !== null ? new \MongoBinData($value, \MongoBinData::FUNC) : null;
}
public function convertToPHPValue($value)
{
return $value !== null ? $value->bin : null;
}
} | {'content_hash': 'aca04004cd2cb626d804ac278dbf51c6', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 87, 'avg_line_length': 24.423076923076923, 'alnum_prop': 0.6409448818897637, 'repo_name': 'duodraco/ophpen', 'id': 'f1aca121af7b23c1c96498777837ecc0c3c62635', 'size': '1609', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/vendor/doctrine-mongodb/lib/Doctrine/ODM/MongoDB/Mapping/Types/BinDataFuncType.php', 'mode': '33188', 'license': 'mit', 'language': []} |
package org.sleuthkit.autopsy.contentviewers;
import java.awt.Component;
import java.util.List;
import org.sleuthkit.datamodel.AbstractFile;
import java.util.Arrays;
import com.dd.plist.NSDictionary;
import com.dd.plist.PropertyListParser;
import com.dd.plist.NSObject;
import com.dd.plist.NSArray;
import com.dd.plist.NSDate;
import com.dd.plist.NSString;
import com.dd.plist.NSNumber;
import com.dd.plist.NSData;
import com.dd.plist.PropertyListFormatException;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableCellRenderer;
import javax.xml.parsers.ParserConfigurationException;
import org.netbeans.swing.outline.DefaultOutlineModel;
import org.netbeans.swing.outline.Outline;
import org.openide.explorer.ExplorerManager;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.util.NbBundle;
import org.openide.windows.WindowManager;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.TskCoreException;
import org.xml.sax.SAXException;
/**
* PListViewer - a file viewer for binary plist files.
*
*/
@SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives
class PListViewer extends javax.swing.JPanel implements FileTypeViewer, ExplorerManager.Provider {
private static final long serialVersionUID = 1L;
private static final String[] MIMETYPES = new String[]{"application/x-bplist"};
private static final Logger logger = Logger.getLogger(PListViewer.class.getName());
private final org.openide.explorer.view.OutlineView outlineView;
private final Outline outline;
private ExplorerManager explorerManager;
private NSDictionary rootDict;
/**
* Creates new form PListViewer
*/
public PListViewer() {
// Create an Outlineview and add to the panel
outlineView = new org.openide.explorer.view.OutlineView();
initComponents();
outline = outlineView.getOutline();
((DefaultOutlineModel) outline.getOutlineModel()).setNodesColumnLabel("Key");
outlineView.setPropertyColumns(
"Type", Bundle.PListNode_TypeCol(),
"Value", Bundle.PListNode_ValueCol());
customize();
}
@NbBundle.Messages({"PListNode.KeyCol=Key",
"PListNode.TypeCol=Type",
"PListNode.ValueCol=Value"})
private void customize() {
outline.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
outline.setRootVisible(false);
if (null == explorerManager) {
explorerManager = new ExplorerManager();
}
//outline.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
plistTableScrollPane.setViewportView(outlineView);
outline.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
this.setVisible(true);
outline.setRowSelectionAllowed(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
plistTableScrollPane = new javax.swing.JScrollPane();
hdrPanel = new javax.swing.JPanel();
exportButton = new javax.swing.JButton();
jPanel1.setLayout(new java.awt.BorderLayout());
plistTableScrollPane.setBorder(null);
plistTableScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
plistTableScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
jPanel1.add(plistTableScrollPane, java.awt.BorderLayout.CENTER);
org.openide.awt.Mnemonics.setLocalizedText(exportButton, org.openide.util.NbBundle.getMessage(PListViewer.class, "PListViewer.exportButton.text")); // NOI18N
exportButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exportButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout hdrPanelLayout = new javax.swing.GroupLayout(hdrPanel);
hdrPanel.setLayout(hdrPanelLayout);
hdrPanelLayout.setHorizontalGroup(
hdrPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, hdrPanelLayout.createSequentialGroup()
.addContainerGap(320, Short.MAX_VALUE)
.addComponent(exportButton)
.addContainerGap())
);
hdrPanelLayout.setVerticalGroup(
hdrPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, hdrPanelLayout.createSequentialGroup()
.addGap(0, 6, Short.MAX_VALUE)
.addComponent(exportButton))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(hdrPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(5, 5, 5))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(hdrPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
@NbBundle.Messages({"PListViewer.ExportSuccess.message=Plist file exported successfully",
"PListViewer.ExportFailed.message=Plist file export failed.",})
/**
* Handles the Export button pressed action
*/
private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
Case openCase;
try {
openCase = Case.getCurrentCaseThrows();
} catch (NoCurrentCaseException ex) {
JOptionPane.showMessageDialog(this,
"Failed to export plist file.",
Bundle.PListViewer_ExportFailed_message(),
JOptionPane.ERROR_MESSAGE);
logger.log(Level.SEVERE, "Exception while getting open case.", ex);
return;
}
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(openCase.getExportDirectory()));
fileChooser.setFileFilter(new FileNameExtensionFilter("XML file", "xml"));
final int returnVal = fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (!selectedFile.getName().endsWith(".xml")) { // NON-NLS
selectedFile = new File(selectedFile.toString() + ".xml"); // NON-NLS
}
try {
//Save the propery list as XML
PropertyListParser.saveAsXML(this.rootDict, selectedFile);
JOptionPane.showMessageDialog(this,
String.format("Plist file exported successfully to %s ", selectedFile.getName()),
Bundle.PListViewer_ExportSuccess_message(),
JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(this,
String.format("Failed to export plist file to %s ", selectedFile.getName()),
Bundle.PListViewer_ExportFailed_message(),
JOptionPane.ERROR_MESSAGE);
logger.log(Level.SEVERE, "Error exporting plist to XML file " + selectedFile.getName(), ex);
}
}
}//GEN-LAST:event_exportButtonActionPerformed
/**
* Returns mime types supported by this viewer
*
* @return list of supported mime types
*/
@Override
public List<String> getSupportedMIMETypes() {
return Arrays.asList(MIMETYPES);
}
/**
* Sets the file to be displayed in the viewer
*
* @param file file to display
*/
@Override
public void setFile(final AbstractFile file) {
processPlist(file);
}
/**
* Returns the viewer component
*
* @return the viewer component
*/
@Override
public Component getComponent() {
return this;
}
/**
* Resets the viewer component
*
*/
@Override
public void resetComponent() {
rootDict = null;
}
/**
* Process the given Plist file
*
* @param plistFile -
*
* @return none
*/
@NbBundle.Messages({"PListViewer.processPlist.interruptedMessage=Interrupted while parsing/displaying plist file.",
"PListViewer.processPlist.errorMessage=Error while parsing/displaying plist file."})
private void processPlist(final AbstractFile plistFile) {
new SwingWorker<List<PropKeyValue>, Void>() {
@Override
protected List<PropKeyValue> doInBackground() throws TskCoreException, IOException, PropertyListFormatException, ParseException, ParserConfigurationException, SAXException {
// Read in and parse the file
final byte[] plistFileBuf = new byte[(int) plistFile.getSize()];
plistFile.read(plistFileBuf, 0, plistFile.getSize());
final List<PropKeyValue> plist = parsePList(plistFileBuf);
return plist;
}
@Override
protected void done() {
super.done();
List<PropKeyValue> plist;
try {
plist = get();
setupTable(plist);
SwingUtilities.invokeLater(() -> {
setColumnWidths();
});
} catch (InterruptedException ex) {
logger.log(Level.SEVERE, "Interruption while parsing/dislaying plist file " + plistFile.getName(), ex);
JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
ex.getMessage(),
Bundle.PListViewer_processPlist_interruptedMessage(),
JOptionPane.ERROR_MESSAGE);
} catch (ExecutionException ex) {
logger.log(Level.SEVERE, "Exception while parsing/dislaying plist file " + plistFile.getName(), ex);
JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
ex.getCause().getMessage(),
Bundle.PListViewer_processPlist_errorMessage(),
JOptionPane.ERROR_MESSAGE);
}
}
}.execute();
}
/**
* Sets up the columns in the display table
*
* @param tableRows
*/
private void setupTable(final List<PropKeyValue> tableRows) {
explorerManager.setRootContext(new AbstractNode(Children.create(new PListRowFactory(tableRows), true)));
}
/**
* Sets up the column widths
*
*/
private void setColumnWidths() {
final int margin = 4;
final int padding = 8;
// find the maximum width needed to fit the values for the first N rows, at most
final int rows = Math.min(20, outline.getRowCount());
for (int col = 0; col < outline.getColumnCount(); col++) {
final int columnWidthLimit = 2000;
int columnWidth = 0;
for (int row = 0; row < rows; row++) {
final TableCellRenderer renderer = outline.getCellRenderer(row, col);
final Component comp = outline.prepareRenderer(renderer, row, col);
columnWidth = Math.max(comp.getPreferredSize().width, columnWidth);
}
columnWidth += 2 * margin + padding; // add margin and regular padding
columnWidth = Math.min(columnWidth, columnWidthLimit);
outline.getColumnModel().getColumn(col).setPreferredWidth(columnWidth);
}
}
/**
* Parses the given plist key/value
*/
@NbBundle.Messages({"PListViewer.DataType.message=Binary Data value not shown"})
private PropKeyValue parseProperty(final String key, final NSObject value) {
if (value == null) {
return null;
} else if (value instanceof NSString) {
return new PropKeyValue(key, PropertyType.STRING, value.toString());
} else if (value instanceof NSNumber) {
final NSNumber number = (NSNumber) value;
if (number.isInteger()) {
return new PropKeyValue(key, PropertyType.NUMBER, number.longValue());
} else if (number.isBoolean()) {
return new PropKeyValue(key, PropertyType.BOOLEAN, number.boolValue());
} else {
return new PropKeyValue(key, PropertyType.NUMBER, number.floatValue());
}
} else if (value instanceof NSDate) {
final NSDate date = (NSDate) value;
return new PropKeyValue(key, PropertyType.DATE, date.toString());
} else if (value instanceof NSData) {
return new PropKeyValue(key, PropertyType.DATA, Bundle.PListViewer_DataType_message());
} else if (value instanceof NSArray) {
final List<PropKeyValue> children = new ArrayList<>();
final NSArray array = (NSArray) value;
final PropKeyValue pkv = new PropKeyValue(key, PropertyType.ARRAY, array);
for (int i = 0; i < array.count(); i++) {
children.add(parseProperty("", array.objectAtIndex(i)));
}
pkv.setChildren(children.toArray(new PropKeyValue[children.size()]));
return pkv;
} else if (value instanceof NSDictionary) {
final List<PropKeyValue> children = new ArrayList<>();
final NSDictionary dict = (NSDictionary) value;
final PropKeyValue pkv = new PropKeyValue(key, PropertyType.DICTIONARY, dict);
for (final String key2 : ((NSDictionary) value).allKeys()) {
final NSObject obj = ((NSDictionary) value).objectForKey(key2);
children.add(parseProperty(key2, obj));
}
pkv.setChildren(children.toArray(new PropKeyValue[children.size()]));
return pkv;
} else {
logger.log(Level.SEVERE, "Can''t parse Plist for key = {0} value of type {1}", new Object[]{key, value.getClass()});
}
return null;
}
/**
* Parses given binary stream and extracts Plist key/value
*
* @param plistbytes
*
* @return list of PropKeyValue
*/
private List<PropKeyValue> parsePList(final byte[] plistbytes) throws IOException, PropertyListFormatException, ParseException, ParserConfigurationException, SAXException {
final List<PropKeyValue> plist = new ArrayList<>();
rootDict = (NSDictionary) PropertyListParser.parse(plistbytes);
final String[] keys = rootDict.allKeys();
for (final String key : keys) {
final PropKeyValue pkv = parseProperty(key, rootDict.objectForKey(key));
if (null != pkv) {
plist.add(pkv);
}
}
return plist;
}
@Override
public ExplorerManager getExplorerManager() {
return explorerManager;
}
/**
* Plist property type
*/
enum PropertyType {
STRING,
NUMBER,
BOOLEAN,
DATE,
DATA,
ARRAY,
DICTIONARY
};
/**
* Encapsulates a Plist property
*
*/
final static class PropKeyValue {
private final String key;
private final PropertyType type;
private final Object value;
private PropKeyValue[] children;
PropKeyValue(String key, PropertyType type, Object value) {
this.key = key;
this.type = type;
this.value = value;
this.children = null;
}
/**
* Copy constructor
*/
PropKeyValue(PropKeyValue other) {
this.key = other.getKey();
this.type = other.getType();
this.value = other.getValue();
this.setChildren(other.getChildren());
}
String getKey() {
return this.key;
}
PropertyType getType() {
return this.type;
}
Object getValue() {
return this.value;
}
/**
* Returns an array of children, if any.
*
* @return
*/
PropKeyValue[] getChildren() {
if (children == null) {
return null;
}
// return a copy
return Arrays.stream(children)
.map(child -> new PropKeyValue(child))
.toArray(PropKeyValue[]::new);
}
void setChildren(final PropKeyValue... children) {
if (children != null) {
this.children = Arrays.stream(children)
.map(child -> new PropKeyValue(child))
.toArray(PropKeyValue[]::new);
}
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton exportButton;
private javax.swing.JPanel hdrPanel;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane plistTableScrollPane;
// End of variables declaration//GEN-END:variables
}
| {'content_hash': '1e8593b0bc2d312d8ed1e1678a58eafe', 'timestamp': '', 'source': 'github', 'line_count': 517, 'max_line_length': 185, 'avg_line_length': 37.17988394584139, 'alnum_prop': 0.6189262303610447, 'repo_name': 'millmanorama/autopsy', 'id': '506084f0c3f251d8ffada69c1244f38575b9cfe6', 'size': '19903', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'Core/src/org/sleuthkit/autopsy/contentviewers/PListViewer.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '4467'}, {'name': 'HTML', 'bytes': '9644'}, {'name': 'Java', 'bytes': '11348573'}, {'name': 'Python', 'bytes': '297069'}, {'name': 'Shell', 'bytes': '9705'}]} |
package io.dropwizard.jersey.sessions;
import io.dropwizard.jersey.AbstractJerseyTest;
import io.dropwizard.jersey.DropwizardResourceConfig;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.servlet.ServletProperties;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.jupiter.api.Test;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class FlashFactoryTest extends AbstractJerseyTest {
@Override
protected TestContainerFactory getTestContainerFactory()
throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
@Override
protected DeploymentContext configureDeployment() {
final ResourceConfig rc = DropwizardResourceConfig.forTesting();
return ServletDeploymentContext.builder(rc)
.initParam(ServletProperties.JAXRS_APPLICATION_CLASS, DropwizardResourceConfig.class.getName())
.initParam(ServerProperties.PROVIDER_CLASSNAMES, FlashResource.class.getName())
.build();
}
@Test
public void passesInHttpSessions() throws Exception {
Response firstResponse = target("/flash").request(MediaType.TEXT_PLAIN)
.post(Entity.entity("Mr. Peeps", MediaType.TEXT_PLAIN));
final Map<String, NewCookie> cookies = firstResponse.getCookies();
firstResponse.close();
Invocation.Builder builder = target("/flash").request().accept(MediaType.TEXT_PLAIN);
for (NewCookie cookie : cookies.values()) {
builder = builder.cookie(cookie);
}
final String secondResponse = builder.get(String.class);
assertThat(secondResponse).isEqualTo("Mr. Peeps");
Invocation.Builder anotherBuilder = target("/flash").request().accept(MediaType.TEXT_PLAIN);
for (NewCookie cookie : cookies.values()) {
anotherBuilder = anotherBuilder.cookie(cookie);
}
final String thirdResponse = anotherBuilder.get(String.class);
assertThat(thirdResponse).isEqualTo("null");
}
}
| {'content_hash': '2bce2f719ec72b8830eb390b61601356', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 111, 'avg_line_length': 37.55072463768116, 'alnum_prop': 0.7344654573523736, 'repo_name': 'pkwarren/dropwizard', 'id': 'b8d11e9daba4ae1d5fcd572f7dc92a8e52927ec0', 'size': '2591', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'dropwizard-jersey/src/test/java/io/dropwizard/jersey/sessions/FlashFactoryTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'FreeMarker', 'bytes': '992'}, {'name': 'HTML', 'bytes': '680'}, {'name': 'Java', 'bytes': '2595785'}, {'name': 'Shell', 'bytes': '6865'}]} |
/**
* Test Lock
*/
package com.ciaoshen.thinkinjava.chapter21;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.*;
public class Checker2{
private volatile TestLock tl;
public Checker2(TestLock tl){this.tl=tl;}
public class Run implements Runnable{
@Override
public void run(){
//synchronized(Checker2.this){ //不行
long stop=System.currentTimeMillis()+10;
while(System.currentTimeMillis()<stop){
synchronized(tl){ //这里可以
tl.increment();
}
}
//}
}
}
public class Check implements Runnable{
@Override
public void run(){
//synchronized(Checker2.this){ //不行
long stop=System.currentTimeMillis()+10;
int num;
while(System.currentTimeMillis()<stop){
synchronized(tl){ //这里可以
num=tl.getNum();
}
if(num%2!=0){
System.out.println(num);
Thread.yield();
}
}
//}
}
}
//main execute the runnable
public static void main(String[] args){
Checker2 ck=new Checker2(new TestLock());
ExecutorService es=Executors.newCachedThreadPool();
es.execute(ck.new Run());
es.execute(ck.new Check());
es.shutdown();
}
} | {'content_hash': 'ec763fe718cbe70575a2ff90252cda2a', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 59, 'avg_line_length': 29.576923076923077, 'alnum_prop': 0.4908972691807542, 'repo_name': 'helloShen/thinkinginjava', 'id': 'cbb27b9150332f64306a17ea613740a66368d396', 'size': '1562', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'chapter21/Checker2.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1210147'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.