text stringlengths 2 1.04M | meta dict |
|---|---|
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="Timer Lite">
<Require feature="rpc"/>
<Require feature="views"/>
</ModulePrefs>
<Content type="html">
<![CDATA[
<script src="//plus.google.com/hangouts/_/api/v1/hangout.js"></script>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://rawgithub.com/phudekar/hangout-timer/master/main.css"/>
<script type="text/javascript" src="https://rawgithub.com/phudekar/hangout-timer/master/timer.js"></script>
</head>
<body>
<div class="main">
<div id="timer">00:00:00</div>
<div class="buttons">
<input type="button" id="start" value="Start" onclick="start(true)">
<input type="button" id="stop" value="Stop" onclick="stop(true)">
<input type="button" id="reset" value="Reset" onclick="reset(true)">
</div>
<div>
<div class="messages">
<textarea id="messageArea" rows="10" cols="32" readonly="readonly">
</textarea>
</div>
<div class="messagesOverlay"></div>
</div>
</div>
</body>
</html>
]]>
</Content>
</Module>
| {
"content_hash": "f134358bf630df1206bcb89afdaefad3",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 114,
"avg_line_length": 30.88888888888889,
"alnum_prop": 0.6070143884892086,
"repo_name": "phudekar/hangout-timer",
"id": "9666d1454ba3c14d4eecba482e2e4e4bf2e8c070",
"size": "1112",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gadget.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1072"
},
{
"name": "JavaScript",
"bytes": "2714"
}
],
"symlink_target": ""
} |
<!--
~ Copyright 2016 The Bazel Authors. All rights reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<idea-plugin>
<vendor>Google</vendor>
<extensions defaultExtensionNs="com.intellij">
<applicationService serviceInterface="com.google.idea.blaze.base.plugin.BlazePluginId"
serviceImplementation="com.google.idea.blaze.ijwb.plugin.IjwbPluginId"/>
</extensions>
<extensions defaultExtensionNs="com.google.idea.blaze">
<SyncPlugin implementation="com.google.idea.blaze.ijwb.android.BlazeAndroidLiteSyncPlugin"/>
<SyncPlugin implementation="com.google.idea.blaze.ijwb.javascript.BlazeJavascriptSyncPlugin"/>
<SyncPlugin implementation="com.google.idea.blaze.ijwb.typescript.BlazeTypescriptSyncPlugin"/>
<SyncPlugin implementation="com.google.idea.blaze.ijwb.dart.BlazeDartSyncPlugin"/>
<JavaSyncAugmenter implementation="com.google.idea.blaze.ijwb.android.BlazeAndroidLiteJavaSyncAugmenter"/>
<PrefetchFileSource implementation="com.google.idea.blaze.ijwb.javascript.JavascriptPrefetchFileSource"/>
<PrefetchFileSource implementation="com.google.idea.blaze.ijwb.typescript.TypescriptPrefetchFileSource"/>
</extensions>
</idea-plugin>
| {
"content_hash": "1074163a9e9e67abf9fcea6c15fb1aab",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 110,
"avg_line_length": 51.088235294117645,
"alnum_prop": 0.7639608520437536,
"repo_name": "brendandouglas/intellij",
"id": "8e22848a9cfd9522c48a949c9169b6a932584d19",
"size": "1737",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ijwb/src/META-INF/ijwb.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "390"
},
{
"name": "C++",
"bytes": "190"
},
{
"name": "Java",
"bytes": "5276951"
},
{
"name": "Python",
"bytes": "166921"
},
{
"name": "Scala",
"bytes": "466"
}
],
"symlink_target": ""
} |
package Google::Ads::GoogleAds::V11::Services::ThirdPartyAppAnalyticsLinkService::RegenerateShareableLinkIdRequest;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {resourceName => $args->{resourceName}};
# Delete the unassigned fields in this object for a more concise JSON payload
remove_unassigned_fields($self, $args);
bless $self, $class;
return $self;
}
1;
| {
"content_hash": "7e007f3745b5e33f38891cf5101420a7",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 115,
"avg_line_length": 25.3,
"alnum_prop": 0.7272727272727273,
"repo_name": "googleads/google-ads-perl",
"id": "5c67480ec87fff40c7c79cef77550d3599743f39",
"size": "1082",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "lib/Google/Ads/GoogleAds/V11/Services/ThirdPartyAppAnalyticsLinkService/RegenerateShareableLinkIdRequest.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "73"
},
{
"name": "Perl",
"bytes": "5866064"
}
],
"symlink_target": ""
} |
FROM ubuntu:16.10
LABEL maintainer "https://github.com/Drowrin/Weeabot"
RUN apt-get update \
&& apt-get install python3.6 python3.6-dev python3-pip -y \
&& apt-get install ffmpeg -y \
&& apt-get install libopus-dev -y \
&& apt-get install libffi-dev -y \
&& apt-get install git -y \
&& apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk -y
RUN python3.6 -m pip install -U https://github.com/Rapptz/discord.py/archive/master.zip#egg=discord.py[voice] \
&& python3.6 -m pip install -U https://github.com/gunthercox/ChatterBot/archive/master.zip#egg=ChatterBot \
&& python3.6 -m pip install pyimgur \
&& python3.6 -m pip install Pillow \
&& python3.6 -m pip install cleverbot \
&& python3.6 -m pip install python-dateutil \
&& python3.6 -m pip install xmltodict \
&& python3.6 -m pip install beautifulsoup4 \
&& python3.6 -m pip install python-twitter
| {
"content_hash": "a1c5ee4f14293d7aac85790745732783",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 135,
"avg_line_length": 46.80952380952381,
"alnum_prop": 0.6876907426246185,
"repo_name": "Drowrin/Weeabot",
"id": "78b6f5d02a388488d02db45b44a991b2b1fcf857",
"size": "983",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "base_Dockerfile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "206327"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MiniNet
{
public interface INetServerOptions
{
bool IPv4Only { get; set; }
int MaxAccept { get; set; }
int MaxConnections { get; set; }
int BufferSize { get; set; }
int ReceivePrefixLength { get; set; }
int SendPrefixLength { get; set; }
}
}
| {
"content_hash": "8b2b45344b2e2c5760a9692aae7144e5",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 45,
"avg_line_length": 23.88888888888889,
"alnum_prop": 0.6372093023255814,
"repo_name": "Q-Smith/MS.NET-MiniNet",
"id": "9a8fb41f1c24ceca16cd133a068f56142c46368e",
"size": "432",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Core/MiniNet.Core/Interfaces/INetServerOptions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "48540"
}
],
"symlink_target": ""
} |
angular.module('ez.datetime')
.constant('EzDatetimeConfig', {
/**
* The minimum view of the calendar
* @options [year, month, day]
*/
minView: 'day',
/**
* The start view of the calendar
* @options [year, month, day]
*/
startView: 'day',
/**
* The momentjs date format for the model data
*/
modelFormat: undefined, // defaults to ISO-8601
/**
* The momentjs date format for the view data
*/
viewFormat: 'MMM Do YYYY [at] h:mma',
/**
* The date to bind ng-model with
*
* options: ["default", "from", "to"]
*/
modelBinding: 'default',
/**
* Enable time selection
*/
timepickerEnabled: true,
/**
* Seconds enabled?
*/
secondsEnabled: false,
/**
* Show AM/PM ?
*/
meridiemEnabled: true,
/**
* Increment/decrement hour options by...
*/
hourStep: 1,
/**
* Increment/decrement minute options by...
*/
minuteStep: 15,
/**
* Increment/decrement second options by...
*/
secondStep: 15,
/**
* Timepicker hour format
*/
hourFormat: 'h',
/**
* Timepicker minute format
*/
minuteFormat: 'mm',
/**
* Timepicker second format
*/
secondFormat: 'ss',
/**
* Timepicker meridiem format
*/
meridiemFormat: 'A',
/**
* Modal heading
*/
heading: 'Select a Date',
/**
* Modal range heading
*/
rangeHeading: 'Select a Start & End Date',
/**
* Modal ok button text
*/
okBtnText: 'OK',
/**
* Modal cancel button text
*/
cancelBtnText: 'Cancel'
})
;
| {
"content_hash": "e7316150286139d4db7fcd7fec9b6e13",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 51,
"avg_line_length": 16.12264150943396,
"alnum_prop": 0.510825043885313,
"repo_name": "kirinse/ez-datetime",
"id": "13ace567099a25231f45ec705c22012c0affd083",
"size": "1709",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/constants/DatetimeConfig.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "25095"
},
{
"name": "HTML",
"bytes": "12560"
},
{
"name": "JavaScript",
"bytes": "188834"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>NetSim: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">NetSim
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div class="header">
<div class="headertitle">
<div class="title">UnackEvent Member List</div> </div>
</div><!--header-->
<div class="contents">
This is the complete list of members for <a class="el" href="classUnackEvent.html">UnackEvent</a>, including all inherited members.<table>
<tr bgcolor="#f0f0f0"><td><b>destination</b> (defined in <a class="el" href="classEvent.html">Event</a>)</td><td><a class="el" href="classEvent.html">Event</a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>Event</b>(std::string dest, std::string src, float ts) (defined in <a class="el" href="classEvent.html">Event</a>)</td><td><a class="el" href="classEvent.html">Event</a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>eventTime</b>() const (defined in <a class="el" href="classEvent.html">Event</a>)</td><td><a class="el" href="classEvent.html">Event</a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>getType</b>() override (defined in <a class="el" href="classUnackEvent.html">UnackEvent</a>)</td><td><a class="el" href="classUnackEvent.html">UnackEvent</a></td><td><code> [virtual]</code></td></tr>
<tr bgcolor="#f0f0f0"><td><b>packet</b> (defined in <a class="el" href="classUnackEvent.html">UnackEvent</a>)</td><td><a class="el" href="classUnackEvent.html">UnackEvent</a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>printEvent</b>() override (defined in <a class="el" href="classUnackEvent.html">UnackEvent</a>)</td><td><a class="el" href="classUnackEvent.html">UnackEvent</a></td><td><code> [virtual]</code></td></tr>
<tr bgcolor="#f0f0f0"><td><b>source</b> (defined in <a class="el" href="classEvent.html">Event</a>)</td><td><a class="el" href="classEvent.html">Event</a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>timestamp</b> (defined in <a class="el" href="classEvent.html">Event</a>)</td><td><a class="el" href="classEvent.html">Event</a></td><td><code> [protected]</code></td></tr>
<tr bgcolor="#f0f0f0"><td><b>UnackEvent</b>(std::shared_ptr< Packet > pkt, std::string dest, std::string src, float ts) (defined in <a class="el" href="classUnackEvent.html">UnackEvent</a>)</td><td><a class="el" href="classUnackEvent.html">UnackEvent</a></td><td></td></tr>
</table></div><!-- contents -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<hr class="footer"/><address class="footer"><small>
Generated on Mon Nov 18 2013 20:33:26 for NetSim by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.7.6.1
</small></address>
</body>
</html>
| {
"content_hash": "301d84b7bd437c5bca27271f3f64fd5d",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 412,
"avg_line_length": 51.228813559322035,
"alnum_prop": 0.6489660876757651,
"repo_name": "zatricion/NetSim",
"id": "d2dc5e8162516c8ae03a99dc5e56531e5ed653b1",
"size": "6045",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CS_143/docs/html/classUnackEvent-members.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4007"
},
{
"name": "C++",
"bytes": "100748"
},
{
"name": "CSS",
"bytes": "20048"
},
{
"name": "JavaScript",
"bytes": "25592"
},
{
"name": "Objective-C",
"bytes": "1536"
},
{
"name": "Perl",
"bytes": "2517"
},
{
"name": "TeX",
"bytes": "47000"
}
],
"symlink_target": ""
} |
"use strict";
var chai = require('chai'),
expect = chai.expect,
should = chai.should();
var paypal_classic_sdk = require('../../../');
require('../../configure');
var auth = paypal_classic_sdk.getModel("authorization");
describe('AuthorizationModel', function () {
describe('Construction', function () {
it('should return an object with the correct properties', function () {
//Check parameters
auth.getParameters().should.be.a('object');
//Check default parameters
auth.getDefaultParameters().should.be.a('object');
auth.getDefaultParameters().should.have.property('METHOD');
auth.getDefaultParameters().METHOD.should.equal("DoDirectPayment");
auth.getDefaultParameters().should.have.property('PAYMENTACTION');
auth.getDefaultParameters().PAYMENTACTION.should.equal("Authorization");
//Check validation parameters
auth.getValidationParameters().should.be.a('array');
auth.getValidationParameters().should.have.length(13);
});
});
describe('exchangeData', function () {
it('should populate the object parameters variable', function () {
var data = {
ACCT: "4716792779006088",
EXPDATE: "112018",
CVV2: "111",
AMT: "100",
IPADDRESS: "127.0.0.1",
FIRSTNAME: "Fred",
LASTNAME: "Flintstone",
STREET: "123 Bedrock",
CITY: "Omaha",
STATE: "NE",
ZIP: "68136",
COUNTRYCODE: "US",
METHOD: "Test",
PAYMENTACTION: "OK"
};
auth.exchangeData(data);
var params = auth.getParameters();
params.should.have.property('METHOD');
params.should.have.property('PAYMENTACTION');
params.should.have.property('ACCT');
params.should.have.property('EXPDATE');
//TRXTYPE and TENDER should be overridden by the model defaults
params.METHOD.should.equal("DoDirectPayment");
params.PAYMENTACTION.should.equal("Authorization");
params.AMT.should.equal("100");
params.EXPDATE.should.equal("112018");
});
});
describe('validateData', function () {
it('Should not throw', function () {
var data = {
ACCT: "4716792779006088",
EXPDATE: "112018",
CVV2: "111",
AMT: "100",
IPADDRESS: "127.0.0.1",
FIRSTNAME: "Fred",
LASTNAME: "Flintstone",
STREET: "123 Bedrock",
CITY: "Omaha",
STATE: "NE",
ZIP: "68136",
COUNTRYCODE: "US"
};
auth.exchangeData(data);
expect(auth.validateData).to.not.throw();
});
it('Should throw', function () {
var data = {
ACCT: "4716792779006088",
EXPDATE: "1118",
CVV2: "111"
};
auth.exchangeData(data);
expect(auth.validateData).to.throw('AMT: Required parameter for this transaction is undefined');
});
});
});
describe('ExecuteAuthorization', function () {
it('Should Return ACK Success', function (done) {
var data = {
ACCT: "4716792779006088",
EXPDATE: "112018",
CVV2: "111",
AMT: "100",
IPADDRESS: "127.0.0.1",
FIRSTNAME: "Fred",
LASTNAME: "Flintstone",
STREET: "123 Bedrock",
CITY: "Omaha",
STATE: "NE",
ZIP: "68136",
COUNTRYCODE: "US"
};
try {
auth.exchangeData(data);
auth.validateData();
paypal_classic_sdk.execute(auth.getParameters(), function (err, res) {
if (err) { done(err); }
res.response.decoded.ACK.should.equal("Success");
done();
});
}
catch (err)
{
console.log(err);
}
});
});
| {
"content_hash": "e72f045dcc60593c244e949f9fe4fd5a",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 108,
"avg_line_length": 32.02255639097744,
"alnum_prop": 0.4994130077482977,
"repo_name": "trainerbill/paypal-classic-sdk",
"id": "7d3ab94ce03ed18e81c06fad220fb0cdcee40b9a",
"size": "4259",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/models/DirectPayments/authorization.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "48656"
}
],
"symlink_target": ""
} |
navigator.serviceWorker.register('./serviceWorker.js')
.then((registration) => {
registration.pushManager.subscribe({
applicationServerKey: key, // derived from server's public key
userVisibleOnly: true
});
});
| {
"content_hash": "8532668611ded25c4d0ba0807ec0833c",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 67,
"avg_line_length": 32.142857142857146,
"alnum_prop": 0.72,
"repo_name": "msfrisbie/pjwd-src",
"id": "55d9fdc251b147dbd9a9e900c2fa2b7b444d2771",
"size": "225",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Chapter27Workers/ServiceWorkers/PushNotifications/SubscribingToPushEvents/SubscribingToPushEventsExample01.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "23266"
},
{
"name": "JavaScript",
"bytes": "430025"
},
{
"name": "Python",
"bytes": "4610"
}
],
"symlink_target": ""
} |
EdDSAPrivateKey::EdDSAPrivateKey(EVP_PKEY *key)
throw (AsymmetricKeyException) : PrivateKey(key)
{
AsymmetricKey::Algorithm algorithm = this->getAlgorithm();
if (algorithm != AsymmetricKey::EdDSA)
{
throw AsymmetricKeyException(AsymmetricKeyException::INVALID_TYPE, "EdDSAPrivateKey::EdDSAPrivateKey");
}
}
EdDSAPrivateKey::EdDSAPrivateKey(ByteArray &derEncoded)
throw (EncodeException, AsymmetricKeyException) : PrivateKey(derEncoded)
{
AsymmetricKey::Algorithm algorithm = this->getAlgorithm();
if (algorithm != AsymmetricKey::EdDSA)
{
throw AsymmetricKeyException(AsymmetricKeyException::INVALID_TYPE, "EdDSAPrivateKey::EdDSAPrivateKey");
}
}
EdDSAPrivateKey::EdDSAPrivateKey(std::string &pemEncoded)
throw (EncodeException, AsymmetricKeyException) : PrivateKey(pemEncoded)
{
AsymmetricKey::Algorithm algorithm = this->getAlgorithm();
if (algorithm != AsymmetricKey::EdDSA)
{
throw AsymmetricKeyException(AsymmetricKeyException::INVALID_TYPE, "EdDSAPrivateKey::EdDSAPrivateKey");
}
}
EdDSAPrivateKey::EdDSAPrivateKey(std::string &pemEncoded, ByteArray &passphrase)
throw (EncodeException, AsymmetricKeyException) : PrivateKey (pemEncoded, passphrase)
{
AsymmetricKey::Algorithm algorithm = this->getAlgorithm();
if (algorithm != AsymmetricKey::EdDSA)
{
throw AsymmetricKeyException(AsymmetricKeyException::INVALID_TYPE, "EdDSAPrivateKey::EdDSAPrivateKey");
}
}
EdDSAPrivateKey::~EdDSAPrivateKey()
{
}
| {
"content_hash": "17858f2210f522a427d25a3e8e4e6211",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 105,
"avg_line_length": 34.26190476190476,
"alnum_prop": 0.7894371091035441,
"repo_name": "LabSEC/libcryptosec",
"id": "0262453a8802d373906de15f1390ab2fa222c677",
"size": "1482",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/EdDSAPrivateKey.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "508"
},
{
"name": "C++",
"bytes": "746998"
},
{
"name": "Makefile",
"bytes": "4203"
}
],
"symlink_target": ""
} |
package cz.yetanotherview.webcamviewer.app.helper;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
public class EmptyRecyclerView extends RecyclerView {
@Nullable
private View emptyView;
public EmptyRecyclerView(Context context) {
super(context);
}
public EmptyRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EmptyRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setAdapter(@Nullable Adapter adapter) {
final Adapter oldAdapter = getAdapter();
if (oldAdapter != null) {
oldAdapter.unregisterAdapterDataObserver(observer);
}
if (adapter != null) {
adapter.registerAdapterDataObserver(observer);
}
super.setAdapter(adapter);
checkIfEmpty();
}
@NonNull
private final AdapterDataObserver observer = new AdapterDataObserver() {
@Override
public void onChanged() {
super.onChanged();
checkIfEmpty();
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
checkIfEmpty();
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
super.onItemRangeRemoved(positionStart, itemCount);
checkIfEmpty();
}
};
public void setEmptyView(@Nullable View emptyView) {
if (this.emptyView != null) {
this.emptyView.setVisibility(GONE);
}
this.emptyView = emptyView;
checkIfEmpty();
}
private void checkIfEmpty() {
if (emptyView == null || getAdapter() == null) {
return;
}
if (getAdapter().getItemCount() > 0) {
emptyView.setVisibility(GONE);
} else {
emptyView.setVisibility(VISIBLE);
}
}
} | {
"content_hash": "b342aaecd13c20967a1442df1e9fa2d0",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 81,
"avg_line_length": 26.975609756097562,
"alnum_prop": 0.6274864376130199,
"repo_name": "makbn/WebCamViewer",
"id": "365da054673efbea0236daebc8dc6fef43d7cdd0",
"size": "2212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/cz/yetanotherview/webcamviewer/app/helper/EmptyRecyclerView.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "531149"
}
],
"symlink_target": ""
} |
package org.hisp.dhis.preheat;
import javassist.util.proxy.ProxyFactory;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.dataelement.DataElementCategory;
import org.hisp.dhis.dataelement.DataElementCategoryCombo;
import org.hisp.dhis.dataelement.DataElementCategoryOption;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.user.User;
import org.hisp.dhis.user.UserCredentials;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
public class Preheat
{
private User user;
private Map<PreheatIdentifier, Map<Class<? extends IdentifiableObject>, Map<String, IdentifiableObject>>> map = new HashMap<>();
private Map<Class<? extends IdentifiableObject>, IdentifiableObject> defaults = new HashMap<>();
private Map<String, UserCredentials> usernames = new HashMap<>();
private Map<Class<? extends IdentifiableObject>, Map<String, Map<Object, String>>> uniquenessMap = new HashMap<>();
private Map<String, Period> periodMap = new HashMap<>();
private Map<String, PeriodType> periodTypeMap = new HashMap<>();
private Map<Class<? extends IdentifiableObject>, Set<String>> mandatoryAttributes = new HashMap<>();
private Map<Class<? extends IdentifiableObject>, Set<String>> uniqueAttributes = new HashMap<>();
private Map<Class<? extends IdentifiableObject>, Map<String, Map<String, String>>> uniqueAttributeValues = new HashMap<>();
public Preheat()
{
}
public User getUser()
{
return user;
}
public String getUsername()
{
return user != null ? user.getUsername() : "system-process";
}
public void setUser( User user )
{
this.user = user;
}
public <T extends IdentifiableObject> T get( PreheatIdentifier identifier, Class<? extends IdentifiableObject> klass, IdentifiableObject object )
{
return get( identifier, klass, identifier.getIdentifier( object ) );
}
@SuppressWarnings( "unchecked" )
public <T extends IdentifiableObject> T get( PreheatIdentifier identifier, Class<? extends IdentifiableObject> klass, String key )
{
if ( !containsKey( identifier, klass, key ) )
{
return null;
}
return (T) map.get( identifier ).get( klass ).get( key );
}
@SuppressWarnings( "unchecked" )
public <T extends IdentifiableObject> List<T> getAll( PreheatIdentifier identifier, List<T> keys )
{
List<T> objects = new ArrayList<>();
for ( T key : keys )
{
IdentifiableObject identifiableObject = get( identifier, key );
if ( identifiableObject != null )
{
objects.add( (T) identifiableObject );
}
}
return objects;
}
@SuppressWarnings( "unchecked" )
public <T extends IdentifiableObject> T get( PreheatIdentifier identifier, T object )
{
if ( object == null )
{
return null;
}
T reference = null;
Class<? extends IdentifiableObject> klass = (Class<? extends IdentifiableObject>) getRealClass( object.getClass() );
if ( PreheatIdentifier.UID == identifier || PreheatIdentifier.AUTO == identifier )
{
reference = get( PreheatIdentifier.UID, klass, object.getUid() );
}
if ( PreheatIdentifier.CODE == identifier || (reference == null && PreheatIdentifier.AUTO == identifier) )
{
reference = get( PreheatIdentifier.CODE, klass, object.getCode() );
}
return reference;
}
public boolean containsKey( PreheatIdentifier identifier, Class<? extends IdentifiableObject> klass, String key )
{
return !(isEmpty() || isEmpty( identifier ) || isEmpty( identifier, klass )) && map.get( identifier ).get( klass ).containsKey( key );
}
public boolean isEmpty()
{
return map.isEmpty();
}
public boolean isEmpty( PreheatIdentifier identifier )
{
return !map.containsKey( identifier ) || map.get( identifier ).isEmpty();
}
public boolean isEmpty( PreheatIdentifier identifier, Class<? extends IdentifiableObject> klass )
{
return isEmpty( identifier ) || !map.get( identifier ).containsKey( klass ) || map.get( identifier ).get( klass ).isEmpty();
}
@SuppressWarnings( "unchecked" )
public <T extends IdentifiableObject> Preheat put( PreheatIdentifier identifier, T object )
{
if ( object == null ) return this;
Class<? extends IdentifiableObject> klass = (Class<? extends IdentifiableObject>) getRealClass( object.getClass() );
if ( PreheatIdentifier.UID == identifier || PreheatIdentifier.AUTO == identifier )
{
if ( !map.containsKey( PreheatIdentifier.UID ) ) map.put( PreheatIdentifier.UID, new HashMap<>() );
if ( !map.get( PreheatIdentifier.UID ).containsKey( klass ) ) map.get( PreheatIdentifier.UID ).put( klass, new HashMap<>() );
if ( User.class.isAssignableFrom( klass ) )
{
if ( !map.get( PreheatIdentifier.UID ).containsKey( UserCredentials.class ) )
{
map.get( PreheatIdentifier.UID ).put( UserCredentials.class, new HashMap<>() );
}
User user = (User) object;
Map<String, IdentifiableObject> identifierMap = map.get( PreheatIdentifier.UID ).get( UserCredentials.class );
if ( !StringUtils.isEmpty( user.getUid() ) && !identifierMap.containsKey( user.getUid() ) )
{
identifierMap.put( user.getUid(), user.getUserCredentials() );
}
}
Map<String, IdentifiableObject> identifierMap = map.get( PreheatIdentifier.UID ).get( klass );
String key = PreheatIdentifier.UID.getIdentifier( object );
if ( !StringUtils.isEmpty( key ) && !identifierMap.containsKey( key ) )
{
identifierMap.put( key, object );
}
}
if ( PreheatIdentifier.CODE == identifier || PreheatIdentifier.AUTO == identifier )
{
if ( !map.containsKey( PreheatIdentifier.CODE ) ) map.put( PreheatIdentifier.CODE, new HashMap<>() );
if ( !map.get( PreheatIdentifier.CODE ).containsKey( klass ) ) map.get( PreheatIdentifier.CODE ).put( klass, new HashMap<>() );
if ( User.class.isAssignableFrom( klass ) )
{
if ( !map.get( PreheatIdentifier.CODE ).containsKey( UserCredentials.class ) )
{
map.get( PreheatIdentifier.CODE ).put( UserCredentials.class, new HashMap<>() );
}
User user = (User) object;
Map<String, IdentifiableObject> identifierMap = map.get( PreheatIdentifier.CODE ).get( UserCredentials.class );
identifierMap.put( user.getCode(), user.getUserCredentials() );
}
Map<String, IdentifiableObject> identifierMap = map.get( PreheatIdentifier.CODE ).get( klass );
String key = PreheatIdentifier.CODE.getIdentifier( object );
if ( !StringUtils.isEmpty( key ) && !identifierMap.containsKey( key ) )
{
identifierMap.put( key, object );
}
}
return this;
}
@SuppressWarnings( "unchecked" )
public <T extends IdentifiableObject> Preheat replace( PreheatIdentifier identifier, T object )
{
if ( object == null ) return this;
Class<? extends IdentifiableObject> klass = (Class<? extends IdentifiableObject>) getRealClass( object.getClass() );
if ( PreheatIdentifier.UID == identifier || PreheatIdentifier.AUTO == identifier )
{
if ( !map.containsKey( PreheatIdentifier.UID ) ) map.put( PreheatIdentifier.UID, new HashMap<>() );
if ( !map.get( PreheatIdentifier.UID ).containsKey( klass ) ) map.get( PreheatIdentifier.UID ).put( klass, new HashMap<>() );
if ( User.class.isAssignableFrom( klass ) )
{
if ( !map.get( PreheatIdentifier.UID ).containsKey( UserCredentials.class ) )
{
map.get( PreheatIdentifier.UID ).put( UserCredentials.class, new HashMap<>() );
}
User user = (User) object;
Map<String, IdentifiableObject> identifierMap = map.get( PreheatIdentifier.UID ).get( UserCredentials.class );
if ( !StringUtils.isEmpty( user.getUid() ) && !identifierMap.containsKey( user.getUid() ) )
{
identifierMap.put( user.getUid(), user.getUserCredentials() );
}
}
Map<String, IdentifiableObject> identifierMap = map.get( PreheatIdentifier.UID ).get( klass );
String key = PreheatIdentifier.UID.getIdentifier( object );
if ( !StringUtils.isEmpty( key ) )
{
identifierMap.put( key, object );
}
}
if ( PreheatIdentifier.CODE == identifier || PreheatIdentifier.AUTO == identifier )
{
if ( !map.containsKey( PreheatIdentifier.CODE ) ) map.put( PreheatIdentifier.CODE, new HashMap<>() );
if ( !map.get( PreheatIdentifier.CODE ).containsKey( klass ) ) map.get( PreheatIdentifier.CODE ).put( klass, new HashMap<>() );
if ( User.class.isAssignableFrom( klass ) )
{
if ( !map.get( PreheatIdentifier.CODE ).containsKey( UserCredentials.class ) )
{
map.get( PreheatIdentifier.CODE ).put( UserCredentials.class, new HashMap<>() );
}
User user = (User) object;
Map<String, IdentifiableObject> identifierMap = map.get( PreheatIdentifier.CODE ).get( UserCredentials.class );
identifierMap.put( user.getCode(), user.getUserCredentials() );
}
Map<String, IdentifiableObject> identifierMap = map.get( PreheatIdentifier.CODE ).get( klass );
String key = PreheatIdentifier.CODE.getIdentifier( object );
if ( !StringUtils.isEmpty( key ) )
{
identifierMap.put( key, object );
}
}
return this;
}
public <T extends IdentifiableObject> Preheat put( PreheatIdentifier identifier, Collection<T> objects )
{
for ( T object : objects )
{
if ( Preheat.isDefault( object ) ) continue;
put( identifier, object );
}
return this;
}
public Preheat remove( PreheatIdentifier identifier, Class<? extends IdentifiableObject> klass, String key )
{
if ( containsKey( identifier, klass, key ) )
{
map.get( identifier ).get( klass ).remove( key );
}
return this;
}
@SuppressWarnings( "unchecked" )
public Preheat remove( PreheatIdentifier identifier, IdentifiableObject object )
{
Class<? extends IdentifiableObject> klass = (Class<? extends IdentifiableObject>) getRealClass( object.getClass() );
if ( PreheatIdentifier.UID == identifier || PreheatIdentifier.AUTO == identifier )
{
String key = PreheatIdentifier.UID.getIdentifier( object );
if ( containsKey( PreheatIdentifier.UID, klass, key ) )
{
map.get( PreheatIdentifier.UID ).get( klass ).remove( key );
}
}
if ( PreheatIdentifier.CODE == identifier || PreheatIdentifier.AUTO == identifier )
{
String key = PreheatIdentifier.CODE.getIdentifier( object );
if ( containsKey( PreheatIdentifier.CODE, klass, key ) )
{
map.get( PreheatIdentifier.CODE ).get( klass ).remove( key );
}
}
return this;
}
public Preheat remove( PreheatIdentifier identifier, Class<? extends IdentifiableObject> klass, Collection<String> keys )
{
for ( String key : keys )
{
remove( identifier, klass, key );
}
return this;
}
public Map<PreheatIdentifier, Map<Class<? extends IdentifiableObject>, Map<String, IdentifiableObject>>> getMap()
{
return map;
}
public Map<Class<? extends IdentifiableObject>, IdentifiableObject> getDefaults()
{
return defaults;
}
public void setDefaults( Map<Class<? extends IdentifiableObject>, IdentifiableObject> defaults )
{
this.defaults = defaults;
}
public Map<String, UserCredentials> getUsernames()
{
return usernames;
}
public void setUsernames( Map<String, UserCredentials> usernames )
{
this.usernames = usernames;
}
public static boolean isDefaultClass( IdentifiableObject object )
{
return object != null && isDefaultClass( getRealClass( object.getClass() ) );
}
public static boolean isDefaultClass( Class<?> klass )
{
return DataElementCategory.class.isAssignableFrom( klass ) || DataElementCategoryOption.class.isAssignableFrom( klass )
|| DataElementCategoryCombo.class.isAssignableFrom( klass );
}
public static boolean isDefault( IdentifiableObject object )
{
return isDefaultClass( object ) && "default".equals( object.getName() );
}
public static Class<?> getRealClass( Class<?> klass )
{
if ( ProxyFactory.isProxyClass( klass ) )
{
klass = klass.getSuperclass();
}
return klass;
}
public void setUniquenessMap( Map<Class<? extends IdentifiableObject>, Map<String, Map<Object, String>>> uniquenessMap )
{
this.uniquenessMap = uniquenessMap;
}
public Map<Class<? extends IdentifiableObject>, Map<String, Map<Object, String>>> getUniquenessMap()
{
return uniquenessMap;
}
public Map<String, Period> getPeriodMap()
{
return periodMap;
}
public void setPeriodMap( Map<String, Period> periodMap )
{
this.periodMap = periodMap;
}
public Map<String, PeriodType> getPeriodTypeMap()
{
return periodTypeMap;
}
public void setPeriodTypeMap( Map<String, PeriodType> periodTypeMap )
{
this.periodTypeMap = periodTypeMap;
}
public Map<Class<? extends IdentifiableObject>, Set<String>> getMandatoryAttributes()
{
return mandatoryAttributes;
}
public void setMandatoryAttributes( Map<Class<? extends IdentifiableObject>, Set<String>> mandatoryAttributes )
{
this.mandatoryAttributes = mandatoryAttributes;
}
public Map<Class<? extends IdentifiableObject>, Set<String>> getUniqueAttributes()
{
return uniqueAttributes;
}
public void setUniqueAttributes( Map<Class<? extends IdentifiableObject>, Set<String>> uniqueAttributes )
{
this.uniqueAttributes = uniqueAttributes;
}
public Map<Class<? extends IdentifiableObject>, Map<String, Map<String, String>>> getUniqueAttributeValues()
{
return uniqueAttributeValues;
}
public void setUniqueAttributeValues( Map<Class<? extends IdentifiableObject>, Map<String, Map<String, String>>> uniqueAttributeValues )
{
this.uniqueAttributeValues = uniqueAttributeValues;
}
}
| {
"content_hash": "bdc4c9d4d48817e93a0bc9fe204f1a0b",
"timestamp": "",
"source": "github",
"line_count": 451,
"max_line_length": 149,
"avg_line_length": 34.61419068736142,
"alnum_prop": 0.6188584972135033,
"repo_name": "mortenoh/dhis2-core",
"id": "bfd557cf74340b25954dc8cb28d0be28a615c910",
"size": "17167",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dhis-2/dhis-api/src/main/java/org/hisp/dhis/preheat/Preheat.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "292397"
},
{
"name": "Game Maker Language",
"bytes": "20893"
},
{
"name": "HTML",
"bytes": "75324"
},
{
"name": "Java",
"bytes": "16179212"
},
{
"name": "JavaScript",
"bytes": "3218103"
},
{
"name": "Ruby",
"bytes": "1011"
},
{
"name": "Shell",
"bytes": "394"
},
{
"name": "XSLT",
"bytes": "8281"
}
],
"symlink_target": ""
} |
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="lib/simpleRequire.js"></script>
<script src="lib/config.js"></script>
<script src="lib/jquery.min.js"></script>
<script src="lib/facePrint.js"></script>
<script src="lib/testHelper.js"></script>
<link rel="stylesheet" href="lib/reset.css">
</head>
<body>
<style>
html, body, #main {
width: 100%;
height: 100%;
margin: 0;
}
.snapshot-rendered {
position: absolute;
right: 10px;
top: 10px;
width: 200px;
height: 180px;
background: #fff;
border: 5px solid rgba(0,0,0,0.5);
z-index: 100;
}
.snapshot-finished {
position: absolute;
right: 10px;
bottom: 30px;
width: 200px;
height: 180px;
background: #fff;
border: 5px solid rgba(0,0,0,0.5);
z-index: 100;
}
.snapshot-info {
position: absolute;
right: 10px;
width: 200px;
text-align: center;
background: #333;
color: #fff;
padding: 2px 5px;
font-size: 12px;
z-index: 100;
}
.snapshot-info span {
color: yellow;
}
.block-box {
position: relative;
}
</style>
<div class="block-box">
<div id="main0"></div>
</div>
<div class="block-box">
<div id="main1"></div>
</div>
<div class="block-box">
<div id="main2"></div>
</div>
<script>
function enableSnapshot(chart, domId) {
var chartDom = testHelper.getDom(domId);
var snapshotRenderedDom = document.createElement('img');
snapshotRenderedDom.className = 'snapshot-rendered';
chartDom.parentNode.appendChild(snapshotRenderedDom);
var snapshotFinishedDom = document.createElement('img');
snapshotFinishedDom.className = 'snapshot-finished';
chartDom.parentNode.appendChild(snapshotFinishedDom);
var renderedInfoDom = document.createElement('div');
renderedInfoDom.className = 'snapshot-info';
chartDom.parentNode.appendChild(renderedInfoDom);
renderedInfoDom.style.top = snapshotRenderedDom.offsetTop + snapshotRenderedDom.offsetHeight + 'px';
var finishedInfoDom = document.createElement('div');
finishedInfoDom.className = 'snapshot-info';
chartDom.parentNode.appendChild(finishedInfoDom);
finishedInfoDom.style.top = snapshotFinishedDom.offsetTop + snapshotFinishedDom.offsetHeight + 'px';
chart.on('rendered', function () {
var url = chart.getDataURL();
snapshotRenderedDom.src = url;
renderedInfoDom.innerHTML = 'rendered triggered at <span>' + +new Date() + '</span>';
});
chart.on('finished', function () {
var url = chart.getDataURL();
snapshotFinishedDom.src = url;
finishedInfoDom.innerHTML = 'finished triggered at <span>' + +new Date() + '</span>';
});
}
</script>
<script>
var chunkMax = 4;
var chunkCount = 0;
function genData1(len, offset) {
var lngRange = [-10.781327, 131.48];
var latRange = [18.252847, 52.33];
var arr = new Float32Array(len * 2);
var off = 0;
for (var i = 0; i < len; i++) {
var x = +Math.random() * 10;
var y = +Math.sin(x) - x * (len % 2 ? 0.1 : -0.1) * Math.random() + (offset || 0) / 10;
arr[off++] = x;
arr[off++] = y;
}
return arr;
}
require(['echarts'], function (echarts) {
var option = {
tooltip: {},
toolbox: {
left: 'center',
feature: {
dataZoom: {}
}
},
legend: {
orient: 'vertical',
left: 'left',
data: ['pm2.5' /* ,'pm10' */]
},
xAxis: [{
}],
yAxis: [{
}],
dataZoom: [{
type: 'inside'
}, {
type: 'slider'
}],
animation: false,
series : [{
name: 'pm2.5',
type: 'scatter',
data: genData1(1e5),
dimensions: ['x', 'y'],
symbolSize: 3,
itemStyle: {
color: '#128de3',
opacity: 0.4
},
large: true,
largeThreshold: 500,
progressive: 500
}]
};
var chart = testHelper.create(echarts, 'main0', {
title: [
'finished should be triggered, and not repeatly',
'finished should not triggered before real finished'
],
autoResize: false,
option: option
});
chart && enableSnapshot(chart, 'main0');
});
</script>
<script>
require(['echarts'], function (echarts) {
var option = {
legend: {},
animationDuration: 4000,
animationDurationUpdate: 5500,
dataset: {
source: [
{name: 'a', value: 123},
{name: 'b', value: 456},
{name: 'should be selected', value: 789, selected: true}
]
},
series: {
type: 'pie',
selectedMode: 'multiply'
}
};
var chart = testHelper.create(echarts, 'main1', {
title: 'Check animation normal. \nfinished should be triggered, and not repeatly',
option: option
// info: option
});
chart && enableSnapshot(chart, 'main1');
});
</script>
<script>
require(['echarts'], function (echarts) {
var option = {
legend: {},
tooltip: {},
xAxis: {},
yAxis: {},
dataset: [{
source: [
['2012', null, '2013', null, '2014', 'amount'],
[41.1, 2585, 30.4, 2473, 65.1, 3418],
[86.5, 2316, 92.1, 3255, 85.7, 2485],
[24.1, 1532, 67.2, 1452, 79.5, 4689],
[55.2, 5312, 67.1, 3266, 69.2, 1354]
]
}],
series: [{
type: 'scatter'
}, {
type: 'scatter'
}, {
type: 'scatter'
}]
};
var chart = testHelper.create(echarts, 'main2', {
title: 'setOption delay',
option: option,
lazyUpdate: true
});
chart && enableSnapshot(chart, 'main2');
});
</script>
</body>
</html> | {
"content_hash": "933b26ebc14e5437870decf4b711bc3a",
"timestamp": "",
"source": "github",
"line_count": 289,
"max_line_length": 116,
"avg_line_length": 32.24567474048443,
"alnum_prop": 0.4146367636012448,
"repo_name": "apache/incubator-echarts",
"id": "77792431de600d26d2344b183657f50fd554f5bb",
"size": "9319",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/finished.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "13440"
},
{
"name": "HTML",
"bytes": "4074349"
},
{
"name": "JavaScript",
"bytes": "5201227"
}
],
"symlink_target": ""
} |
'use strict';
var
os = require('os'),
fs = require('fs'),
_ = require('underscore');
var MongoConfigParser = function() {
// default config
var env = {
'host' : 'localhost',
'port' : 27017,
'database' : 'test' // default mongo DB
};
/**
* Environment getter
*
* Returns the apppropiate environment file (a json, so returned as an obj).
* If there's a file called {yourHostName}.json it will be returned.
* If not found, it will search for a file called default.json.
* If that file is not found neuiither, it will return false.
*
* @param {String} envDir environment directory that contains the env. config. files
* @return {Object} environment obj. with its properties (host, port, user, pass and dbName)
* or false if not found
*/
var getEnvObj = function(envDir) {
if(!envDir || !fs.existsSync(envDir)) {
return false;
}
var
base = envDir + '/',
ext = '.json',
customEnvFilePath = base + os.hostname().toLowerCase() + ext,
defaultEnvFilePath = base + 'default' + ext,
data;
/* istanbul ignore else */
if(fs.existsSync(customEnvFilePath)) {
data = fs.readFileSync(customEnvFilePath, 'utf8');
} else if(fs.existsSync(defaultEnvFilePath)) {
data = fs.readFileSync(defaultEnvFilePath, 'utf8');
}
return data ? JSON.parse(data) : false;
};
/**
* Environment extender: merges the defaults with the propperties of the supplied obj
* @param {Object} envObj
*/
var setEnvObj = function(envObj) {
if(envObj) {
env = _.extend(env, envObj);
}
};
return {
/**
* Environment setter
* @param {Object} envObj obj. with the following keys
* (all of them are optional):
* "host" : string, mongo host name
* "port" : int, mongo port
* "user" : string, mongo user name
* "password" : string, mongo password
* "database" : string, mongo db name
*/
setEnv : function(envObj) {
setEnvObj(envObj);
// make the method chainable
return this;
},
/**
* Environment getter
* @return {Object} obj. with the following keys
* (if set):
* "host" : string, mongo host name
* "port" : int, mongo port
* "user" : string, mongo user name
* "password" : string, mongo password
* "database" : string, mongo db name
*/
getEnv : function() {
return env;
},
/**
* Environment setter (set the env. dir and it will load the appropiate file)
* @param {string} dir environment directory path
*/
setEnvDir : function(dir) {
setEnvObj( getEnvObj(dir) );
// make the method chainable
return this;
},
/**
* Returns the mongo conn. string using the environment if deffined or using default values
* @return {String} mongo connection string
*/
getConnectionString : function() {
var ret;
// set the proto
ret = 'mongodb://';
// set the host
ret += env.host;
// set the port
ret += ':' + env.port;
// set the database name
ret += '/' + env.database;
return ret;
},
/**
* Returns the mongo connection options (currently only the user and password)
*
* The user and password are passed to mongoose independently from the connection
* string so they can contain weird characters like '@' that would break the
* connection string
*
* @return {Object}
*/
getConnectionOptions : function() {
var ret = {};
// set the user/password
if(env.user) {
ret.user = env.user;
if(env.password) {
ret.pass = env.password;
}
}
return ret;
}
};
};
module.exports = MongoConfigParser;
| {
"content_hash": "972cad6361893b3addc56a194a47f56f",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 101,
"avg_line_length": 25.925465838509318,
"alnum_prop": 0.5371346430282703,
"repo_name": "mosaiqo/frontend-devServer",
"id": "ace83d1b5cf7e4ec1337653c9963ea572a32ba74",
"size": "4174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/lib/mongoConfigParser.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "7722"
},
{
"name": "JavaScript",
"bytes": "264096"
}
],
"symlink_target": ""
} |
color_code_mode = 1 # 0 == Disabled, 1 == Enabled, 2 == Color Codes Only, 3 == Mixed
max_blocks = 1000
max_blocks_per_signature = 1000
min_block_area = 20
# Pan Servo
s0_lower_limit = 1000 # Servo pulse width lower limit in microseconds.
s0_upper_limit = 2000 # Servo pulse width upper limit in microseconds.
# Tilt Servo
s1_lower_limit = 1000 # Servo pulse width lower limit in microseconds.
s1_upper_limit = 2000 # Servo pulse width upper limit in microseconds.
analog_out_enable = False # P6 -> Analog Out (0v - 3.3v).
analog_out_mode = 0 # 0 == x position of largest blob - 1 == y position of largest blob
# Parameter 0 - L Min.
# Parameter 1 - L Max.
# Parameter 2 - A Min.
# Parameter 3 - A Max.
# Parameter 4 - B Min.
# Parameter 5 - B Max.
# Parameter 6 - Is Color Code Threshold? (True/False).
# Parameter 7 - Enable Threshold? (True/False).
lab_color_thresholds = [(0, 100, 40, 127, -128, 127, True, True), # Generic Red Threshold
(0, 100, -128, -10, -128, 127, True, True), # Generic Green Threshold
(0, 0, 0, 0, 0, 0, False, False),
(0, 0, 0, 0, 0, 0, False, False),
(0, 0, 0, 0, 0, 0, False, False),
(0, 0, 0, 0, 0, 0, False, False),
(0, 0, 0, 0, 0, 0, False, False)]
fb_pixels_threshold = 500 # minimum number of pixels that must be in a blob
fb_merge_margin = 5 # how close pixel wise blobs can be before merging
##############################################################################
e_lab_color_thresholds = [] # enabled thresholds
e_lab_color_code = [] # enabled color code
e_lab_color_signatures = [] # original enabled threshold indexes
for i in range(len(lab_color_thresholds)):
if lab_color_thresholds[i][7]:
e_lab_color_thresholds.append(lab_color_thresholds[i][0:6])
e_lab_color_code.append(lab_color_thresholds[i][6])
e_lab_color_signatures.append(i + 1)
import image, math, pyb, sensor, struct, time
# Camera Setup
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)
sensor.set_auto_gain(False)
# LED Setup
red_led = pyb.LED(1)
green_led = pyb.LED(2)
blue_led = pyb.LED(3)
red_led.off()
green_led.off()
blue_led.off()
# DAC Setup
dac = pyb.DAC("P6") if analog_out_enable else None
if dac:
dac.write(0)
# Servo Setup
min_s0_limit = min(s0_lower_limit, s0_upper_limit)
max_s0_limit = max(s0_lower_limit, s0_upper_limit)
min_s1_limit = min(s1_lower_limit, s1_upper_limit)
max_s1_limit = max(s1_lower_limit, s1_upper_limit)
s0_pan = pyb.Servo(1) # P7
s1_tilt = pyb.Servo(2) # P8
s0_pan.pulse_width(int((max_s0_limit - min_s0_limit) // 2)) # center
s1_tilt.pulse_width(int((max_s1_limit - min_s1_limit) // 2)) # center
s0_pan_conversion_factor = (max_s0_limit - min_s0_limit) / 1000
s1_tilt_conversion_factor = (max_s1_limit - min_s1_limit) / 1000
def s0_pan_position(value):
s0_pan.pulse_width(round(s0_lower_limit + (max(min(value, 1000), 0) * s0_pan_conversion_factor)))
def s1_tilt_position(value):
s1_tilt.pulse_width(round(s1_lower_limit + (max(min(value, 1000), 0) * s1_tilt_conversion_factor)))
# Link Setup
bus = pyb.SPI(2, pyb.SPI.SLAVE, polarity = 0, phase = 0, bits = 16)
while(True):
try:
sync_bytes = bus.recv(2, timeout = 10)
if((sync_bytes[0] == 0x00) and (sync_bytes[1] == 0x5A)):
break
except OSError as error:
pass
bus.deinit()
bus.init(pyb.SPI.SLAVE, polarity = 0, phase = 0, bits = 16)
def write(data):
max_exceptions = 10
loop = True
while(loop):
try:
bus.send(data, timeout = 10)
loop = False
except OSError as error:
if(max_exceptions <= 0):
return
max_exceptions -= 1
def available():
return 0 # Not implemented as there is no way for the us to be ready to receive the data.
def read_byte():
return 0 # Not implemented as there is no way for the us to be ready to receive the data.
# Helper Stuff
def checksum(data):
checksum = 0
for i in range(0, len(data), 2):
checksum += ((data[i+1] & 0xFF) << 8) | ((data[i+0] & 0xFF) << 0)
return checksum & 0xFFFF
def get_normal_signature(code):
for i in range(len(e_lab_color_signatures)):
if code & (1 << i):
return e_lab_color_signatures[i]
return 0
def to_normal_object_block_format(blob):
temp = struct.pack("<hhhhh", get_normal_signature(blob.code()), blob.cx(), blob.cy(), blob.w(), blob.h())
return struct.pack("<hh10s", 0xAA55, checksum(temp), temp)
def get_color_code_signature(code):
color_code_list = []
for i in range(len(e_lab_color_signatures)):
if code & (1 << i):
color_code_list.append(e_lab_color_signatures[i])
octal = 0
color_code_list_len = len(color_code_list) - 1
for i in range(color_code_list_len + 1):
octal += color_code_list[i] << (3 * (color_code_list_len - i))
return octal
def to_color_code_object_block_format(blob):
angle = int((blob.rotation() * 180) // math.pi)
temp = struct.pack("<hhhhhh", get_color_code_signature(blob.code()), blob.cx(), blob.cy(), blob.w(), blob.h(), angle)
return struct.pack("<hh12s", 0xAA56, checksum(temp), temp)
def get_signature(blob, bits):
return get_normal_signature(blob.code()) if (bits == 1) else get_color_code_signature(blob.code())
def to_object_block_format(blob, bits):
return to_normal_object_block_format(blob) if (bits == 1) else to_color_code_object_block_format(blob)
# FSM Code
fsm_state = 0
last_byte = 0
FSM_STATE_NONE = 0
FSM_STATE_ZERO = 1
FSM_STATE_SERVO_CONTROL_0 = 2
FSM_STATE_SERVO_CONTROL_1 = 3
FSM_STATE_SERVO_CONTROL_2 = 4
FSM_STATE_SERVO_CONTROL_3 = 5
FSM_STATE_CAMERA_CONTROL = 6
FSM_STATE_LED_CONTROL_0 = 7
FSM_STATE_LED_CONTROL_1 = 8
FSM_STATE_LED_CONTROL_2 = 9
def parse_byte(byte):
global fsm_state
global last_byte
if fsm_state == FSM_STATE_NONE:
if byte == 0x00: fsm_state = FSM_STATE_ZERO
else: fsm_state = FSM_STATE_NONE
elif fsm_state == FSM_STATE_ZERO:
if byte == 0xFF: fsm_state = FSM_STATE_SERVO_CONTROL_0
elif byte == 0xFE: fsm_state = FSM_STATE_CAMERA_CONTROL
elif byte == 0xFD: fsm_state = FSM_STATE_LED_CONTROL_0
else: fsm_state = FSM_STATE_NONE
elif fsm_state == FSM_STATE_SERVO_CONTROL_0:
fsm_state = FSM_STATE_SERVO_CONTROL_1
elif fsm_state == FSM_STATE_SERVO_CONTROL_1:
fsm_state = FSM_STATE_SERVO_CONTROL_2
s0_pan_position(((byte & 0xFF) << 8) | ((last_byte & 0xFF) << 0))
elif fsm_state == FSM_STATE_SERVO_CONTROL_2:
fsm_state = FSM_STATE_SERVO_CONTROL_3
elif fsm_state == FSM_STATE_SERVO_CONTROL_3:
fsm_state = FSM_STATE_NONE
s1_tilt_position(((byte & 0xFF) << 8) | ((last_byte & 0xFF) << 0))
elif fsm_state == FSM_STATE_CAMERA_CONTROL:
fsm_state = FSM_STATE_NONE
# Ignore...
elif fsm_state == FSM_STATE_LED_CONTROL_0:
fsm_state = FSM_STATE_LED_CONTROL_1
if byte & 0x80: red_led.on()
else: red_led.off()
elif fsm_state == FSM_STATE_LED_CONTROL_1:
fsm_state = FSM_STATE_LED_CONTROL_2
if byte & 0x80: green_led.on()
else: green_led.off()
elif fsm_state == FSM_STATE_LED_CONTROL_2:
fsm_state = FSM_STATE_NONE
if byte & 0x80: blue_led.on()
else: blue_led.off()
last_byte = byte
# Main Loop
pri_color_code_mode = color_code_mode % 4
def bits_set(code):
count = 0
for i in range(7):
count += 1 if (code & (1 << i)) else 0
return count
def color_code(code):
for i in range(len(e_lab_color_code)):
if code & (1 << i):
return e_lab_color_code[i]
return False
def fb_merge_cb(blob0, blob1):
if not pri_color_code_mode:
return blob0.code() == blob1.code()
else:
return True if (blob0.code() == blob1.code()) else (color_code(blob0.code()) and color_code(blob1.code()))
def blob_filter(blob):
if(pri_color_code_mode == 0):
return True
elif(pri_color_code_mode == 1): # color codes with two or more colors or regular
return (bits_set(blob.code()) > 1) or (not color_code(blob.code()))
elif(pri_color_code_mode == 2): # only color codes with two or more colors
return (bits_set(blob.code()) > 1)
elif(pri_color_code_mode == 3):
return True
clock = time.clock()
while(True):
clock.tick()
img = sensor.snapshot()
blobs = list(filter(blob_filter, img.find_blobs(e_lab_color_thresholds, area_threshold = min_block_area, pixels_threshold = fb_pixels_threshold, merge = True, margin = fb_merge_margin, merge_cb = fb_merge_cb)))
# Transmit Blobs #
if blobs and (max_blocks > 0) and (max_blocks_per_signature > 0): # new frame
dat_buf = struct.pack("<h", 0xAA55)
sig_map = {}
first_b = False
for blob in sorted(blobs, key = lambda x: x.area(), reverse = True)[0:max_blocks]:
bits = bits_set(blob.code())
sign = get_signature(blob, bits)
if not sign in sig_map:
sig_map[sign] = 1
else:
sig_map[sign] += 1
if sig_map[sign] <= max_blocks_per_signature:
dat_buf += to_object_block_format(blob, bits)
img.draw_rectangle(blob.rect())
img.draw_cross(blob.cx(), blob.cy())
if dac and not first_b:
x_scale = 255 / (img.width()-1)
y_scale = 255 / (img.height()-1)
dac.write(round((blob.y() * y_scale) if analog_out_mode else (blob.x() * x_scale)))
first_b = True
dat_buf += struct.pack("<h", 0x0000)
write(dat_buf) # write all data in one packet...
else: # nothing found
write(struct.pack("<h", 0x0000))
if dac:
dac.write(0)
# Parse Commands #
for i in range(available()):
parse_byte(read_byte())
num_blobs = min(len(blobs), max_blocks)
print("%d blob(s) found - FPS %f" % (num_blobs, clock.fps()))
| {
"content_hash": "82a59215a733efa0e0fbd2013288b0c8",
"timestamp": "",
"source": "github",
"line_count": 315,
"max_line_length": 214,
"avg_line_length": 32.31111111111111,
"alnum_prop": 0.6024759284731774,
"repo_name": "iabdalkader/openmv",
"id": "50c94e32a3483caf2aa39c4925d941e07ea913b0",
"size": "10917",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/examples/Arduino/Portenta-H7/17-Pixy-Emulation/pixy_spi_emulation.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "569030"
},
{
"name": "C",
"bytes": "100413378"
},
{
"name": "C++",
"bytes": "97780"
},
{
"name": "CMake",
"bytes": "10173"
},
{
"name": "Dockerfile",
"bytes": "874"
},
{
"name": "Makefile",
"bytes": "72669"
},
{
"name": "Python",
"bytes": "1197447"
},
{
"name": "Shell",
"bytes": "3220"
}
],
"symlink_target": ""
} |
<?php
namespace Cake\Test\TestCase\Error;
use Cake\Controller\Controller;
use Cake\Core\App;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\Error;
use Cake\Error\ErrorHandler;
use Cake\Error\ExceptionRenderer;
use Cake\Log\Log;
use Cake\Network\Exception\ForbiddenException;
use Cake\Network\Exception\NotFoundException;
use Cake\Network\Request;
use Cake\Network\Response;
use Cake\Routing\Router;
use Cake\TestSuite\TestCase;
/**
* Testing stub.
*/
class TestErrorHandler extends ErrorHandler
{
/**
* Access the response used.
*
* @var \Cake\Network\Response
*/
public $response;
/**
* Stub output clearing in tests.
*
* @return void
*/
protected function _clearOutput()
{
// noop
}
/**
* Stub sending responses
*
* @return void
*/
protected function _sendResponse($response)
{
$this->response = $response;
}
}
/**
* ErrorHandlerTest class
*/
class ErrorHandlerTest extends TestCase
{
protected $_restoreError = false;
/**
* setup create a request object to get out of router later.
*
* @return void
*/
public function setUp()
{
parent::setUp();
Router::reload();
$request = new Request();
$request->base = '';
Router::setRequestInfo($request);
Configure::write('debug', true);
$this->_logger = $this->getMock('Psr\Log\LoggerInterface');
Log::reset();
Log::config('error_test', [
'engine' => $this->_logger
]);
}
/**
* tearDown
*
* @return void
*/
public function tearDown()
{
parent::tearDown();
Log::reset();
if ($this->_restoreError) {
restore_error_handler();
restore_exception_handler();
}
}
/**
* test error handling when debug is on, an error should be printed from Debugger.
*
* @return void
*/
public function testHandleErrorDebugOn()
{
$errorHandler = new ErrorHandler();
$errorHandler->register();
$this->_restoreError = true;
ob_start();
$wrong = $wrong + 1;
$result = ob_get_clean();
$this->assertRegExp('/<pre class="cake-error">/', $result);
$this->assertRegExp('/<b>Notice<\/b>/', $result);
$this->assertRegExp('/variable:\s+wrong/', $result);
}
/**
* provides errors for mapping tests.
*
* @return void
*/
public static function errorProvider()
{
return [
[E_USER_NOTICE, 'Notice'],
[E_USER_WARNING, 'Warning'],
];
}
/**
* test error mappings
*
* @dataProvider errorProvider
* @return void
*/
public function testErrorMapping($error, $expected)
{
$errorHandler = new ErrorHandler();
$errorHandler->register();
$this->_restoreError = true;
ob_start();
trigger_error('Test error', $error);
$result = ob_get_clean();
$this->assertContains('<b>' . $expected . '</b>', $result);
}
/**
* test error prepended by @
*
* @return void
*/
public function testErrorSuppressed()
{
$errorHandler = new ErrorHandler();
$errorHandler->register();
$this->_restoreError = true;
ob_start();
//@codingStandardsIgnoreStart
@include 'invalid.file';
//@codingStandardsIgnoreEnd
$result = ob_get_clean();
$this->assertTrue(empty($result));
}
/**
* Test that errors go into Cake Log when debug = 0.
*
* @return void
*/
public function testHandleErrorDebugOff()
{
Configure::write('debug', false);
$errorHandler = new ErrorHandler();
$errorHandler->register();
$this->_restoreError = true;
$this->_logger->expects($this->once())
->method('log')
->with(
$this->matchesRegularExpression('(notice|debug)'),
'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ + 3) . ']' . "\n\n"
);
$out = $out + 1;
}
/**
* Test that errors going into Cake Log include traces.
*
* @return void
*/
public function testHandleErrorLoggingTrace()
{
Configure::write('debug', false);
$errorHandler = new ErrorHandler(['trace' => true]);
$errorHandler->register();
$this->_restoreError = true;
$this->_logger->expects($this->once())
->method('log')
->with(
$this->matchesRegularExpression('(notice|debug)'),
$this->logicalAnd(
$this->stringContains('Notice (8): Undefined variable: out in '),
$this->stringContains('Trace:'),
$this->stringContains(__NAMESPACE__ . '\ErrorHandlerTest::testHandleErrorLoggingTrace()')
)
);
$out = $out + 1;
}
/**
* test handleException generating a page.
*
* @return void
*/
public function testHandleException()
{
$error = new NotFoundException('Kaboom!');
$errorHandler = new TestErrorHandler();
$errorHandler->handleException($error);
$this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
}
/**
* test handleException generating log.
*
* @return void
*/
public function testHandleExceptionLog()
{
$errorHandler = new TestErrorHandler([
'log' => true,
]);
$error = new NotFoundException('Kaboom!');
$this->_logger->expects($this->once())
->method('log')
->with('error', $this->logicalAnd(
$this->stringContains('[Cake\Network\Exception\NotFoundException] Kaboom!'),
$this->stringContains('ErrorHandlerTest->testHandleExceptionLog')
));
$errorHandler->handleException($error);
$this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
}
/**
* test handleException generating log.
*
* @return void
*/
public function testHandleExceptionLogSkipping()
{
$notFound = new NotFoundException('Kaboom!');
$forbidden = new ForbiddenException('Fooled you!');
$this->_logger->expects($this->once())
->method('log')
->with(
'error',
$this->stringContains('[Cake\Network\Exception\ForbiddenException] Fooled you!')
);
$errorHandler = new TestErrorHandler([
'log' => true,
'skipLog' => ['Cake\Network\Exception\NotFoundException'],
]);
$errorHandler->handleException($notFound);
$this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
$errorHandler->handleException($forbidden);
$this->assertContains('Fooled you!', $errorHandler->response->body(), 'message missing.');
}
/**
* tests it is possible to load a plugin exception renderer
*
* @return void
*/
public function testLoadPluginHandler()
{
Plugin::load('TestPlugin');
$errorHandler = new TestErrorHandler([
'exceptionRenderer' => 'TestPlugin.TestPluginExceptionRenderer',
]);
$error = new NotFoundException('Kaboom!');
$errorHandler->handleException($error);
$result = $errorHandler->response;
$this->assertEquals('Rendered by test plugin', $result);
}
/**
* test handleFatalError generating a page.
*
* These tests start two buffers as handleFatalError blows the outer one up.
*
* @return void
*/
public function testHandleFatalErrorPage()
{
$line = __LINE__;
$errorHandler = new TestErrorHandler();
Configure::write('debug', true);
$errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
$result = $errorHandler->response->body();
$this->assertContains('Something wrong', $result, 'message missing.');
$this->assertContains(__FILE__, $result, 'filename missing.');
$this->assertContains((string)$line, $result, 'line missing.');
Configure::write('debug', false);
$errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
$result = $errorHandler->response->body();
$this->assertNotContains('Something wrong', $result, 'message must not appear.');
$this->assertNotContains(__FILE__, $result, 'filename must not appear.');
$this->assertContains('An Internal Error Has Occurred', $result);
}
/**
* test handleFatalError generating log.
*
* @return void
*/
public function testHandleFatalErrorLog()
{
$this->_logger->expects($this->at(0))
->method('log')
->with('error', $this->logicalAnd(
$this->stringContains(__FILE__ . ', line ' . (__LINE__ + 9)),
$this->stringContains('Fatal Error (1)'),
$this->stringContains('Something wrong')
));
$this->_logger->expects($this->at(1))
->method('log')
->with('error', $this->stringContains('[Cake\Error\FatalErrorException] Something wrong'));
$errorHandler = new TestErrorHandler(['log' => true]);
$errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, __LINE__);
}
}
| {
"content_hash": "b569224a64b8ddfdd3f16347a5340ca4",
"timestamp": "",
"source": "github",
"line_count": 353,
"max_line_length": 113,
"avg_line_length": 27.376770538243626,
"alnum_prop": 0.5579470198675497,
"repo_name": "digvijay3012/sndtrack",
"id": "baa7c07f7ce75a8ecc3f2e2803592b52431198a6",
"size": "10295",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "html/dev/vendor/cakephp/cakephp/tests/TestCase/Error/ErrorHandlerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "97232"
},
{
"name": "ApacheConf",
"bytes": "1651"
},
{
"name": "Batchfile",
"bytes": "1910"
},
{
"name": "CSS",
"bytes": "858495"
},
{
"name": "HTML",
"bytes": "9569505"
},
{
"name": "JavaScript",
"bytes": "2061591"
},
{
"name": "PHP",
"bytes": "6958840"
},
{
"name": "Shell",
"bytes": "2704"
}
],
"symlink_target": ""
} |
require "date"
module Idioms
class InvalidDate < ArgumentError; end
class InvalidDateTime < ArgumentError; end
end
class Date
module ParseWithError
def parse!(*args)
time = parse(*args)
if time && time.year > 294276
raise Idioms::InvalidDate, "Years larger than 294276 are not supported by Postgres timestamps"
elsif time && time.year <= 0
raise Idioms::InvalidDate, "Years smaller than 1 are not supported by Postgres timestamps"
end
time
rescue ArgumentError
raise Idioms::InvalidDate, $!.message
end
end
extend ParseWithError
end
class DateTime
module ParseWithError
def parse!(*args)
time = parse(*args)
if time && time.year > 294276
raise Idioms::InvalidDate, "Years larger than 294276 are not supported by Postgres timestamps"
end
time
rescue ArgumentError
raise Idioms::InvalidDateTime, $!.message
end
end
extend ParseWithError
end
| {
"content_hash": "bf341d23b14aa1e0934cc154cb804514",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 102,
"avg_line_length": 22.227272727272727,
"alnum_prop": 0.6809815950920245,
"repo_name": "cph/idioms",
"id": "d43686b89f596cf021e1689e2b4ef4bce186bb65",
"size": "978",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/idioms/core_ext/date.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "14604"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>libspotify: Globals</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">libspotify
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.8.0 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li class="current"><a href="globals.html"><span>Globals</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li class="current"><a href="globals.html"><span>All</span></a></li>
<li><a href="globals_func.html"><span>Functions</span></a></li>
<li><a href="globals_type.html"><span>Typedefs</span></a></li>
<li><a href="globals_enum.html"><span>Enumerations</span></a></li>
<li><a href="globals_eval.html"><span>Enumerator</span></a></li>
<li><a href="globals_defs.html"><span>Defines</span></a></li>
</ul>
</div>
<div id="navrow4" class="tabs3">
<ul class="tablist">
<li><a href="globals.html#index_a"><span>a</span></a></li>
<li><a href="globals_0x69.html#index_i"><span>i</span></a></li>
<li><a href="globals_0x73.html#index_s"><span>s</span></a></li>
<li class="current"><a href="globals_0x74.html#index_t"><span>t</span></a></li>
</ul>
</div>
</div>
<div class="contents">
<div class="textblock">Here is a list of all documented functions, variables, defines, enums, and typedefs with links to the documentation:</div>
<h3><a class="anchor" id="index_t"></a>- t -</h3><ul>
<li>toplistbrowse_complete_cb
: <a class="el" href="group__toplist.html#gafe8e94ae23133105f35c03b9e3836a0a">api.h</a>
</li>
</ul>
</div><!-- contents -->
<hr size="1"><address style="text-align: right;"><small>
Generated on Wed May 23 2012 10:59:47.<br>
Copyright © 2006–2012 Spotify Ltd</small></address>
</body>
</html>
| {
"content_hash": "446d8c338d4c97457f130e9b964af99c",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 145,
"avg_line_length": 33.58139534883721,
"alnum_prop": 0.6142659279778393,
"repo_name": "niklasberglund/spotthedaemon",
"id": "03b55f932cfc10944ba286c5ca806e942a5c5083",
"size": "2888",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CocoaLibSpotify/libspotify-12.1.45-Darwin-universal/docs/html/globals_0x74.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "163938"
},
{
"name": "C++",
"bytes": "144547"
},
{
"name": "CSS",
"bytes": "7568"
},
{
"name": "Objective-C",
"bytes": "1283140"
},
{
"name": "Shell",
"bytes": "4407"
}
],
"symlink_target": ""
} |
SLIB_DEFINE_APPLICATION(DragAndDropApp, UIApp)
DragAndDropApp::DragAndDropApp()
{
}
void DragAndDropApp::onStart()
{
Ref<MainWindow> window = new MainWindow;
window->create();
setMainWindow(window);
}
| {
"content_hash": "bdfa5acc49a7536ec8a74b3680d5e13f",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 46,
"avg_line_length": 17.166666666666668,
"alnum_prop": 0.7572815533980582,
"repo_name": "SLIBIO/SLib",
"id": "387254662c62c16c4a6ecb22fa52bd0dde76f34a",
"size": "249",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/UI/DragAndDrop/src/cpp/app.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "12324"
},
{
"name": "C",
"bytes": "172728"
},
{
"name": "C++",
"bytes": "8974152"
},
{
"name": "CMake",
"bytes": "25579"
},
{
"name": "Java",
"bytes": "412451"
},
{
"name": "Objective-C",
"bytes": "13961"
},
{
"name": "Objective-C++",
"bytes": "641784"
},
{
"name": "PHP",
"bytes": "306070"
},
{
"name": "Shell",
"bytes": "4835"
},
{
"name": "SourcePawn",
"bytes": "19475"
}
],
"symlink_target": ""
} |
<?php
/*
Safe sample
input : get the field userData from the variable $_GET via an object, which store it in a array
SANITIZE : use in_array to check if $tainted is in the white list
construction : use of sprintf via a %s with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
class Input{
private $input;
public function getInput(){
return $this->input['realOne'];
}
public function __construct(){
$this->input = array();
$this->input['test']= 'safe' ;
$this->input['realOne']= $_GET['UserData'] ;
$this->input['trap']= 'safe' ;
}
}
$temp = new Input();
$tainted = $temp->getInput();
$legal_table = array("safe1", "safe2");
if (in_array($tainted, $legal_table, true)) {
$tainted = $tainted;
} else {
$tainted = $legal_table[0];
}
$query = sprintf("echo $'%s';", $tainted);
$res = eval($query);
?> | {
"content_hash": "30460e3a8def3849b1b082e45421eeb1",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 95,
"avg_line_length": 23.52054794520548,
"alnum_prop": 0.7157833430401864,
"repo_name": "stivalet/PHP-Vulnerability-test-suite",
"id": "6b896622b204a7b934cd7fd57eccdb0a8f7bfd72",
"size": "1717",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Injection/CWE_95/safe/CWE_95__object-indexArray__whitelist_using_array__echo-sprintf_%s_simple_quote.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "64184004"
}
],
"symlink_target": ""
} |
import { Item } from '../Models/Item';
import { Location } from '../Models/Location';
import { ObservableArray } from 'data/observable-array';
/**
* Interface which describes how ViewModel that implements showing Item information ought to implement in order to be used in application
*/
export interface IShowItems {
/**
* Initial set of items givn by constructor
*/
readonly _items: ObservableArray<any>;
/**
* Array of objects which represent JOINed items with theirs foreign key tables
*/
items: ObservableArray<any>;
/**
* When user taps on item
*/
onItemTap(args: any): void;
} | {
"content_hash": "191502eaeaa832c557e3c0e61ed1fcb4",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 137,
"avg_line_length": 27.869565217391305,
"alnum_prop": 0.672386895475819,
"repo_name": "rLoka/OfficeEquipmentTracker",
"id": "4520182473f7d411ff6a260932daafa203485c1a",
"size": "641",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Common/IShowItems.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2976"
},
{
"name": "JavaScript",
"bytes": "1765"
},
{
"name": "TypeScript",
"bytes": "86327"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.compute.generated;
import com.azure.core.util.Context;
import com.azure.resourcemanager.compute.models.GalleryApplicationVersionPublishingProfile;
import com.azure.resourcemanager.compute.models.GalleryApplicationVersionSafetyProfile;
import com.azure.resourcemanager.compute.models.GalleryApplicationVersionUpdate;
import com.azure.resourcemanager.compute.models.StorageAccountType;
import com.azure.resourcemanager.compute.models.TargetRegion;
import com.azure.resourcemanager.compute.models.UserArtifactManage;
import com.azure.resourcemanager.compute.models.UserArtifactSource;
import java.time.OffsetDateTime;
import java.util.Arrays;
/** Samples for GalleryApplicationVersions Update. */
public final class GalleryApplicationVersionsUpdateSamples {
/*
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/GalleryRP/stable/2022-03-03/examples/galleryExamples/GalleryApplicationVersion_Update.json
*/
/**
* Sample code: Update a simple gallery Application Version.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void updateASimpleGalleryApplicationVersion(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.virtualMachines()
.manager()
.serviceClient()
.getGalleryApplicationVersions()
.update(
"myResourceGroup",
"myGalleryName",
"myGalleryApplicationName",
"1.0.0",
new GalleryApplicationVersionUpdate()
.withPublishingProfile(
new GalleryApplicationVersionPublishingProfile()
.withTargetRegions(
Arrays
.asList(
new TargetRegion()
.withName("West US")
.withRegionalReplicaCount(1)
.withStorageAccountType(StorageAccountType.STANDARD_LRS)
.withExcludeFromLatest(false)))
.withReplicaCount(1)
.withEndOfLifeDate(OffsetDateTime.parse("2019-07-01T07:00:00Z"))
.withStorageAccountType(StorageAccountType.STANDARD_LRS)
.withSource(
new UserArtifactSource()
.withMediaLink(
"https://mystorageaccount.blob.core.windows.net/mycontainer/package.zip?{sasKey}"))
.withManageActions(
new UserArtifactManage()
.withInstall(
"powershell -command \"Expand-Archive -Path package.zip -DestinationPath"
+ " C:\\package\"")
.withRemove("del C:\\package ")))
.withSafetyProfile(
new GalleryApplicationVersionSafetyProfile().withAllowDeletionOfReplicatedLocations(false)),
Context.NONE);
}
}
| {
"content_hash": "3e135749324385a0652a37fa35b51a2e",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 174,
"avg_line_length": 52.32835820895522,
"alnum_prop": 0.5818596691386195,
"repo_name": "Azure/azure-sdk-for-java",
"id": "e22b1c73a95e5e53867ad6861582abb20c2626f3",
"size": "3506",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/compute/generated/GalleryApplicationVersionsUpdateSamples.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#ifdef WITH_XCURSOR
#include <X11/Xcursor/Xcursor.h>
#endif
#ifdef WITH_XI
#include <X11/extensions/XInput2.h>
#endif
#include <math.h>
#include "xf_event.h"
#include "xf_input.h"
#include <freerdp/log.h>
#define TAG CLIENT_TAG("x11")
#ifdef WITH_XI
#define MAX_CONTACTS 2
#define PAN_THRESHOLD 50
#define ZOOM_THRESHOLD 10
#define MIN_FINGER_DIST 5
typedef struct touch_contact
{
int id;
int count;
double pos_x;
double pos_y;
double last_x;
double last_y;
} touchContact;
static touchContact contacts[MAX_CONTACTS];
static int active_contacts;
static int lastEvType;
static XIDeviceEvent lastEvent;
static double firstDist = -1.0;
static double lastDist;
static double z_vector;
static double px_vector;
static double py_vector;
const char* xf_input_get_class_string(int class)
{
if (class == XIKeyClass)
return "XIKeyClass";
else if (class == XIButtonClass)
return "XIButtonClass";
else if (class == XIValuatorClass)
return "XIValuatorClass";
else if (class == XIScrollClass)
return "XIScrollClass";
else if (class == XITouchClass)
return "XITouchClass";
return "XIUnknownClass";
}
int xf_input_init(xfContext* xfc, Window window)
{
int i, j;
int nmasks;
int ndevices;
int major = 2;
int minor = 2;
Status xstatus;
XIDeviceInfo* info;
XIEventMask evmasks[64];
int opcode, event, error;
BYTE masks[8][XIMaskLen(XI_LASTEVENT)];
z_vector = 0;
px_vector = 0;
py_vector = 0;
nmasks = 0;
ndevices = 0;
active_contacts = 0;
ZeroMemory(contacts, sizeof(touchContact) * MAX_CONTACTS);
if (!XQueryExtension(xfc->display, "XInputExtension", &opcode, &event, &error))
{
WLog_WARN(TAG, "XInput extension not available.");
return -1;
}
xfc->XInputOpcode = opcode;
XIQueryVersion(xfc->display, &major, &minor);
if (major * 1000 + minor < 2002)
{
WLog_WARN(TAG, "Server does not support XI 2.2");
return -1;
}
if (xfc->context.settings->MultiTouchInput)
xfc->use_xinput = TRUE;
info = XIQueryDevice(xfc->display, XIAllDevices, &ndevices);
for (i = 0; i < ndevices; i++)
{
BOOL touch = FALSE;
XIDeviceInfo* dev = &info[i];
for (j = 0; j < dev->num_classes; j++)
{
XIAnyClassInfo* class = dev->classes[j];
XITouchClassInfo* t = (XITouchClassInfo*) class;
if ((class->type == XITouchClass) && (t->mode == XIDirectTouch) &&
(strcmp(dev->name, "Virtual core pointer") != 0))
{
touch = TRUE;
}
}
for (j = 0; j < dev->num_classes; j++)
{
XIAnyClassInfo* class = dev->classes[j];
XITouchClassInfo* t = (XITouchClassInfo*) class;
if (xfc->context.settings->MultiTouchInput)
{
WLog_INFO(TAG, "%s (%d) \"%s\" id: %d",
xf_input_get_class_string(class->type),
class->type, dev->name, dev->deviceid);
}
evmasks[nmasks].mask = masks[nmasks];
evmasks[nmasks].mask_len = sizeof(masks[0]);
ZeroMemory(masks[nmasks], sizeof(masks[0]));
evmasks[nmasks].deviceid = dev->deviceid;
if ((class->type == XITouchClass) && (t->mode == XIDirectTouch) &&
(strcmp(dev->name, "Virtual core pointer") != 0))
{
if (xfc->context.settings->MultiTouchInput)
{
WLog_INFO(TAG, "%s %s touch device (id: %d, mode: %d), supporting %d touches.",
dev->name, (t->mode == XIDirectTouch) ? "direct" : "dependent",
dev->deviceid, t->mode, t->num_touches);
}
XISetMask(masks[nmasks], XI_TouchBegin);
XISetMask(masks[nmasks], XI_TouchUpdate);
XISetMask(masks[nmasks], XI_TouchEnd);
nmasks++;
}
if (xfc->use_xinput)
{
if (!touch && (class->type == XIButtonClass)
&& strcmp(dev->name, "Virtual core pointer"))
{
WLog_INFO(TAG, "%s button device (id: %d, mode: %d)",
dev->name,
dev->deviceid, t->mode);
XISetMask(masks[nmasks], XI_ButtonPress);
XISetMask(masks[nmasks], XI_ButtonRelease);
XISetMask(masks[nmasks], XI_Motion);
nmasks++;
}
}
}
}
XIFreeDeviceInfo(info);
if (nmasks > 0)
xstatus = XISelectEvents(xfc->display, window, evmasks, nmasks);
return 0;
}
static BOOL xf_input_is_duplicate(XGenericEventCookie* cookie)
{
XIDeviceEvent* event;
event = cookie->data;
if ((lastEvent.time == event->time) &&
(lastEvType == cookie->evtype) &&
(lastEvent.detail == event->detail) &&
(lastEvent.event_x == event->event_x) &&
(lastEvent.event_y == event->event_y))
{
return TRUE;
}
return FALSE;
}
static void xf_input_save_last_event(XGenericEventCookie* cookie)
{
XIDeviceEvent* event;
event = cookie->data;
lastEvType = cookie->evtype;
lastEvent.time = event->time;
lastEvent.detail = event->detail;
lastEvent.event_x = event->event_x;
lastEvent.event_y = event->event_y;
}
static void xf_input_detect_pan(xfContext* xfc)
{
double dx[2];
double dy[2];
double px;
double py;
double dist_x;
double dist_y;
if (active_contacts != 2)
{
return;
}
dx[0] = contacts[0].pos_x - contacts[0].last_x;
dx[1] = contacts[1].pos_x - contacts[1].last_x;
dy[0] = contacts[0].pos_y - contacts[0].last_y;
dy[1] = contacts[1].pos_y - contacts[1].last_y;
px = fabs(dx[0]) < fabs(dx[1]) ? dx[0] : dx[1];
py = fabs(dy[0]) < fabs(dy[1]) ? dy[0] : dy[1];
px_vector += px;
py_vector += py;
dist_x = fabs(contacts[0].pos_x - contacts[1].pos_x);
dist_y = fabs(contacts[0].pos_y - contacts[1].pos_y);
if (dist_y > MIN_FINGER_DIST)
{
if (px_vector > PAN_THRESHOLD)
{
{
PanningChangeEventArgs e;
EventArgsInit(&e, "xfreerdp");
e.dx = 5;
e.dy = 0;
PubSub_OnPanningChange(((rdpContext*) xfc)->pubSub, xfc, &e);
}
px_vector = 0;
py_vector = 0;
z_vector = 0;
}
else if (px_vector < -PAN_THRESHOLD)
{
{
PanningChangeEventArgs e;
EventArgsInit(&e, "xfreerdp");
e.dx = -5;
e.dy = 0;
PubSub_OnPanningChange(((rdpContext*) xfc)->pubSub, xfc, &e);
}
px_vector = 0;
py_vector = 0;
z_vector = 0;
}
}
if (dist_x > MIN_FINGER_DIST)
{
if (py_vector > PAN_THRESHOLD)
{
{
PanningChangeEventArgs e;
EventArgsInit(&e, "xfreerdp");
e.dx = 0;
e.dy = 5;
PubSub_OnPanningChange(((rdpContext*) xfc)->pubSub, xfc, &e);
}
py_vector = 0;
px_vector = 0;
z_vector = 0;
}
else if (py_vector < -PAN_THRESHOLD)
{
{
PanningChangeEventArgs e;
EventArgsInit(&e, "xfreerdp");
e.dx = 0;
e.dy = -5;
PubSub_OnPanningChange(((rdpContext*) xfc)->pubSub, xfc, &e);
}
py_vector = 0;
px_vector = 0;
z_vector = 0;
}
}
}
static void xf_input_detect_pinch(xfContext* xfc)
{
double dist;
double delta;
ZoomingChangeEventArgs e;
if (active_contacts != 2)
{
firstDist = -1.0;
return;
}
/* first calculate the distance */
dist = sqrt(pow(contacts[1].pos_x - contacts[0].last_x, 2.0) +
pow(contacts[1].pos_y - contacts[0].last_y, 2.0));
/* if this is the first 2pt touch */
if (firstDist <= 0)
{
firstDist = dist;
lastDist = firstDist;
z_vector = 0;
px_vector = 0;
py_vector = 0;
}
else
{
delta = lastDist - dist;
if (delta > 1.0)
delta = 1.0;
if (delta < -1.0)
delta = -1.0;
/* compare the current distance to the first one */
z_vector += delta;
lastDist = dist;
if (z_vector > ZOOM_THRESHOLD)
{
EventArgsInit(&e, "xfreerdp");
e.dx = e.dy = -10;
PubSub_OnZoomingChange(((rdpContext*) xfc)->pubSub, xfc, &e);
z_vector = 0;
px_vector = 0;
py_vector = 0;
}
if (z_vector < -ZOOM_THRESHOLD)
{
EventArgsInit(&e, "xfreerdp");
e.dx = e.dy = 10;
PubSub_OnZoomingChange(((rdpContext*) xfc)->pubSub, xfc, &e);
z_vector = 0;
px_vector = 0;
py_vector = 0;
}
}
}
static void xf_input_touch_begin(xfContext* xfc, XIDeviceEvent* event)
{
int i;
for (i = 0; i < MAX_CONTACTS; i++)
{
if (contacts[i].id == 0)
{
contacts[i].id = event->detail;
contacts[i].count = 1;
contacts[i].pos_x = event->event_x;
contacts[i].pos_y = event->event_y;
active_contacts++;
break;
}
}
}
static void xf_input_touch_update(xfContext* xfc, XIDeviceEvent* event)
{
int i;
for (i = 0; i < MAX_CONTACTS; i++)
{
if (contacts[i].id == event->detail)
{
contacts[i].count++;
contacts[i].last_x = contacts[i].pos_x;
contacts[i].last_y = contacts[i].pos_y;
contacts[i].pos_x = event->event_x;
contacts[i].pos_y = event->event_y;
xf_input_detect_pinch(xfc);
xf_input_detect_pan(xfc);
break;
}
}
}
static void xf_input_touch_end(xfContext* xfc, XIDeviceEvent* event)
{
int i;
for (i = 0; i < MAX_CONTACTS; i++)
{
if (contacts[i].id == event->detail)
{
contacts[i].id = 0;
contacts[i].count = 0;
active_contacts--;
break;
}
}
}
static int xf_input_handle_event_local(xfContext* xfc, XEvent* event)
{
XGenericEventCookie* cookie = &event->xcookie;
XGetEventData(xfc->display, cookie);
if ((cookie->type == GenericEvent) && (cookie->extension == xfc->XInputOpcode))
{
switch (cookie->evtype)
{
case XI_TouchBegin:
if (xf_input_is_duplicate(cookie) == FALSE)
xf_input_touch_begin(xfc, cookie->data);
xf_input_save_last_event(cookie);
break;
case XI_TouchUpdate:
if (xf_input_is_duplicate(cookie) == FALSE)
xf_input_touch_update(xfc, cookie->data);
xf_input_save_last_event(cookie);
break;
case XI_TouchEnd:
if (xf_input_is_duplicate(cookie) == FALSE)
xf_input_touch_end(xfc, cookie->data);
xf_input_save_last_event(cookie);
break;
default:
WLog_ERR(TAG, "unhandled xi type= %d", cookie->evtype);
break;
}
}
XFreeEventData(xfc->display, cookie);
return 0;
}
#ifdef WITH_DEBUG_X11
static char* xf_input_touch_state_string(DWORD flags)
{
if (flags & CONTACT_FLAG_DOWN)
return "TouchBegin";
else if (flags & CONTACT_FLAG_UPDATE)
return "TouchUpdate";
else if (flags & CONTACT_FLAG_UP)
return "TouchEnd";
else
return "TouchUnknown";
}
#endif
static void xf_input_hide_cursor(xfContext* xfc)
{
#ifdef WITH_XCURSOR
if (!xfc->cursorHidden)
{
XcursorImage ci;
XcursorPixel xp = 0;
static Cursor nullcursor = None;
xf_lock_x11(xfc, FALSE);
ZeroMemory(&ci, sizeof(ci));
ci.version = XCURSOR_IMAGE_VERSION;
ci.size = sizeof(ci);
ci.width = ci.height = 1;
ci.xhot = ci.yhot = 0;
ci.pixels = &xp;
nullcursor = XcursorImageLoadCursor(xfc->display, &ci);
if ((xfc->window) && (nullcursor != None))
XDefineCursor(xfc->display, xfc->window->handle, nullcursor);
xfc->cursorHidden = TRUE;
xf_unlock_x11(xfc, FALSE);
}
#endif
}
static void xf_input_show_cursor(xfContext* xfc)
{
#ifdef WITH_XCURSOR
xf_lock_x11(xfc, FALSE);
if (xfc->cursorHidden)
{
if (xfc->window)
{
if (!xfc->pointer)
XUndefineCursor(xfc->display, xfc->window->handle);
else
XDefineCursor(xfc->display, xfc->window->handle, xfc->pointer->cursor);
}
xfc->cursorHidden = FALSE;
}
xf_unlock_x11(xfc, FALSE);
#endif
}
static int xf_input_touch_remote(xfContext* xfc, XIDeviceEvent* event, int evtype)
{
int x, y;
int touchId;
int contactId;
RdpeiClientContext* rdpei = xfc->rdpei;
if (!rdpei)
return 0;
xf_input_hide_cursor(xfc);
touchId = event->detail;
x = (int) event->event_x;
y = (int) event->event_y;
xf_event_adjust_coordinates(xfc, &x, &y);
if (evtype == XI_TouchBegin)
{
WLog_DBG(TAG, "TouchBegin: %d", touchId);
rdpei->TouchBegin(rdpei, touchId, x, y, &contactId);
}
else if (evtype == XI_TouchUpdate)
{
WLog_DBG(TAG, "TouchUpdate: %d", touchId);
rdpei->TouchUpdate(rdpei, touchId, x, y, &contactId);
}
else if (evtype == XI_TouchEnd)
{
WLog_DBG(TAG, "TouchEnd: %d", touchId);
rdpei->TouchEnd(rdpei, touchId, x, y, &contactId);
}
return 0;
}
static int xf_input_event(xfContext* xfc, XIDeviceEvent* event, int evtype)
{
xf_input_show_cursor(xfc);
switch (evtype)
{
case XI_ButtonPress:
xf_generic_ButtonPress(xfc, (int) event->event_x, (int) event->event_y,
event->detail, event->event, xfc->remote_app);
break;
case XI_ButtonRelease:
xf_generic_ButtonRelease(xfc, (int) event->event_x, (int) event->event_y,
event->detail, event->event, xfc->remote_app);
break;
case XI_Motion:
xf_generic_MotionNotify(xfc, (int) event->event_x, (int) event->event_y,
event->detail, event->event, xfc->remote_app);
break;
}
return 0;
}
static int xf_input_handle_event_remote(xfContext* xfc, XEvent* event)
{
XGenericEventCookie* cookie = &event->xcookie;
XGetEventData(xfc->display, cookie);
if ((cookie->type == GenericEvent) && (cookie->extension == xfc->XInputOpcode))
{
switch (cookie->evtype)
{
case XI_TouchBegin:
xf_input_touch_remote(xfc, cookie->data, XI_TouchBegin);
break;
case XI_TouchUpdate:
xf_input_touch_remote(xfc, cookie->data, XI_TouchUpdate);
break;
case XI_TouchEnd:
xf_input_touch_remote(xfc, cookie->data, XI_TouchEnd);
break;
default:
xf_input_event(xfc, cookie->data, cookie->evtype);
break;
}
}
XFreeEventData(xfc->display, cookie);
return 0;
}
#else
int xf_input_init(xfContext* xfc, Window window)
{
return 0;
}
#endif
int xf_input_handle_event(xfContext* xfc, XEvent* event)
{
#ifdef WITH_XI
if (xfc->context.settings->MultiTouchInput)
{
return xf_input_handle_event_remote(xfc, event);
}
if (xfc->context.settings->MultiTouchGestures)
{
return xf_input_handle_event_local(xfc, event);
}
#endif
return 0;
}
| {
"content_hash": "e77504a742395c26d9d78dd5fc3d24f9",
"timestamp": "",
"source": "github",
"line_count": 639,
"max_line_length": 84,
"avg_line_length": 21.114241001564945,
"alnum_prop": 0.63170767862437,
"repo_name": "bjcollins/FreeRDP",
"id": "1db2ff1f09a9a3f8ff711558bac86d79a2a6dba3",
"size": "14182",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "client/X11/xf_input.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "11521439"
},
{
"name": "C#",
"bytes": "9237"
},
{
"name": "C++",
"bytes": "170315"
},
{
"name": "CMake",
"bytes": "702268"
},
{
"name": "CSS",
"bytes": "5696"
},
{
"name": "HTML",
"bytes": "99139"
},
{
"name": "Java",
"bytes": "421049"
},
{
"name": "Makefile",
"bytes": "1423"
},
{
"name": "Objective-C",
"bytes": "1113117"
},
{
"name": "Perl",
"bytes": "8044"
},
{
"name": "Python",
"bytes": "1430"
},
{
"name": "Roff",
"bytes": "3708"
},
{
"name": "Shell",
"bytes": "24716"
}
],
"symlink_target": ""
} |
\section{\textbf{FibTaskTest}}
\subsection{Particular Case (problem)}
The problem is calculating the sum of the first $n$ Fibonacci numbers,
in parallel.
\subsection{Solution}
The solution merely follows the recursive definition of the Fibonacci
sequence, whose base cases are 1 (for first and second elements of the
sequence). Each recursive call of the function creates a new task
(\C{Future} from java concurrency library). Below the code of the main
function: \\
\begin{lstlisting}[style=numbers]
public Integer call() {
try {
if (arg > 2) {
Future<Integer> left = exec.submit(new FibTask(arg-1));
Future<Integer> right = exec.submit(new FibTask(arg-2));
return left.get() + right.get();
} else {
return 1;
}
} catch (Exception ex) {
ex.printStackTrace();
return 1;
}
}
\end{lstlisting}
\hfill
Note that \C{Future} class represents asynchronous calculations, and
that the \C{get} method is blocking (waits for calculation to be
complete); hence we would effectively create a tree of tasks until we
reach the base cases and start evaluating bottom up.
\subsection{Experiment Description}
The experiment merely request the calculation of the sum up to a known
number (16), and asserts the expected result (987).
\subsection{Observations and Interpretations}
The test works as expected in both 2 and 24 cores machines. Below a
sample output: \\
\begin{verbatim}
[oraadm@gdlaa008 orig]$ junit steal.FibTaskTest
.run
Time: 0.128
OK (1 test)
\end{verbatim}
\hfill
| {
"content_hash": "4027522e0de89fb8871e6eeeeec9b197",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 70,
"avg_line_length": 28.74074074074074,
"alnum_prop": 0.7216494845360825,
"repo_name": "rzavalet/multiprocessor",
"id": "2dafd426122f15fb5c1ac8ddbf0924256a07caa5",
"size": "1552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dario/Multiprocessor/FibTaskTest.tex",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2042"
},
{
"name": "Makefile",
"bytes": "685"
},
{
"name": "Shell",
"bytes": "434"
},
{
"name": "TeX",
"bytes": "683610"
}
],
"symlink_target": ""
} |
package coordinatorTest
import (
"flag"
)
var testGoLogger = flag.Bool("logdog.gologger", false, "Attach console logger.")
| {
"content_hash": "6fe1cd1bcde6caadfa862993e2f39546",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 80,
"avg_line_length": 18,
"alnum_prop": 0.7380952380952381,
"repo_name": "luci/luci-go",
"id": "66f849c8264904d8309a2fbfc66d72e9f0558d7e",
"size": "722",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "logdog/appengine/coordinator/coordinatorTest/flag.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25460"
},
{
"name": "Go",
"bytes": "10674259"
},
{
"name": "HTML",
"bytes": "658081"
},
{
"name": "JavaScript",
"bytes": "18433"
},
{
"name": "Makefile",
"bytes": "2862"
},
{
"name": "Python",
"bytes": "49205"
},
{
"name": "Shell",
"bytes": "20986"
},
{
"name": "TypeScript",
"bytes": "110221"
}
],
"symlink_target": ""
} |
package org.apache.sis.internal.storage.io;
import java.io.IOException;
/**
* Stream reader or writer capable to mark its current position and reset to that position later.
* The stream shall support nested marks.
*
* <div class="note"><b>Use case:</b>
* this interface can be used when we need to move to a previously marked position, but we do not know how many nested
* {@code mark()} method calls may have been performed (typically because the stream has been used by arbitrary code).
* We can compare {@link #getStreamPosition()} value after {@link #reset()} method calls with the expected position.
* </div>
*
* <div class="note"><b>Design note:</b>
* an alternative could be to support the {@code seek(long)} method. But using marks instead allows the stream
* to invalidate the marks if needed (for example when {@link ChannelData#setStreamPosition(long)} is invoked).
* </div>
*
* @author Martin Desruisseaux (Geomatys)
* @version 1.2
*
* @see Readable
*
* @since 0.8
* @module
*/
public interface Markable {
/**
* Returns the current byte position of the stream.
*
* @return the position of the stream.
* @throws IOException if the position cannot be obtained.
*/
long getStreamPosition() throws IOException;
/**
* Pushes the current stream position onto a stack of marked positions.
* A subsequent call to the {@link #reset()} method repositions this stream
* at the last marked position so that subsequent reads re-read the same bytes.
* Calls to {@code mark()} and {@code reset()} can be nested arbitrarily.
*
* @throws IOException if this stream cannot mark the current position.
*
* @see javax.imageio.stream.ImageInputStream#mark()
*/
void mark() throws IOException;
/**
* Resets the current stream byte and bit positions from the stack of marked positions.
* An {@code IOException} may be be thrown if the previous marked position lies in the
* discarded portion of the stream.
*
* <h4>Behavior if there is no mark</h4>
* Calls to {@code reset()} without a corresponding call to {@code mark()}
* have different behavior depending on which interface defines the mark/reset methods:
* {@link java.io.InputStream#reset()} specifies that we might move to the file beginning or throw an exception.
* {@link javax.imageio.stream.ImageInputStream#reset()} specifies that we shall do nothing.
* For this {@code Markable} interface we recommend to throw an {@link IOException}.
*
* @throws IOException if this stream cannot move to the last mark position.
*
* @see java.io.InputStream#reset()
* @see javax.imageio.stream.ImageInputStream#reset()
* @see org.apache.sis.io.InvalidSeekException
*/
void reset() throws IOException;
/**
* Resets the stream position to the mark at the given position. Invoking this method is similar to
* invoking {@code seek(mark)} except that it may work on non-seekable stream if a mark has been set
* on that position.
*
* @param mark position where to seek. Should be a position where a mark has been created.
* @throws IOException if this stream cannot move to the specified mark position.
*/
void reset(long mark) throws IOException;
}
| {
"content_hash": "eeff301e11d5ae0601bfe53175d479f2",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 118,
"avg_line_length": 41.6625,
"alnum_prop": 0.6921692169216922,
"repo_name": "apache/sis",
"id": "285336cc469c1f3a377a3e1aae1d41d7cbcdc9ba",
"size": "4134",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "storage/sis-storage/src/main/java/org/apache/sis/internal/storage/io/Markable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1667"
},
{
"name": "CSS",
"bytes": "152"
},
{
"name": "HTML",
"bytes": "76446"
},
{
"name": "Java",
"bytes": "32802649"
},
{
"name": "Shell",
"bytes": "3379"
}
],
"symlink_target": ""
} |
<?php
$cmd = $argv[0];
$name = $argv[1];
if (!$name) {
die("Write a name for your application. The name will be the PHP class name of your application base class. a-z, 0-9 and _ are allowed\n");
}
$nice = strtolower($name);
if (!preg_match('|^[a-z][\w\d_]*$|', $nice)) {
die("Not a valid name, only a-z0-9_ are allowed: $name ($nice)\n");
}
if (is_dir($nice)) {
die("A directory exists by that name: $nice\n");
}
if (file_exists($nice)) {
die("A file exists by that name: $nice\n");
}
$path = preg_replace('|_|', "/", $name);
mkdir($nice);
mkdir("$nice/lib");
mkdir("$nice/lib/$path", 0777, true);
$context = <<<EOF
<?php
require_once 'DF/Web.php';
class $name extends DF_Web {
}
EOF;
file_put_contents("$nice/lib/$path.php", $context);
$config = <<<EOF
---
Controller_Root:
namespace: ""
actions:
chained:
# Chained: /
chained: /
path: ""
index:
# Matches: /
chained: chained
path: ""
args: 0
default:
# Matches: /*
chained: chained
path: ""
args:
EOF;
file_put_contents("$nice/config.yaml", $config);
mkdir("$nice/lib/$path/Controller");
mkdir("$nice/lib/$path/Model");
mkdir("$nice/lib/$path/View");
$root_ctrl = <<<EOF
<?php
class ${name}_Controller_Root extends DF_Web_Controller {
# Run once for this controller per request
public function handle_auto(\$c) {
error_log("This is Root/auto");
return true;
}
# Chained to the root, see config.yaml
public function handle_chained(\$c) {
error_log("This is Root/chained");
}
# The index page, see config.yaml
public function handle_index(\$c) {
error_log("This is Root/index");
\$c->response->content_type('text/plain');
\$c->response->body("Hello world");
return true;
}
# The default page, see config.yaml
# Fallbacks to this if on other actions match
public function handle_default(\$c) {
error_log("This is Root/default");
\$c->response->status(404);
\$c->response->content_type('text/plain');
\$c->response->body("Nothing found");
return true;
}
}
EOF;
file_put_contents("$nice/lib/$path/Controller/Root.php", $root_ctrl);
mkdir("$nice/www");
$dot_htaccess = <<<EOF
SetEnv ENVIRONMENT 'development'
RewriteEngine On
RewriteBase /$nice
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /$nice/index.php
EOF;
file_put_contents("$nice/www/.htaccess", $dot_htaccess);
$index = <<<EOF
<?php
# index.php
\$DIR_SCRIPT = dirname(__FILE__);
\$DIR_ROOT = "\$DIR_SCRIPT/..";
\$DIR_LIB = "\$DIR_ROOT/lib";
set_include_path(\$DIR_LIB.':'.get_include_path());
require_once 'DF/Web/Logger.php';
DF_Web_Logger::setActiveLogger('error_log');
require_once '$path.php';
\$environment = DF_Web_Environment::singleton();
\$environment->app_root = \$DIR_ROOT;
\$environment->trusted_proxies = 0;
\$environment->base_path = dirname(\$_SERVER['SCRIPT_NAME']);
if (getenv('ENVIRONMENT')) {
\$environment->environment = getenv('ENVIRONMENT');
}
\$environment->debug = 1;
# for production
#\$environment->environment = 'production';
#\$environment->debug = 0;
\$context = new $name();
\$context->execute();
\$context->finalize();
\$context = NULL;
DF_Web_Logger::shutdown();
EOF;
file_put_contents("$nice/www/index.php", $index);
echo "\n";
echo "SUCCESS - soon ready to use\n";
echo "\n";
echo "You might have to symlink the $nice/www directory to your Apache (or other web server) web application folder and configure $nice/www/.htaccess rewrite rules\n";
echo "\n";
| {
"content_hash": "d905dede26d6f416c16ce366b395cfab",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 167,
"avg_line_length": 23.53125,
"alnum_prop": 0.598140770252324,
"repo_name": "hovenko/Madcow",
"id": "fc627e66a4b9896432e8fd3f87a134b5b2ba5988",
"size": "3765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/madcow.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "229486"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0059_auto_20150706_0526'),
]
operations = [
migrations.AddField(
model_name='activity',
name='likes',
field=models.ManyToManyField(related_name='liked_activities', to=settings.AUTH_USER_MODEL),
preserve_default=True,
),
]
| {
"content_hash": "300124dd5d2590e7607242e3184a0e1f",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 103,
"avg_line_length": 26.714285714285715,
"alnum_prop": 0.6399286987522281,
"repo_name": "rdsathene/SchoolIdolAPI",
"id": "b5db7c2cd7bbacd8adb02686789d11d2458cff6e",
"size": "585",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "api/migrations/0060_activity_likes.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "67801"
},
{
"name": "HTML",
"bytes": "474584"
},
{
"name": "JavaScript",
"bytes": "93928"
},
{
"name": "Python",
"bytes": "748281"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_272) on Tue May 11 08:03:45 PDT 2021 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package com.fasterxml.aalto.out (aalto-xml 1.3.0 API)</title>
<meta name="date" content="2021-05-11">
<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 Package com.fasterxml.aalto.out (aalto-xml 1.3.0 API)";
}
}
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>Class</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-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/fasterxml/aalto/out/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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">
<h1 title="Uses of Package com.fasterxml.aalto.out" class="title">Uses of Package<br>com.fasterxml.aalto.out</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../com/fasterxml/aalto/out/package-summary.html">com.fasterxml.aalto.out</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.aalto.dom">com.fasterxml.aalto.dom</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.fasterxml.aalto.io">com.fasterxml.aalto.io</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.aalto.out">com.fasterxml.aalto.out</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.fasterxml.aalto.stax">com.fasterxml.aalto.stax</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.aalto.dom">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../com/fasterxml/aalto/out/package-summary.html">com.fasterxml.aalto.out</a> used by <a href="../../../../com/fasterxml/aalto/dom/package-summary.html">com.fasterxml.aalto.dom</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/WriterConfig.html#com.fasterxml.aalto.dom">WriterConfig</a>
<div class="block">This is the shared configuration object passed by the factory to writer.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.aalto.io">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../com/fasterxml/aalto/out/package-summary.html">com.fasterxml.aalto.out</a> used by <a href="../../../../com/fasterxml/aalto/io/package-summary.html">com.fasterxml.aalto.io</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/WriterConfig.html#com.fasterxml.aalto.io">WriterConfig</a>
<div class="block">This is the shared configuration object passed by the factory to writer.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.aalto.out">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../com/fasterxml/aalto/out/package-summary.html">com.fasterxml.aalto.out</a> used by <a href="../../../../com/fasterxml/aalto/out/package-summary.html">com.fasterxml.aalto.out</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/ByteXmlWriter.html#com.fasterxml.aalto.out">ByteXmlWriter</a>
<div class="block">This abstract base class (partial implementation of <a href="../../../../com/fasterxml/aalto/out/XmlWriter.html" title="class in com.fasterxml.aalto.out"><code>XmlWriter</code></a>)
is used if the destination is byte-based <a href="https://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io"><code>OutputStream</code></a>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/SingleByteXmlWriter.html#com.fasterxml.aalto.out">SingleByteXmlWriter</a>
<div class="block">This is the common base class for writers that output to byte-backed
output sources, and use Ascii or ISO-8859-1 (Latin1) encoding.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/StreamWriterBase.html#com.fasterxml.aalto.out">StreamWriterBase</a>
<div class="block">Base class for <a href="https://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLStreamReader.html?is-external=true" title="class or interface in javax.xml.stream"><code>XMLStreamReader</code></a> implementations.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/StreamWriterBase.State.html#com.fasterxml.aalto.out">StreamWriterBase.State</a> </td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/WName.html#com.fasterxml.aalto.out">WName</a>
<div class="block">This class is similar to <a href="../../../../com/fasterxml/aalto/in/PName.html" title="class in com.fasterxml.aalto.in"><code>PName</code></a>, in
that it implements an efficient representation of prefixed names,
but one used on output (Writer) side.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/WNameFactory.html#com.fasterxml.aalto.out">WNameFactory</a>
<div class="block">This abstract class defines factory object (with factory methods)
that are needed by <a href="../../../../com/fasterxml/aalto/out/WNameTable.html" title="class in com.fasterxml.aalto.out"><code>WNameTable</code></a> instances, to be able to
construct <a href="../../../../com/fasterxml/aalto/out/WName.html" title="class in com.fasterxml.aalto.out"><code>WName</code></a> instances for element and attribute names.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/WNameTable.html#com.fasterxml.aalto.out">WNameTable</a>
<div class="block">This is a symbol table implementation used for storing byte-based
<code>WName</code>s.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/WriterConfig.html#com.fasterxml.aalto.out">WriterConfig</a>
<div class="block">This is the shared configuration object passed by the factory to writer.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/XmlWriter.html#com.fasterxml.aalto.out">XmlWriter</a>
<div class="block">Base class for output type / encoding-specific serializers
used to do actual physical output of serialized xml content.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.aalto.stax">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../com/fasterxml/aalto/out/package-summary.html">com.fasterxml.aalto.out</a> used by <a href="../../../../com/fasterxml/aalto/stax/package-summary.html">com.fasterxml.aalto.stax</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../com/fasterxml/aalto/out/class-use/WriterConfig.html#com.fasterxml.aalto.stax">WriterConfig</a>
<div class="block">This is the shared configuration object passed by the factory to writer.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</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>Class</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-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/fasterxml/aalto/out/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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>Copyright © 2021 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "83685c4387628486a292e96fe94bffd3",
"timestamp": "",
"source": "github",
"line_count": 270,
"max_line_length": 276,
"avg_line_length": 43.81481481481482,
"alnum_prop": 0.6671174978867287,
"repo_name": "FasterXML/aalto-xml",
"id": "97ff55b4ac68c019ed8fb04e6499d5bab4d4f6a3",
"size": "11830",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/javadoc/1.3/com/fasterxml/aalto/out/package-use.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1911443"
}
],
"symlink_target": ""
} |
package janala.logger.inst;
public class LDC_Object extends Instruction {
public int c;
public LDC_Object(int iid, int mid, int c) {
super(iid, mid);
this.c = c;
}
public void visit(IVisitor visitor) {
visitor.visitLDC_Object(this);
}
@Override
public String toString() {
return "LDC_Object iid=" + iid + " mid=" + mid + " c=" + c;
}
}
| {
"content_hash": "d29366fb017d05d525c6730501dac7c4",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 63,
"avg_line_length": 18.65,
"alnum_prop": 0.6193029490616622,
"repo_name": "ksen007/janala2",
"id": "237407282a000228b6e3fdf38abb285a68876f10",
"size": "373",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/main/java/janala/logger/inst/LDC_Object.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Groovy",
"bytes": "246644"
},
{
"name": "HTML",
"bytes": "2163"
},
{
"name": "Java",
"bytes": "2578822"
},
{
"name": "Python",
"bytes": "9967"
},
{
"name": "Roff",
"bytes": "10556"
},
{
"name": "Shell",
"bytes": "6919"
}
],
"symlink_target": ""
} |
package de.knightsoftnet.validators.shared;
public class ResourcePaths {
public static final String API_BASE_DIR = "/api/";
public class PhoneNumber {
public static final String ROOT = "phonenumberservice";
public static final String PARSE_PHONE_NUMBER = "parsePhoneNumber";
public static final String PARSE_WITH_POS = "parsewithpos";
public static final String PARSE_AND_FORMAT = "parseandformat";
public static final String FORMAT_E123 = "formate123";
public static final String FORMAT_E123_WITH_POS = "formate123withpos";
public static final String FORMAT_E123_INTERNATIONAL = "formate123international";
public static final String FORMAT_E123_INTERNATIONAL_WITH_POS =
"formate123internationalwithpos";
public static final String FORMAT_E123_NATIONAL = "formate123national";
public static final String FORMAT_E123_NATIONAL_WITH_POS = "formate123nationalwithpos";
public static final String FORMAT_DIN5008 = "formatdin5008";
public static final String FORMAT_DIN5008_WITH_POS = "formatdin5008withpos";
public static final String FORMAT_DIN5008_INTERNATIONAL = "formatdin5008international";
public static final String FORMAT_DIN5008_INTERNATIONAL_WITH_POS =
"formatdin5008internationalwithpos";
public static final String FORMAT_DIN5008_NATIONAL = "formatdin5008national";
public static final String FORMAT_DIN5008_NATIONAL_WITH_POS = "formatdin5008nationalwithpos";
public static final String FORMAT_RFC3966 = "formatrfc3966";
public static final String FORMAT_RFC3966_WITH_POS = "formatrfc3966withpos";
public static final String FORMAT_MS = "formatms";
public static final String FORMAT_MS_WITH_POS = "formatmswithpos";
public static final String FORMAT_URL = "formaturl";
public static final String FORMAT_URL_WITH_POS = "formaturlwithpos";
public static final String FORMAT_COMMON = "formatcommon";
public static final String FORMAT_COMMON_WITH_POS = "formatcommonwithpos";
public static final String FORMAT_COMMON_INTERNATIONAL = "formatcommoninternational";
public static final String FORMAT_COMMON_INTERNATIONAL_WITH_POS =
"formatcommoninternationalwithpos";
public static final String FORMAT_COMMON_NATIONAL = "formatcommonnational";
public static final String FORMAT_COMMON_NATIONAL_WITH_POS = "formatcommonnationalwithpos";
public static final String GET_SUGGESTIONS = "getsuggestions";
public static final String VALIDATE = "validate";
}
}
| {
"content_hash": "06190fa3b93382e6d41a94eb016f8c21",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 97,
"avg_line_length": 56.97727272727273,
"alnum_prop": 0.7658556043079378,
"repo_name": "ManfredTremmel/gwt-bean-validators",
"id": "8b6f7679ba6fbbc41f5b97c57ef2f84a8049317b",
"size": "3296",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "gwt-bean-validators-restygwt-jaxrs/src/main/java/de/knightsoftnet/validators/shared/ResourcePaths.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "51"
},
{
"name": "Java",
"bytes": "3723881"
}
],
"symlink_target": ""
} |
package designpattern.behavioral.responsibilitychain;
public class Obj1 extends AbstractObj {
public Obj1(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("Object Level 1 : " + message);
}
} | {
"content_hash": "66cd55f0eb57dce843ff0b769f5d736f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 54,
"avg_line_length": 21.307692307692307,
"alnum_prop": 0.6787003610108303,
"repo_name": "dongdapeng2012/student",
"id": "c8b45fa483ed89854af9eaeea9c8a83902596acc",
"size": "277",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/designpattern/behavioral/responsibilitychain/Obj1.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "46572"
}
],
"symlink_target": ""
} |
var test = require('tape'),
inspector = require('../lib/inspector');
var rule_include_true = {
"rules": {
"include": "search"
},
"body": "search on google. search."
}
var rule_exclude_false = {
"rules": {
"exclude": "search"
},
"body": "try to search on google"
}
var rule_double_false = {
"rules": {
"exclude": "messenger",
"include": "not include"
},
"body": "double false body messenger"
}
var rule_double_true = {
"rules": {
"exclude": "exclude",
"include": "google"
},
"body": "facebook and google"
}
test('inspector', function(t){
t.plan(6);
var res_1 = inspector.checkValidity(
rule_include_true['body'], rule_include_true['rules']);
t.equal(res_1.include, true);
var res_2 = inspector.checkValidity(
rule_exclude_false['body'], rule_exclude_false['rules']);
t.equal(res_2.exclude, false);
var res_3 = inspector.checkValidity(
rule_double_false['body'], rule_double_false['rules']);
t.equal(res_3.include, false);
t.equal(res_3.exclude, false);
var res_4 = inspector.checkValidity(
rule_double_true['body'], rule_double_true['rules']);
t.equal(res_4.include, true);
t.equal(res_4.exclude, true);
});
| {
"content_hash": "fc480299217b58f41bdcd12d864cff0e",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 59,
"avg_line_length": 20.403508771929825,
"alnum_prop": 0.6440240756663801,
"repo_name": "gpestana/web_monitor",
"id": "ef44d039bff16ad063f676358f870f7d074a3bc7",
"size": "1163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "monitor/tests/inspector_include_exclude.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "90"
},
{
"name": "HTML",
"bytes": "2145"
},
{
"name": "JavaScript",
"bytes": "9256"
},
{
"name": "Shell",
"bytes": "371"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace MaterialDesignThemes.Wpf
{
[TemplateVisualState(GroupName = "CommonStates", Name = TemplateStateNormal)]
[TemplateVisualState(GroupName = "CommonStates", Name = TemplateStateMousePressed)]
[TemplateVisualState(GroupName = "CommonStates", Name = TemplateStateMouseOut)]
public class Ripple : ContentControl
{
public const string TemplateStateNormal = "Normal";
public const string TemplateStateMousePressed = "MousePressed";
public const string TemplateStateMouseOut = "MouseOut";
private static readonly HashSet<Ripple> PressedInstances = new HashSet<Ripple>();
static Ripple()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Ripple), new FrameworkPropertyMetadata(typeof(Ripple)));
EventManager.RegisterClassHandler(typeof(ContentControl), Mouse.PreviewMouseUpEvent, new MouseButtonEventHandler(MouseButtonEventHandler), true);
EventManager.RegisterClassHandler(typeof(ContentControl), Mouse.MouseMoveEvent, new MouseEventHandler(MouseMouveEventHandler), true);
EventManager.RegisterClassHandler(typeof(Popup), Mouse.PreviewMouseUpEvent, new MouseButtonEventHandler(MouseButtonEventHandler), true);
EventManager.RegisterClassHandler(typeof(Popup), Mouse.MouseMoveEvent, new MouseEventHandler(MouseMouveEventHandler), true);
}
public Ripple()
{
SizeChanged += OnSizeChanged;
}
private static void MouseButtonEventHandler(object sender, MouseButtonEventArgs e)
{
foreach (var ripple in PressedInstances)
{
// adjust the transition scale time according to the current animated scale
var scaleTrans = ripple.Template.FindName("ScaleTransform", ripple) as ScaleTransform;
if (scaleTrans != null)
{
double currentScale = scaleTrans.ScaleX;
var newTime = TimeSpan.FromMilliseconds(300 * (1.0 - currentScale));
// change the scale animation according to the current scale
var scaleXKeyFrame = ripple.Template.FindName("MousePressedToNormalScaleXKeyFrame", ripple) as EasingDoubleKeyFrame;
if (scaleXKeyFrame != null)
{
scaleXKeyFrame.KeyTime = KeyTime.FromTimeSpan(newTime);
}
var scaleYKeyFrame = ripple.Template.FindName("MousePressedToNormalScaleYKeyFrame", ripple) as EasingDoubleKeyFrame;
if (scaleYKeyFrame != null) {
scaleYKeyFrame.KeyTime = KeyTime.FromTimeSpan(newTime);
}
}
VisualStateManager.GoToState(ripple, TemplateStateNormal, true);
}
PressedInstances.Clear();
}
private static void MouseMouveEventHandler(object sender, MouseEventArgs e)
{
foreach (var ripple in PressedInstances.ToList())
{
var relativePosition = Mouse.GetPosition(ripple);
if (relativePosition.X < 0
|| relativePosition.Y < 0
|| relativePosition.X >= ripple.ActualWidth
|| relativePosition.Y >= ripple.ActualHeight)
{
VisualStateManager.GoToState(ripple, TemplateStateMouseOut, true);
PressedInstances.Remove(ripple);
}
}
}
public static readonly DependencyProperty FeedbackProperty = DependencyProperty.Register(
nameof(Feedback), typeof(Brush), typeof(Ripple), new PropertyMetadata(default(Brush)));
public Brush Feedback
{
get { return (Brush)GetValue(FeedbackProperty); }
set { SetValue(FeedbackProperty, value); }
}
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
var point = e.GetPosition(this);
if (RippleAssist.GetIsCentered(this))
{
var innerContent = (Content as FrameworkElement);
if (innerContent != null)
{
var position = innerContent.TransformToAncestor(this)
.Transform(new Point(0, 0));
RippleX = position.X + innerContent.ActualWidth / 2 - RippleSize / 2;
RippleY = position.Y + innerContent.ActualHeight / 2 - RippleSize / 2;
}
else
{
RippleX = ActualWidth / 2 - RippleSize / 2;
RippleY = ActualHeight / 2 - RippleSize / 2;
}
}
else
{
RippleX = point.X - RippleSize / 2;
RippleY = point.Y - RippleSize / 2;
}
if (!RippleAssist.GetIsDisabled(this))
{
VisualStateManager.GoToState(this, TemplateStateNormal, false);
VisualStateManager.GoToState(this, TemplateStateMousePressed, true);
PressedInstances.Add(this);
}
base.OnPreviewMouseLeftButtonDown(e);
}
private static readonly DependencyPropertyKey RippleSizePropertyKey =
DependencyProperty.RegisterReadOnly(
"RippleSize", typeof(double), typeof(Ripple),
new PropertyMetadata(default(double)));
public static readonly DependencyProperty RippleSizeProperty =
RippleSizePropertyKey.DependencyProperty;
public double RippleSize
{
get { return (double)GetValue(RippleSizeProperty); }
private set { SetValue(RippleSizePropertyKey, value); }
}
private static readonly DependencyPropertyKey RippleXPropertyKey =
DependencyProperty.RegisterReadOnly(
"RippleX", typeof(double), typeof(Ripple),
new PropertyMetadata(default(double)));
public static readonly DependencyProperty RippleXProperty =
RippleXPropertyKey.DependencyProperty;
public double RippleX
{
get { return (double)GetValue(RippleXProperty); }
private set { SetValue(RippleXPropertyKey, value); }
}
private static readonly DependencyPropertyKey RippleYPropertyKey =
DependencyProperty.RegisterReadOnly(
"RippleY", typeof(double), typeof(Ripple),
new PropertyMetadata(default(double)));
public static readonly DependencyProperty RippleYProperty =
RippleYPropertyKey.DependencyProperty;
public double RippleY
{
get { return (double)GetValue(RippleYProperty); }
private set { SetValue(RippleYPropertyKey, value); }
}
/// <summary>
/// The DependencyProperty for the RecognizesAccessKey property.
/// Default Value: false
/// </summary>
public static readonly DependencyProperty RecognizesAccessKeyProperty =
DependencyProperty.Register(
nameof(RecognizesAccessKey), typeof(bool), typeof(Ripple),
new PropertyMetadata(default(bool)));
/// <summary>
/// Determine if Ripple should use AccessText in its style
/// </summary>
public bool RecognizesAccessKey
{
get { return (bool)GetValue(RecognizesAccessKeyProperty); }
set { SetValue(RecognizesAccessKeyProperty, value); }
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
VisualStateManager.GoToState(this, TemplateStateNormal, false);
}
private void OnSizeChanged(object sender, SizeChangedEventArgs sizeChangedEventArgs)
{
var innerContent = (Content as FrameworkElement);
double width, height;
if (RippleAssist.GetIsCentered(this) && innerContent != null)
{
width = innerContent.ActualWidth;
height = innerContent.ActualHeight;
}
else
{
width = sizeChangedEventArgs.NewSize.Width;
height = sizeChangedEventArgs.NewSize.Height;
}
var radius = Math.Sqrt(Math.Pow(width, 2) + Math.Pow(height, 2));
RippleSize = 2 * radius * RippleAssist.GetRippleSizeMultiplier(this);
}
}
}
| {
"content_hash": "926b240367a5bbd7c91d4e4a7a0d56f3",
"timestamp": "",
"source": "github",
"line_count": 220,
"max_line_length": 157,
"avg_line_length": 40.513636363636365,
"alnum_prop": 0.6008078088185796,
"repo_name": "DingpingZhang/MaterialDesignInXamlToolkit",
"id": "9eba9a56ef10554efcd22ac5816eaec483438962",
"size": "8915",
"binary": false,
"copies": "12",
"ref": "refs/heads/for-accelerider",
"path": "MaterialDesignThemes.Wpf/Ripple.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1098005"
}
],
"symlink_target": ""
} |
<HTML>
<HEAD>
<meta charset="UTF-8">
<title>ONLPSentenceTrainer.done - biomedicus-core</title>
<link rel="stylesheet" href="../../../style.css">
</HEAD>
<BODY>
<a href="../../index.html">biomedicus-core</a> / <a href="../index.html">edu.umn.biomedicus.sentence</a> / <a href="index.html">ONLPSentenceTrainer</a> / <a href="./done.html">done</a><br/>
<br/>
<h1>done</h1>
<a name="edu.umn.biomedicus.sentence.ONLPSentenceTrainer$done()"></a>
<code><span class="keyword">open</span> <span class="keyword">fun </span><span class="identifier">done</span><span class="symbol">(</span><span class="symbol">)</span><span class="symbol">: </span><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html"><span class="identifier">Unit</span></a></code>
</BODY>
</HTML>
| {
"content_hash": "1ab6701f04860b6c9e9f4d8d46efba08",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 323,
"avg_line_length": 57.857142857142854,
"alnum_prop": 0.6802469135802469,
"repo_name": "NLPIE/BioMedICUS",
"id": "19970c0bb92098ff57cf2542adc9dedf6f1349dd",
"size": "810",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/dokka/biomedicus-core/edu.umn.biomedicus.sentence/-o-n-l-p-sentence-trainer/done.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1158577"
},
{
"name": "Shell",
"bytes": "1548"
}
],
"symlink_target": ""
} |
'use strict';
module.exports = function(/* environment, appConfig */) {
return {
"spree": {
apiHost: "http://localhost:3000",
namespace: "api/ams",
mount: "/",
productsPath: "products",
cartPath: "cart",
checkoutPath: "checkout",
ordersPath: "orders",
taxonsPath: "t"
}
};
};
| {
"content_hash": "39a2e5f64efdce2fbd59b6b337741803",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 57,
"avg_line_length": 21.125,
"alnum_prop": 0.5443786982248521,
"repo_name": "vulk/spree-ember",
"id": "c52e9884fa1a03897221397b6bf12b133234e934",
"size": "338",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "packages/storefront/config/environment.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "31"
},
{
"name": "HTML",
"bytes": "6296"
},
{
"name": "Handlebars",
"bytes": "38257"
},
{
"name": "JavaScript",
"bytes": "160939"
},
{
"name": "Ruby",
"bytes": "994"
}
],
"symlink_target": ""
} |
import {container} from "tsyringe";
import {Arg, SubstituteOf} from "@fluffy-spoon/substitute";
import {Mo} from "../test-support/Mo";
import {HtmlOptionsService} from "../../src/service/option/HtmlOptionsService";
import {OptionService} from "../../src/service/OptionService";
import {HtmlDocumentService} from "../../src/service/option/HtmlDocumentService";
import {HtmlStatusService} from "../../src/service/option/HtmlStatusService";
describe("OptionServiceTest", (): void => {
let testee: OptionService;
let htmlOptionsServiceMock: SubstituteOf<HtmlOptionsService>;
let htmlStatusServiceMock: SubstituteOf<HtmlStatusService>;
let htmlDocumentServiceMock: SubstituteOf<HtmlDocumentService>;
let assertOnStatusUpdate: (assert: () => void) => void = (assert: () => void)=>{};
beforeEach((): void => {
container.reset();
htmlOptionsServiceMock = Mo.injectMock(HtmlOptionsService);
htmlStatusServiceMock = Mo.injectMock(HtmlStatusService);
htmlDocumentServiceMock = Mo.injectMock(HtmlDocumentService);
testee = container.resolve(OptionService);
assertOnStatusUpdate = (assert: () => void) => {
expect.assertions(1);
htmlStatusServiceMock.showStatus(Arg.all()).mimicks(() => {
expect(true).toBeTruthy();
assert();
});
htmlDocumentServiceMock.onClick(Arg.any(), Arg.any()).mimicks((id, callback) => {
callback();
});
}
});
test("testShowAndHandleOptions", async (): Promise<void> => {
await testee.showAndHandleOptions();
htmlOptionsServiceMock.received(1).showOptionsHtml(Arg.any());
});
test("testShowAndHandleOptionsFailed", async (): Promise<void> => {
assertOnStatusUpdate(() => {
htmlOptionsServiceMock.received(1).showOptionsHtml(Arg.any());
htmlStatusServiceMock.received(1).showStatus(Arg.any(), Arg.any(), Arg.is((value) => Boolean(value)))
htmlStatusServiceMock.received(0).showStatus(Arg.any(), Arg.any(), Arg.is((value) => value === undefined))
});
htmlOptionsServiceMock.showOptionsHtml(Arg.any()).throws(new Error("test"));
await testee.showAndHandleOptions();
});
test("testShowAndHandleOptionsClickSaveSuccess", async (): Promise<void> => {
assertOnStatusUpdate(() => {
htmlOptionsServiceMock.received(1).showOptionsHtml(Arg.any());
htmlOptionsServiceMock.received(1).saveUpdatedOptions(Arg.any());
htmlStatusServiceMock.received(1).showStatus(Arg.any(), Arg.any(), Arg.is((value) => value === undefined));
});
htmlOptionsServiceMock.saveUpdatedOptions(Arg.any()).resolves();
htmlOptionsServiceMock.manageUrlPermissions(Arg.any()).resolves(true);
await testee.showAndHandleOptions();
});
test("testShowAndHandleOptionsClickSaveFailed", async (): Promise<void> => {
assertOnStatusUpdate(() => {
htmlOptionsServiceMock.received(1).showOptionsHtml(Arg.any());
htmlOptionsServiceMock.received(1).saveUpdatedOptions(Arg.any());
htmlStatusServiceMock.received(1).showStatus(Arg.any(), Arg.any(), Arg.is((value) => Boolean(value)))
htmlStatusServiceMock.received(0).showStatus(Arg.any(), Arg.any(), Arg.is((value) => value === undefined));
});
htmlOptionsServiceMock.saveUpdatedOptions(Arg.any()).throws(new Error("test"));
htmlOptionsServiceMock.manageUrlPermissions(Arg.any()).resolves(true);
await testee.showAndHandleOptions();
});
test("testShowAndHandleOptionsClickSavePermissionsNotGranted", async (): Promise<void> => {
assertOnStatusUpdate(() => {
htmlOptionsServiceMock.received(1).showOptionsHtml(Arg.any());
htmlOptionsServiceMock.didNotReceive().saveUpdatedOptions(Arg.any());
htmlStatusServiceMock.received(1).showStatus(Arg.any(), Arg.any(), Arg.is((value) => Boolean(value)))
htmlStatusServiceMock.didNotReceive().showStatus(Arg.any(), Arg.any(), Arg.is((value) => value === undefined));
});
htmlOptionsServiceMock.manageUrlPermissions(Arg.any()).resolves(false);
await testee.showAndHandleOptions();
});
test("testShowAndHandleOptionsClickSavePermissionsFailed", async (): Promise<void> => {
assertOnStatusUpdate(() => {
htmlOptionsServiceMock.received(1).showOptionsHtml(Arg.any());
htmlOptionsServiceMock.didNotReceive().saveUpdatedOptions(Arg.any());
htmlStatusServiceMock.received(1).showStatus(Arg.any(), Arg.any(), Arg.is((value) => Boolean(value)))
htmlStatusServiceMock.didNotReceive().showStatus(Arg.any(), Arg.any(), Arg.is((value) => value === undefined));
});
htmlOptionsServiceMock.manageUrlPermissions(Arg.any()).throws(new Error(""));
await testee.showAndHandleOptions();
});
});
| {
"content_hash": "3676454cb0c06def0c121c3938d006d9",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 123,
"avg_line_length": 44.990990990990994,
"alnum_prop": 0.65778934721666,
"repo_name": "gasserus/github-download-helper-chrome",
"id": "66e4cd0ceb443020a636a6fab8851f5f1f735463",
"size": "4994",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/service/OptionService.test.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "733"
},
{
"name": "TypeScript",
"bytes": "34271"
}
],
"symlink_target": ""
} |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework.task;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.*;
import org.apache.logging.log4j.core.config.Configurator;
import org.junit.*;
import generic.concurrent.GThreadPool;
import generic.test.AbstractGenericTest;
import ghidra.framework.model.UndoableDomainObject;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.TaskMonitor;
public class GTaskTest extends AbstractGenericTest {
private GenericDomainObjectDB domainObject;
private GTaskManager gTaskManager;
private List<GTaskResult> taskResults = new ArrayList<GTaskResult>();
private GTaskListener listener = new GTaskListenerAdapter() {
@Override
public void taskCompleted(GScheduledTask task, GTaskResult result) {
taskResults.add(result);
}
};
public GTaskTest() {
super();
}
@Before
public void setUp() throws IOException {
domainObject = new GenericDomainObjectDB(this);
GThreadPool threadPool = GThreadPool.getSharedThreadPool("Test Thread Pool");
gTaskManager = new GTaskManager(domainObject, threadPool);
gTaskManager.addTaskListener(listener);
}
@After
public void tearDown() {
domainObject.release(this);
}
@Test
public void testRunOneTask() {
SimpleTask task = new SimpleTask("Task 1");
gTaskManager.scheduleTask(task, 5, true);
waitForTaskManager();
assertTrue("Task did not run!", task.didRun());
assertTrue(domainObject.currentTransaction == null);
assertTrue(domainObject.transactionsList.size() == 1);
assertEquals("Task 1", domainObject.transactionsList.get(0));
}
@Test
public void testRunTwoTasksSameTransaction() {
LatchedTask task1 = new LatchedTask("Task 1");
SimpleTask task2 = new SimpleTask("Task 2");
gTaskManager.scheduleTask(task1, 1, true);
gTaskManager.scheduleTask(task2, 2, true);
task1.latch.countDown();
waitForTaskManager();
assertTrue("Task did not run!", task1.didRun());
assertTrue("Task did not run!", task2.didRun());
assertTrue(domainObject.currentTransaction == null);
assertTrue(domainObject.transactionsList.size() == 1);
assertEquals("Task 1", domainObject.transactionsList.get(0));
}
@Test
public void testRunTwoTaskDifferentTransactions() {
LatchedTask task1 = new LatchedTask("Task 1");
SimpleTask task2 = new SimpleTask("Task 2");
gTaskManager.scheduleTask(task1, 1, true);
gTaskManager.scheduleTask(task2, 2, false);
task1.latch.countDown();
waitForTaskManager();
assertTrue("Task did not run!", task1.didRun());
assertTrue("Task did not run!", task2.didRun());
assertTrue(domainObject.currentTransaction == null);
assertTrue(domainObject.transactionsList.size() == 2);
assertEquals("Task 1", domainObject.transactionsList.get(0));
assertEquals("Task 2", domainObject.transactionsList.get(1));
}
@Test
public void testNewTransactionGroupWithoutNewTransaction() {
LatchedTask task1 = new LatchedTask("Task 1");
gTaskManager.scheduleTask(task1, 1, true);
GTaskGroup group = new GTaskGroup("Group", false);
SimpleTask task2 = new SimpleTask("Task 2");
group.addTask(task2, 4);
gTaskManager.scheduleTaskGroup(group);
task1.latch.countDown();
waitForTaskManager();
assertTrue("Task did not run!", task1.didRun());
assertTrue("Task did not run!", task2.didRun());
assertTrue(domainObject.currentTransaction == null);
assertEquals(1, domainObject.transactionsList.size());
assertEquals("Task 1", domainObject.transactionsList.get(0));
}
@Test
public void testNewTransactionGroupWithNewTransaction() {
LatchedTask task1 = new LatchedTask("Task 1");
gTaskManager.scheduleTask(task1, 1, true);
GTaskGroup group = new GTaskGroup("Group", true);
SimpleTask task2 = new SimpleTask("Task 2");
group.addTask(task2, 4);
gTaskManager.scheduleTaskGroup(group);
task1.latch.countDown();
waitForTaskManager();
assertTrue("Task did not run!", task1.didRun());
assertTrue("Task did not run!", task2.didRun());
assertTrue(domainObject.currentTransaction == null);
assertTrue(domainObject.transactionsList.size() == 2);
assertEquals("Task 1", domainObject.transactionsList.get(0));
assertEquals("Group", domainObject.transactionsList.get(1));
}
@Test
public void testSuspendBeforeSchedulingTasks() {
gTaskManager.setSuspended(true);
SimpleTask task = new SimpleTask("Task 1");
gTaskManager.scheduleTask(task, 5, true);
waitForRunningTaskManager();
assertTrue(!task.didRun);
gTaskManager.setSuspended(false);
waitForTaskManager();
assertTrue(task.didRun);
}
@Test
public void testSuspendWhileRunningTasks() {
LatchedTask task = new LatchedTask("Task 1");
SimpleTask task2 = new SimpleTask("test 2");
gTaskManager.scheduleTask(task, 5, true);
gTaskManager.scheduleTask(task2, 10, true);
gTaskManager.setSuspended(true);
gTaskManager.scheduleTask(task, DEFAULT_WAIT_DELAY, BATCH_MODE);
assertTrue(!task.didRun());
task.latch.countDown();
waitForRunningTaskManager();
assertTrue(task.didRun());
assertTrue(!task2.didRun());
gTaskManager.setSuspended(false);
waitForTaskManager();
assertTrue(task2.didRun());
}
@Test
public void testIsBusy() {
assertTrue(!gTaskManager.isBusy());
LatchedTask task = new LatchedTask("Task 1");
gTaskManager.scheduleTask(task, 3, true);
assertTrue(gTaskManager.isBusy());
assertTrue(gTaskManager.isRunning());
gTaskManager.setSuspended(true);
gTaskManager.scheduleTask(new SimpleTask("Task 2"), 4, true);
task.latch.countDown();
waitForRunningTaskManager();
assertTrue(gTaskManager.isBusy());
gTaskManager.scheduleTask(new SimpleTask("Task 3"), 4, false);
gTaskManager.runNextTaskEvenWhenSuspended();
waitForRunningTaskManager();
assertTrue(gTaskManager.isBusy());
gTaskManager.runNextTaskEvenWhenSuspended();
waitForRunningTaskManager();
assertTrue(!gTaskManager.isBusy());
}
@Test
public void testWaitForHigherPriorityTasks() {
LatchedTask task = new LatchedTask("Task 1");
gTaskManager.scheduleTask(task, 10, true);
gTaskManager.scheduleTask(new YieldingTask("Task 2"), 10, true);
gTaskManager.scheduleTask(new SimpleTask("Task 3"), 1, true);
gTaskManager.scheduleTask(new SimpleTask("Task 4"), 2, true);
gTaskManager.scheduleTask(new SimpleTask("Task 5"), 11, true);
task.latch.countDown();
waitForTaskManager();
assertEquals(5, taskResults.size());
assertEquals("Task 1", taskResults.get(0).getDescription());
assertEquals("Task 3", taskResults.get(1).getDescription());
assertEquals("Task 4", taskResults.get(2).getDescription());
assertEquals("Task 2", taskResults.get(3).getDescription());
assertEquals("Task 5", taskResults.get(4).getDescription());
}
@Test
public void testSuspendWhileYielding() {
LatchedTask task = new LatchedTask("Task 1");
gTaskManager.scheduleTask(task, 10, true);
gTaskManager.scheduleTask(new YieldingTask("Task 2"), 10, true);
gTaskManager.scheduleTask(new SimpleTask("Task 3"), 2, true);
gTaskManager.scheduleTask(new SimpleTask("Task 4"), 2, true);
gTaskManager.scheduleTask(new SimpleTask("Task 5"), 11, true);
gTaskManager.setSuspended(true);
task.latch.countDown();
waitForRunningTaskManager();
assertEquals(1, taskResults.size());
assertEquals("Task 1", taskResults.get(0).getDescription());
gTaskManager.setSuspended(false);
waitForTaskManager();
assertEquals(5, taskResults.size());
assertEquals("Task 1", taskResults.get(0).getDescription());
assertEquals("Task 3", taskResults.get(1).getDescription());
assertEquals("Task 4", taskResults.get(2).getDescription());
assertEquals("Task 2", taskResults.get(3).getDescription());
assertEquals("Task 5", taskResults.get(4).getDescription());
}
@Test
public void testSuspendAndSingleSteppingWhileYielding() {
LatchedTask task = new LatchedTask("Task 1");
gTaskManager.scheduleTask(task, 10, true);
gTaskManager.scheduleTask(new YieldingTask("Task 2"), 10, true);
gTaskManager.scheduleTask(new SimpleTask("Task 3"), 2, true);
gTaskManager.scheduleTask(new SimpleTask("Task 4"), 3, true);
gTaskManager.scheduleTask(new SimpleTask("Task 5"), 11, true);
gTaskManager.setSuspended(true);
task.latch.countDown();
waitForRunningTaskManager();
assertEquals(1, taskResults.size());
assertEquals("Task 1", taskResults.get(0).getDescription());
gTaskManager.runNextTaskEvenWhenSuspended();
waitForRunningTaskManager();
assertEquals(2, taskResults.size());
assertEquals("Task 3", taskResults.get(1).getDescription());
gTaskManager.runNextTaskEvenWhenSuspended();
waitForRunningTaskManager();
assertEquals(3, taskResults.size());
assertEquals("Task 4", taskResults.get(2).getDescription());
gTaskManager.runNextTaskEvenWhenSuspended();
waitForRunningTaskManager();
assertEquals(4, taskResults.size());
assertEquals("Task 2", taskResults.get(3).getDescription());
gTaskManager.runNextTaskEvenWhenSuspended();
waitForRunningTaskManager();
assertEquals(5, taskResults.size());
assertEquals("Task 5", taskResults.get(4).getDescription());
gTaskManager.runNextTaskEvenWhenSuspended();
waitForRunningTaskManager();
assertEquals(5, taskResults.size());
}
@Test
public void testPriority() {
gTaskManager.setSuspended(true);
gTaskManager.scheduleTask(new SimpleTask("Test 1"), 3, true);
gTaskManager.scheduleTask(new SimpleTask("Test 2"), 1, true);
gTaskManager.scheduleTask(new SimpleTask("Test 3"), 2, true);
gTaskManager.setSuspended(false);
waitForTaskManager();
assertEquals("Test 2", taskResults.get(0).getDescription());
assertEquals("Test 3", taskResults.get(1).getDescription());
assertEquals("Test 1", taskResults.get(2).getDescription());
}
@Test
public void testCancelTask() {
LatchedTask task1 = new LatchedTask("Task 1");
SimpleTask task2 = new SimpleTask("Task 2");
gTaskManager.scheduleTask(task1, 1, true);
gTaskManager.scheduleTask(task2, 2, true);
cancelCurrentTask();
task1.latch.countDown();
waitForTaskManager();
assertTrue("Task was not cancelled!", !task1.didRun());
assertTrue("Task did not run!", task2.didRun());
}
@Test
public void testCancelGroup() {
LatchedTask task1 = new LatchedTask("Task 1");
SimpleTask task2 = new SimpleTask("Task 2");
gTaskManager.scheduleTask(task1, 1, true);
gTaskManager.scheduleTask(task2, 2, true);
cancelCurrentGroup();
task1.latch.countDown();
waitForTaskManager();
assertTrue("Running Task was not cancelled!", !task1.didRun());
assertTrue("Waiting Task was not cancelled!", !task2.didRun());
}
@Test
public void testCancelAll() {
LatchedTask task1 = new LatchedTask("Task 1");
SimpleTask task2 = new SimpleTask("Task 2");
gTaskManager.scheduleTask(task1, 1, true);
gTaskManager.scheduleTask(task2, 2, true);
GTaskGroup group = new GTaskGroup("Group", true);
SimpleTask task3 = new SimpleTask("Task 3");
SimpleTask task4 = new SimpleTask("Task 4");
group.addTask(task3, 4);
group.addTask(task4, 4);
gTaskManager.scheduleTaskGroup(group);
gTaskManager.cancelAll();
task1.latch.countDown();
waitForTaskManager();
assertTrue("Running Task was not cancelled!", !task1.didRun());
assertTrue("Waiting Task was not cancelled!", !task2.didRun());
assertTrue("Running Task was not cancelled!", !task3.didRun());
assertTrue("Waiting Task was not cancelled!", !task4.didRun());
List<GTaskResult> results = gTaskManager.getTaskResults();
assertEquals(4, results.size());
for (GTaskResult gTaskResult : results) {
assertTrue(gTaskResult.wasCancelled());
}
}
@Test
public void testAddingTaskByGroupNameToRunningGroup() {
LatchedTask task1 = new LatchedTask("Task 1");
gTaskManager.scheduleTask(task1, 10, "GROUP1");
gTaskManager.scheduleTask(new SimpleTask("Task 2"), 20, "GROUP1");
assertTrue(domainObject.transactionsList.size() == 0);
task1.latch.countDown();
waitForTaskManager();
assertTrue(domainObject.transactionsList.size() == 1);
assertEquals("GROUP1", domainObject.transactionsList.get(0));
List<GTaskResult> results = gTaskManager.getTaskResults();
assertEquals(2, results.size());
}
@Test
public void testAddingTaskByGroupNameToWaitingGroup() {
LatchedTask task1 = new LatchedTask("Task 1");
gTaskManager.scheduleTask(task1, 10, "GROUP1");
GTaskGroup group = new GTaskGroup("GROUP2", true);
SimpleTask task3 = new SimpleTask("Task 3");
SimpleTask task4 = new SimpleTask("Task 4");
group.addTask(task3, 10);
group.addTask(task4, 10);
gTaskManager.scheduleTaskGroup(group);
gTaskManager.scheduleTask(new SimpleTask("Task 5"), 20, "GROUP2");
List<GTaskGroup> scheduledGroups = gTaskManager.getScheduledGroups();
assertEquals(1, scheduledGroups.size());
assertEquals(3, scheduledGroups.get(0).getTasks().size());
task1.latch.countDown();
waitForTaskManager();
assertTrue(domainObject.transactionsList.size() == 2);
assertEquals("GROUP1", domainObject.transactionsList.get(0));
assertEquals("GROUP2", domainObject.transactionsList.get(1));
List<GTaskResult> results = gTaskManager.getTaskResults();
assertEquals(4, results.size());
}
@Test
public void testAddingTaskByGroupNameToNonExistingGroup() {
LatchedTask task1 = new LatchedTask("Task 1");
gTaskManager.scheduleTask(task1, 10, "GROUP1");
gTaskManager.scheduleTask(new SimpleTask("Task 5"), 20, "GROUP2");
List<GTaskGroup> scheduledGroups = gTaskManager.getScheduledGroups();
assertEquals(1, scheduledGroups.size());
assertEquals(1, scheduledGroups.get(0).getTasks().size());
task1.latch.countDown();
waitForTaskManager();
assertTrue(domainObject.transactionsList.size() == 2);
assertEquals("GROUP1", domainObject.transactionsList.get(0));
assertEquals("GROUP2", domainObject.transactionsList.get(1));
List<GTaskResult> results = gTaskManager.getTaskResults();
assertEquals(2, results.size());
}
@Test
public void testExceptionInTaskListenerTaskCompleted() {
// disable printing of exception below
Logger logger = LogManager.getLogger(GTaskManager.class);
Configurator.setLevel(logger.getName(), Level.OFF);
gTaskManager.addTaskListener(new GTaskListenerAdapter() {
@Override
public void taskCompleted(GScheduledTask task, GTaskResult result) {
throw new RuntimeException("Test Exception");
}
});
gTaskManager.scheduleTask(new SimpleTask("Task 5"), 20, true);
// this is testing that the exception does cause the taskManager to timeout still busy
waitForTaskManager();
Configurator.setLevel(logger.getName(), Level.DEBUG);
}
@Test
public void testExceptionInTaskListenerTaskStarted() {
// disable printing of exception below
Logger logger = LogManager.getLogger(GTaskManager.class);
Configurator.setLevel(logger.getName(), Level.OFF);
gTaskManager.addTaskListener(new GTaskListenerAdapter() {
@Override
public void taskStarted(GScheduledTask task) {
throw new RuntimeException("Test Exception");
}
});
gTaskManager.scheduleTask(new SimpleTask("Task 5"), 20, true);
// this is testing that the exception does cause the taskManager to timeout still busy
waitForTaskManager();
Configurator.setLevel(logger.getName(), Level.DEBUG);
}
private void cancelCurrentTask() {
GScheduledTask runningTask = gTaskManager.getRunningTask();
runningTask.getTaskMonitor().cancel();
}
private void cancelCurrentGroup() {
gTaskManager.cancelRunningGroup(gTaskManager.getCurrentGroup());
}
private void waitForTaskManager() {
assertTrue(gTaskManager.waitWhileBusy(1000));
assertFalse(gTaskManager.isBusy());
}
private void waitForRunningTaskManager() {
while (gTaskManager.isRunning()) {
sleep(10);
}
}
private class LatchedTask extends SimpleTask {
CountDownLatch latch = new CountDownLatch(1);
LatchedTask(String name) {
super(name);
}
@Override
public void run(UndoableDomainObject obj, TaskMonitor monitor) throws CancelledException {
try {
if (!latch.await(2, TimeUnit.SECONDS)) {
Assert.fail("Latch await expired!");
}
}
catch (InterruptedException e) {
Assert.fail("Did not expect Interrupted Exception");
}
monitor.checkCanceled();
super.run(obj, monitor);
}
}
private class YieldingTask extends SimpleTask {
YieldingTask(String name) {
super(name);
}
@Override
public void run(UndoableDomainObject obj, TaskMonitor monitor) throws CancelledException {
GTaskManager taskManager = GTaskManagerFactory.getTaskManager(obj);
taskManager.waitForHigherPriorityTasks();
super.run(obj, monitor);
}
}
}
| {
"content_hash": "cd2254073b5a5175543f9a8dcc170ffe",
"timestamp": "",
"source": "github",
"line_count": 518,
"max_line_length": 92,
"avg_line_length": 33.24131274131274,
"alnum_prop": 0.7435971891515186,
"repo_name": "NationalSecurityAgency/ghidra",
"id": "73dade7bae41c3b1650b8e57ff7b0df1f2c39681",
"size": "17219",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ghidra/Framework/Project/src/test/java/ghidra/framework/task/GTaskTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "77536"
},
{
"name": "Batchfile",
"bytes": "21610"
},
{
"name": "C",
"bytes": "1132868"
},
{
"name": "C++",
"bytes": "7334484"
},
{
"name": "CSS",
"bytes": "75788"
},
{
"name": "GAP",
"bytes": "102771"
},
{
"name": "GDB",
"bytes": "3094"
},
{
"name": "HTML",
"bytes": "4121163"
},
{
"name": "Hack",
"bytes": "31483"
},
{
"name": "Haskell",
"bytes": "453"
},
{
"name": "Java",
"bytes": "88669329"
},
{
"name": "JavaScript",
"bytes": "1109"
},
{
"name": "Lex",
"bytes": "22193"
},
{
"name": "Makefile",
"bytes": "15883"
},
{
"name": "Objective-C",
"bytes": "23937"
},
{
"name": "Pawn",
"bytes": "82"
},
{
"name": "Python",
"bytes": "587415"
},
{
"name": "Shell",
"bytes": "234945"
},
{
"name": "TeX",
"bytes": "54049"
},
{
"name": "XSLT",
"bytes": "15056"
},
{
"name": "Xtend",
"bytes": "115955"
},
{
"name": "Yacc",
"bytes": "127754"
}
],
"symlink_target": ""
} |
using UnityEngine;
using UnityEditor;
using System.Collections;
using StrayTech.CustomAttributes;
namespace StrayTech
{
/// <summary>
///
/// </summary>
[CustomPropertyDrawer(typeof(NonNegativeAttribute))]
public class NonNegativeAttributePropertyDrawer : PropertyDrawer
{
#region methods
/// <summary>
/// Prevent the value from being changed to negative.
/// </summary>
/// <param name="position"></param>
/// <param name="property"></param>
/// <param name="label"></param>
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.showMixedValue = property.hasMultipleDifferentValues;
if (property.propertyType == SerializedPropertyType.Float)
{
EditorGUI.BeginChangeCheck();
var value = EditorGUI.FloatField(position, property.name.NiceifyPropertyName(), property.floatValue);
if (value < 0)
{
value = 0;
}
if (EditorGUI.EndChangeCheck() == true)
{
property.floatValue = value;
property.serializedObject.ApplyModifiedProperties();
}
}
else if (property.propertyType == SerializedPropertyType.Integer)
{
EditorGUI.BeginChangeCheck();
var value = EditorGUI.IntField(position, property.name.NiceifyPropertyName(), property.intValue);
if (value < 0)
{
value = 0;
}
if (EditorGUI.EndChangeCheck() == true)
{
property.intValue = value;
property.serializedObject.ApplyModifiedProperties();
}
}
else
{
//Did not specify attribute over a float or int member..
base.OnGUI(position, property, label);
}
EditorGUI.showMixedValue = false;
}
#endregion methods
}
} | {
"content_hash": "0cf8d3556bcd97a2ff3428d1b36a20b2",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 121,
"avg_line_length": 33.95652173913044,
"alnum_prop": 0.4899701237729407,
"repo_name": "supertms/WolongYin",
"id": "0e78cb13535a572f4751d83d2b17f67a32367e89",
"size": "2345",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "project/client/Assets/StrayTech/Camera System/Scripts/Common/Attributes/Editor/NonNegativeAttributePropertyDrawer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "972"
},
{
"name": "C#",
"bytes": "3106422"
},
{
"name": "GLSL",
"bytes": "601969"
},
{
"name": "HTML",
"bytes": "36728"
},
{
"name": "Objective-C",
"bytes": "4421"
},
{
"name": "Objective-C++",
"bytes": "683"
},
{
"name": "Protocol Buffer",
"bytes": "20439"
},
{
"name": "XSLT",
"bytes": "165830"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.2.xsd">
<changeSet id="1" author="Gilles Zimmermann">
<createTable tableName="USER">
<column name="ID" type="VARCHAR(255)">
<constraints nullable="false" primaryKey="true" primaryKeyName="USER_PK"/>
</column>
<column name="VERSION" type="NUMBER(19,0)"/>
<column name="CREATED" type="DATETIME"/>
<column name="NAME" type="VARCHAR(255)"/>
<column name="USER_ID" type="VARCHAR(10)"/>
<column name="EMAIL" type="VARCHAR(255)"/>
<column name="EMAIL_SENT" type="BOOLEAN"/>
<column name="RETRY_COUNT" type="INTEGER"/>
</createTable>
<!-- Sequence -->
<createSequence sequenceName="USER_SEQ"
incrementBy="1" startValue="1"/>
</changeSet>
</databaseChangeLog>
| {
"content_hash": "866f11799b644268c3bf8a0c3dd983fd",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 148,
"avg_line_length": 47.28,
"alnum_prop": 0.5854483925549916,
"repo_name": "SchweizerischeBundesbahnen/conference-buddy",
"id": "6e9d71972f9dc39bdfbb5731754ac69f798f1444",
"size": "1182",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "server/conferencebuddy-persistence/src/main/resources/changelog/changelog-user.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3357"
},
{
"name": "HTML",
"bytes": "21371"
},
{
"name": "Java",
"bytes": "73743"
},
{
"name": "JavaScript",
"bytes": "67469"
},
{
"name": "Shell",
"bytes": "959"
}
],
"symlink_target": ""
} |
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.7.6.1">
<compounddef id="follow__helpers_8hpp" kind="file">
<compoundname>follow_helpers.hpp</compoundname>
<includes refid="assert_8hpp" local="no">boost/geometry/core/assert.hpp</includes>
<includes refid="condition_8hpp" local="no">boost/geometry/util/condition.hpp</includes>
<includes refid="util_2range_8hpp" local="no">boost/geometry/util/range.hpp</includes>
<includedby refid="relate_2areal__areal_8hpp" local="no">/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/relate/areal_areal.hpp</includedby>
<includedby refid="relate_2linear__areal_8hpp" local="no">/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/relate/linear_areal.hpp</includedby>
<includedby refid="relate_2linear__linear_8hpp" local="no">/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/relate/linear_linear.hpp</includedby>
<incdepgraph>
<node id="33245">
<label>boost/range/empty.hpp</label>
</node>
<node id="33239">
<label>iterator</label>
</node>
<node id="33244">
<label>boost/range/end.hpp</label>
</node>
<node id="33240">
<label>boost/concept_check.hpp</label>
</node>
<node id="33247">
<label>boost/range/iterator.hpp</label>
</node>
<node id="33233">
<label>boost/geometry/core/assert.hpp</label>
<link refid="assert_8hpp"/>
<childnode refid="33234" relation="include">
</childnode>
</node>
<node id="33232">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/relate/follow_helpers.hpp</label>
<link refid="follow_helpers.hpp"/>
<childnode refid="33233" relation="include">
</childnode>
<childnode refid="33235" relation="include">
</childnode>
<childnode refid="33237" relation="include">
</childnode>
</node>
<node id="33243">
<label>boost/range/begin.hpp</label>
</node>
<node id="33246">
<label>boost/range/difference_type.hpp</label>
</node>
<node id="33237">
<label>boost/geometry/util/range.hpp</label>
<link refid="util_2range_8hpp"/>
<childnode refid="33238" relation="include">
</childnode>
<childnode refid="33239" relation="include">
</childnode>
<childnode refid="33240" relation="include">
</childnode>
<childnode refid="33236" relation="include">
</childnode>
<childnode refid="33241" relation="include">
</childnode>
<childnode refid="33242" relation="include">
</childnode>
<childnode refid="33243" relation="include">
</childnode>
<childnode refid="33244" relation="include">
</childnode>
<childnode refid="33245" relation="include">
</childnode>
<childnode refid="33246" relation="include">
</childnode>
<childnode refid="33247" relation="include">
</childnode>
<childnode refid="33248" relation="include">
</childnode>
<childnode refid="33249" relation="include">
</childnode>
<childnode refid="33250" relation="include">
</childnode>
<childnode refid="33251" relation="include">
</childnode>
<childnode refid="33252" relation="include">
</childnode>
<childnode refid="33233" relation="include">
</childnode>
<childnode refid="33253" relation="include">
</childnode>
</node>
<node id="33255">
<label>boost/type_traits/remove_reference.hpp</label>
</node>
<node id="33234">
<label>boost/assert.hpp</label>
</node>
<node id="33242">
<label>boost/range/concepts.hpp</label>
</node>
<node id="33249">
<label>boost/range/reference.hpp</label>
</node>
<node id="33241">
<label>boost/core/addressof.hpp</label>
</node>
<node id="33235">
<label>boost/geometry/util/condition.hpp</label>
<link refid="condition_8hpp"/>
<childnode refid="33236" relation="include">
</childnode>
</node>
<node id="33252">
<label>boost/type_traits/is_convertible.hpp</label>
</node>
<node id="33251">
<label>boost/range/value_type.hpp</label>
</node>
<node id="33254">
<label>cstddef</label>
</node>
<node id="33236">
<label>boost/config.hpp</label>
</node>
<node id="33253">
<label>boost/geometry/core/mutable_range.hpp</label>
<link refid="mutable__range_8hpp"/>
<childnode refid="33254" relation="include">
</childnode>
<childnode refid="33251" relation="include">
</childnode>
<childnode refid="33255" relation="include">
</childnode>
</node>
<node id="33250">
<label>boost/range/size.hpp</label>
</node>
<node id="33238">
<label>algorithm</label>
</node>
<node id="33248">
<label>boost/range/rbegin.hpp</label>
</node>
</incdepgraph>
<invincdepgraph>
<node id="33266">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/buffer/turn_in_piece_visitor.hpp</label>
<link refid="turn__in__piece__visitor_8hpp"/>
<childnode refid="33263" relation="include">
</childnode>
</node>
<node id="33289">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/intersection/interface.hpp</label>
<link refid="intersection_2interface_8hpp"/>
<childnode refid="33290" relation="include">
</childnode>
<childnode refid="33291" relation="include">
</childnode>
<childnode refid="33293" relation="include">
</childnode>
</node>
<node id="33275">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/has_spikes.hpp</label>
<link refid="has__spikes_8hpp"/>
<childnode refid="33272" relation="include">
</childnode>
<childnode refid="33276" relation="include">
</childnode>
<childnode refid="33279" relation="include">
</childnode>
</node>
<node id="33258">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/relate/implementation.hpp</label>
<link refid="relate_2implementation_8hpp"/>
<childnode refid="33259" relation="include">
</childnode>
<childnode refid="33298" relation="include">
</childnode>
</node>
<node id="33277">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/implementation.hpp</label>
<link refid="is__valid_2implementation_8hpp"/>
<childnode refid="33278" relation="include">
</childnode>
</node>
<node id="33292">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/intersection/implementation.hpp</label>
<link refid="intersection_2implementation_8hpp"/>
<childnode refid="33290" relation="include">
</childnode>
</node>
<node id="33268">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/distance/implementation.hpp</label>
<link refid="distance_2implementation_8hpp"/>
<childnode refid="33269" relation="include">
</childnode>
<childnode refid="33270" relation="include">
</childnode>
</node>
<node id="33297">
<label>/home/travis/build/boostorg/boost/boost/geometry/strategies/strategies.hpp</label>
<link refid="strategies_8hpp"/>
</node>
<node id="33290">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/intersection.hpp</label>
<link refid="algorithms_2intersection_8hpp"/>
<childnode refid="33286" relation="include">
</childnode>
</node>
<node id="33298">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/relation/implementation.hpp</label>
<link refid="relation_2implementation_8hpp"/>
<childnode refid="33299" relation="include">
</childnode>
</node>
<node id="33261">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/equals.hpp</label>
<link refid="equals_8hpp"/>
<childnode refid="33262" relation="include">
</childnode>
<childnode refid="33266" relation="include">
</childnode>
<childnode refid="33267" relation="include">
</childnode>
<childnode refid="33272" relation="include">
</childnode>
<childnode refid="33275" relation="include">
</childnode>
<childnode refid="33276" relation="include">
</childnode>
<childnode refid="33279" relation="include">
</childnode>
<childnode refid="33282" relation="include">
</childnode>
<childnode refid="33283" relation="include">
</childnode>
</node>
<node id="33284">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/linear_linear.hpp</label>
<link refid="overlay_2linear__linear_8hpp"/>
<childnode refid="33285" relation="include">
</childnode>
<childnode refid="33287" relation="include">
</childnode>
</node>
<node id="33256">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/relate/follow_helpers.hpp</label>
<link refid="follow_helpers.hpp"/>
<childnode refid="33257" relation="include">
</childnode>
<childnode refid="33300" relation="include">
</childnode>
<childnode refid="33301" relation="include">
</childnode>
</node>
<node id="33283">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/turns/remove_duplicate_turns.hpp</label>
<link refid="remove__duplicate__turns_8hpp"/>
<childnode refid="33284" relation="include">
</childnode>
</node>
<node id="33276">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/linear.hpp</label>
<link refid="is__valid_2linear_8hpp"/>
<childnode refid="33277" relation="include">
</childnode>
</node>
<node id="33273">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_simple/implementation.hpp</label>
<link refid="is__simple_2implementation_8hpp"/>
<childnode refid="33274" relation="include">
</childnode>
</node>
<node id="33271">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/comparable_distance.hpp</label>
<link refid="comparable__distance_8hpp"/>
<childnode refid="33263" relation="include">
</childnode>
<childnode refid="33266" relation="include">
</childnode>
</node>
<node id="33260">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/crosses.hpp</label>
<link refid="crosses_8hpp"/>
</node>
<node id="33285">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/union.hpp</label>
<link refid="union_8hpp"/>
<childnode refid="33286" relation="include">
</childnode>
</node>
<node id="33287">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/intersection_insert.hpp</label>
<link refid="intersection__insert_8hpp"/>
<childnode refid="33288" relation="include">
</childnode>
<childnode refid="33289" relation="include">
</childnode>
</node>
<node id="33281">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/multipolygon.hpp</label>
<link refid="multipolygon_8hpp"/>
<childnode refid="33277" relation="include">
</childnode>
</node>
<node id="33263">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/buffer/buffered_piece_collection.hpp</label>
<link refid="buffered__piece__collection_8hpp"/>
<childnode refid="33264" relation="include">
</childnode>
</node>
<node id="33280">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/polygon.hpp</label>
<link refid="algorithms_2detail_2is__valid_2polygon_8hpp"/>
<childnode refid="33277" relation="include">
</childnode>
<childnode refid="33281" relation="include">
</childnode>
</node>
<node id="33279">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/ring.hpp</label>
<link refid="algorithms_2detail_2is__valid_2ring_8hpp"/>
<childnode refid="33277" relation="include">
</childnode>
<childnode refid="33280" relation="include">
</childnode>
</node>
<node id="33257">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/relate/areal_areal.hpp</label>
<link refid="relate_2areal__areal_8hpp"/>
<childnode refid="33258" relation="include">
</childnode>
</node>
<node id="33288">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/difference.hpp</label>
<link refid="difference_8hpp"/>
</node>
<node id="33293">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/intersection/multi.hpp</label>
<link refid="multi_8hpp"/>
<childnode refid="33292" relation="include">
</childnode>
</node>
<node id="33286">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/sym_difference.hpp</label>
<link refid="sym__difference_8hpp"/>
</node>
<node id="33264">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/buffer/buffer_inserter.hpp</label>
<link refid="buffer__inserter_8hpp"/>
<childnode refid="33265" relation="include">
</childnode>
</node>
<node id="33301">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/relate/linear_linear.hpp</label>
<link refid="relate_2linear__linear_8hpp"/>
<childnode refid="33258" relation="include">
</childnode>
</node>
<node id="33265">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/buffer.hpp</label>
<link refid="algorithms_2buffer_8hpp"/>
</node>
<node id="33262">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/buffer/get_piece_turns.hpp</label>
<link refid="get__piece__turns_8hpp"/>
<childnode refid="33263" relation="include">
</childnode>
</node>
<node id="33299">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/relation.hpp</label>
<link refid="relation_8hpp"/>
</node>
<node id="33295">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/touches.hpp</label>
<link refid="touches_8hpp"/>
</node>
<node id="33296">
<label>/home/travis/build/boostorg/boost/boost/geometry/strategies/agnostic/relate.hpp</label>
<link refid="strategies_2agnostic_2relate_8hpp"/>
<childnode refid="33297" relation="include">
</childnode>
</node>
<node id="33269">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/distance.hpp</label>
<link refid="algorithms_2distance_8hpp"/>
</node>
<node id="33270">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/comparable_distance/implementation.hpp</label>
<link refid="comparable__distance_2implementation_8hpp"/>
<childnode refid="33271" relation="include">
</childnode>
</node>
<node id="33259">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/relate.hpp</label>
<link refid="algorithms_2relate_8hpp"/>
<childnode refid="33260" relation="include">
</childnode>
<childnode refid="33261" relation="include">
</childnode>
<childnode refid="33294" relation="include">
</childnode>
<childnode refid="33295" relation="include">
</childnode>
<childnode refid="33296" relation="include">
</childnode>
</node>
<node id="33278">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/is_valid.hpp</label>
<link refid="is__valid_8hpp"/>
</node>
<node id="33272">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_simple/linear.hpp</label>
<link refid="is__simple_2linear_8hpp"/>
<childnode refid="33273" relation="include">
</childnode>
</node>
<node id="33274">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/is_simple.hpp</label>
<link refid="is__simple_8hpp"/>
</node>
<node id="33282">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/segment.hpp</label>
<link refid="algorithms_2detail_2is__valid_2segment_8hpp"/>
<childnode refid="33277" relation="include">
</childnode>
</node>
<node id="33267">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/distance/segment_to_box.hpp</label>
<link refid="segment__to__box_8hpp"/>
<childnode refid="33268" relation="include">
</childnode>
</node>
<node id="33294">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/overlaps.hpp</label>
<link refid="overlaps_8hpp"/>
</node>
<node id="33291">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/intersection/box_box.hpp</label>
<link refid="intersection_2box__box_8hpp"/>
<childnode refid="33292" relation="include">
</childnode>
</node>
<node id="33300">
<label>/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/relate/linear_areal.hpp</label>
<link refid="relate_2linear__areal_8hpp"/>
<childnode refid="33258" relation="include">
</childnode>
</node>
</invincdepgraph>
<innernamespace refid="namespaceboost">boost</innernamespace>
<innernamespace refid="namespaceboost_1_1geometry">boost::geometry</innernamespace>
<briefdescription>
</briefdescription>
<detaileddescription>
</detaileddescription>
<location file="/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/relate/follow_helpers.hpp"/>
</compounddef>
</doxygen>
| {
"content_hash": "c6e1e0395ee8f6fa54c7ef936cd5bdcf",
"timestamp": "",
"source": "github",
"line_count": 456,
"max_line_length": 167,
"avg_line_length": 42.23684210526316,
"alnum_prop": 0.6244548286604361,
"repo_name": "hsu1994/Terminator",
"id": "3255815bffe81b4b8184c4b91e8e7a384a8d4250",
"size": "19260",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Server/RelyON/boost_1_61_0/libs/geometry/doc/doxy/doxygen_output/xml/follow__helpers_8hpp.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "223360"
},
{
"name": "Batchfile",
"bytes": "43670"
},
{
"name": "C",
"bytes": "3717232"
},
{
"name": "C#",
"bytes": "12172138"
},
{
"name": "C++",
"bytes": "188465965"
},
{
"name": "CMake",
"bytes": "119765"
},
{
"name": "CSS",
"bytes": "430770"
},
{
"name": "Cuda",
"bytes": "52444"
},
{
"name": "DIGITAL Command Language",
"bytes": "6246"
},
{
"name": "FORTRAN",
"bytes": "1856"
},
{
"name": "GLSL",
"bytes": "143058"
},
{
"name": "Groff",
"bytes": "5189"
},
{
"name": "HTML",
"bytes": "234253948"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "JavaScript",
"bytes": "694216"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "M4",
"bytes": "29689"
},
{
"name": "Makefile",
"bytes": "1459789"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "15456"
},
{
"name": "Objective-C++",
"bytes": "630"
},
{
"name": "PHP",
"bytes": "59030"
},
{
"name": "Perl",
"bytes": "38649"
},
{
"name": "Perl6",
"bytes": "2053"
},
{
"name": "Protocol Buffer",
"bytes": "409987"
},
{
"name": "Python",
"bytes": "1764372"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Ruby",
"bytes": "5532"
},
{
"name": "Shell",
"bytes": "362208"
},
{
"name": "Smalltalk",
"bytes": "2796"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "32117"
},
{
"name": "XSLT",
"bytes": "265714"
},
{
"name": "Yacc",
"bytes": "19623"
}
],
"symlink_target": ""
} |
package org.apache.jackrabbit.oak.plugins.document;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import javax.management.openmbean.CompositeData;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import org.apache.jackrabbit.api.stats.RepositoryStatistics;
import org.apache.jackrabbit.api.stats.TimeSeries;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.commons.jmx.AnnotatedStandardMBean;
import org.apache.jackrabbit.oak.plugins.document.util.Utils;
import org.apache.jackrabbit.stats.TimeSeriesStatsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.toArray;
import static com.google.common.collect.Iterables.transform;
/**
* Implementation of a DocumentNodeStoreMBean.
*/
final class DocumentNodeStoreMBeanImpl extends AnnotatedStandardMBean implements DocumentNodeStoreMBean {
private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
private static final TimeZone TZ_UTC = TimeZone.getTimeZone("UTC");
private static final String COMPOSITE_INFO = "composite.checkpoint.";
private final DocumentNodeStore nodeStore;
private final RepositoryStatistics repoStats;
private final Iterable<ClusterNodeInfoDocument> clusterNodes;
private final long revisionGCMaxAgeMillis;
private final Logger log = LoggerFactory.getLogger(this.getClass());
DocumentNodeStoreMBeanImpl(DocumentNodeStore nodeStore,
RepositoryStatistics repoStats,
Iterable<ClusterNodeInfoDocument> clusterNodes,
long revisionGCMaxAgeMillis) {
super(DocumentNodeStoreMBean.class);
this.nodeStore = nodeStore;
this.repoStats = repoStats;
this.clusterNodes = clusterNodes;
this.revisionGCMaxAgeMillis = revisionGCMaxAgeMillis;
}
@Override
public String getRevisionComparatorState() {
return "";
}
@Override
public String getHead() {
return nodeStore.getHeadRevision().toString();
}
@Override
public int getClusterId() {
return nodeStore.getClusterId();
}
@Override
public int getUnmergedBranchCount() {
return nodeStore.getBranches().size();
}
@Override
public String[] getInactiveClusterNodes() {
return toArray(transform(filter(clusterNodes,
new Predicate<ClusterNodeInfoDocument>() {
@Override
public boolean apply(ClusterNodeInfoDocument input) {
return !input.isActive();
}
}), new Function<ClusterNodeInfoDocument, String>() {
@Override
public String apply(ClusterNodeInfoDocument input) {
return input.getClusterId() + "=" + input.getCreated();
}
}), String.class);
}
@Override
public String[] getActiveClusterNodes() {
return toArray(transform(filter(clusterNodes,
new Predicate<ClusterNodeInfoDocument>() {
@Override
public boolean apply(ClusterNodeInfoDocument input) {
return input.isActive();
}
}), new Function<ClusterNodeInfoDocument, String>() {
@Override
public String apply(ClusterNodeInfoDocument input) {
return input.getClusterId() + "=" + input.getLeaseEndTime();
}
}), String.class);
}
@Override
public String[] getLastKnownRevisions() {
return toArray(transform(filter(nodeStore.getHeadRevision(),
new Predicate<Revision>() {
@Override
public boolean apply(Revision input) {
return input.getClusterId() != getClusterId();
}
}), new Function<Revision, String>() {
@Override
public String apply(Revision input) {
return input.getClusterId() + "=" + input.toString();
}
}), String.class);
}
@Override
public String formatRevision(String rev, boolean utc) {
Revision r = Revision.fromString(rev);
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
if (utc) {
sdf.setTimeZone(TZ_UTC);
}
return sdf.format(r.getTimestamp());
}
@Override
public long determineServerTimeDifferenceMillis() {
return nodeStore.getDocumentStore().determineServerTimeDifferenceMillis();
}
@Override
public CompositeData getMergeSuccessHistory() {
return getTimeSeriesData(DocumentNodeStoreStats.MERGE_SUCCESS_COUNT,
"Merge Success Count");
}
@Override
public CompositeData getMergeFailureHistory() {
return getTimeSeriesData(DocumentNodeStoreStats.MERGE_FAILED_EXCLUSIVE,
"Merge failure count");
}
@Override
public CompositeData getExternalChangeCountHistory() {
return getTimeSeriesData(DocumentNodeStoreStats.BGR_NUM_CHANGES_RATE,
"Count of nodes modified by other " +
"cluster nodes since last background read");
}
@Override
public CompositeData getBackgroundUpdateCountHistory() {
return getTimeSeriesData(DocumentNodeStoreStats.BGW_NUM_WRITES_RATE,
"Count of nodes updated as part of " +
"background update");
}
@Override
public CompositeData getBranchCommitHistory() {
return getTimeSeriesData(DocumentNodeStoreStats.BRANCH_COMMIT_COUNT,
"Branch commit count");
}
@Override
public CompositeData getMergeBranchCommitHistory() {
return getTimeSeriesData(DocumentNodeStoreStats.MERGE_BRANCH_COMMIT_COUNT,
"Number of merged branch commits");
}
private CompositeData getTimeSeriesData(String name, String desc) {
return TimeSeriesStatsUtil.asCompositeData(getTimeSeries(name), desc);
}
private TimeSeries getTimeSeries(String name) {
return repoStats.getTimeSeries(name, true);
}
@Override
public int recover(String path, int clusterId) {
checkNotNull(path, "path must not be null");
checkArgument(PathUtils.isAbsolute(path), "path must be absolute");
checkArgument(clusterId >= 0, "clusterId must not be a negative");
DocumentStore docStore = nodeStore.getDocumentStore();
boolean isActive = false;
for (ClusterNodeInfoDocument it : ClusterNodeInfoDocument.all(docStore)) {
if (it.getClusterId() == clusterId && it.isActive()) {
isActive = true;
}
}
if (isActive) {
throw new IllegalStateException(
"Cannot run recover on clusterId " + clusterId + " as it's currently active");
}
String p = path;
NodeDocument nodeDocument = docStore.find(Collection.NODES, Utils.getIdFromPath(p));
if(nodeDocument == null) {
throw new DocumentStoreException("Document node with given path = " + p + " does not exist");
}
boolean dryRun = nodeStore.isReadOnlyMode();
int sum = 0;
for (;;) {
log.info("Running recovery on child documents of path = " + p);
List<NodeDocument> childDocs = getChildDocs(p);
sum += nodeStore.getLastRevRecoveryAgent().recover(childDocs, clusterId, dryRun);
if (PathUtils.denotesRoot(p)) {
break;
}
p = PathUtils.getParentPath(p);
}
return sum;
}
private List<NodeDocument> getChildDocs(String path) {
Path pathRef = Path.fromString(path);
final String to = Utils.getKeyUpperLimit(pathRef);
final String from = Utils.getKeyLowerLimit(pathRef);
return nodeStore.getDocumentStore().query(Collection.NODES, from, to, 10000);
}
@Override
public String cleanAllCaches() {
nodeStore.getDiffCache().invalidateAll();
nodeStore.getNodeCache().invalidateAll();
nodeStore.getNodeChildrenCache().invalidateAll();
nodeStore.getDocumentStore().invalidateCache();
return "Caches invalidated.";
}
@Override
public String cleanIndividualCache(String name) {
switch(name.toUpperCase()) {
case "DIFF":
nodeStore.getDiffCache().invalidateAll();
return "DiffCache invalidated.";
case "NODE":
nodeStore.getNodeCache().invalidateAll();
return "NodeCache invalidated.";
case "NODECHILDREN":
nodeStore.getNodeChildrenCache().invalidateAll();
return "NodeChildrenCache invalidated.";
case "DOCUMENT":
nodeStore.getDocumentStore().invalidateCache();
return "DocumentCache invalidated.";
default:
return "ERROR: Invalid cache name received.";
}
}
@Override
public String createCheckpoint(String revision, long lifetime, boolean force) {
Revision rev = Revision.fromString(revision);
long oldestTimestamp = nodeStore.getClock().getTime() - revisionGCMaxAgeMillis;
Revision oldestCheckpoint = nodeStore.getCheckpoints().getOldestRevisionToKeep();
if (oldestCheckpoint != null) {
oldestTimestamp = Math.min(oldestTimestamp, oldestCheckpoint.getTimestamp());
}
if (force || oldestTimestamp < rev.getTimestamp()) {
Map<String, String> info = new HashMap<>();
// Below properties are only needed when the DocumentNodeStore is
// used in a composite NodeStore setup. This is a bit ugly because
// it introduces a dependency on an implementation detail of the
// CompositeNodeStore implementation. The module oak-it therefore
// has a CompositeCheckpointTest to prevent a regression should the
// implementation ever change.
info.put(COMPOSITE_INFO + "created", Long.toString(rev.getTimestamp()));
info.put(COMPOSITE_INFO + "expires", Long.toString(Utils.sum(rev.getTimestamp() + lifetime)));
String cp = nodeStore.getCheckpoints().create(lifetime, info, rev).toString();
log.info("Created checkpoint [{}] with lifetime {} for Revision {}", cp, lifetime, revision);
return String.format("Created checkpoint [%s] with lifetime %d for Revision %s", cp, lifetime, revision);
} else {
throw new IllegalArgumentException(String.format("Cannot create a checkpoint for revision %s. " +
"Revision timestamp is %d and oldest timestamp to keep is %d",
revision, rev.getTimestamp(), oldestTimestamp));
}
}
}
| {
"content_hash": "78e2a37dd41ed70d9da410bb52a5961c",
"timestamp": "",
"source": "github",
"line_count": 290,
"max_line_length": 117,
"avg_line_length": 38.43103448275862,
"alnum_prop": 0.6460296096904441,
"repo_name": "mreutegg/jackrabbit-oak",
"id": "de00b0d21ae504c029f358bf388b86c077e9de71",
"size": "11947",
"binary": false,
"copies": "3",
"ref": "refs/heads/trunk",
"path": "oak-store-document/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStoreMBeanImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "24043"
},
{
"name": "Groovy",
"bytes": "146403"
},
{
"name": "HTML",
"bytes": "1406"
},
{
"name": "Java",
"bytes": "33142102"
},
{
"name": "JavaScript",
"bytes": "43898"
},
{
"name": "Perl",
"bytes": "7585"
},
{
"name": "Rich Text Format",
"bytes": "64887"
},
{
"name": "Shell",
"bytes": "18524"
}
],
"symlink_target": ""
} |
> A radial progress bar component for Vue.js. Uses SVG and javascript to animate a radial progress bar with a gradient.
# Requirements
- [Vue.js](https://github.com/vuejs/vue) `^1.0.0` (Compatible with Vue 1.0 or 2.0)
- A module bundler such as [webpack](https://github.com/webpack/webpack) or use the minified version on its own.
# Installation
``` bash
$ npm install --save vue-radial-progress
```
# Usage
``` html
<template>
<radial-progress-bar :diameter="200"
:completed-steps="completedSteps"
:total-steps="totalSteps">
<p>Total steps: {{ totalSteps }}</p>
<p>Completed steps: {{ completedSteps }}</p>
</radial-progress-bar>
</template>
<script>
import RadialProgressBar from 'vue-radial-progress'
export default {
data () {
return {
completedSteps: 0,
totalSteps: 10
}
},
components: {
RadialProgressBar
}
}
</script>
```
# Props
Name | Default value | Description
---|:---:|---
`diameter` | `200` | Diameter of the progress bar circle in pixels.
`totalSteps` | `10` | Total number of steps to complete progress bar.
`completedSteps` | `0` | Number of completed steps in the progress bar.
`startColor` | `#bbff42` | The color of the leading edge of the progress bar gradient.
`stopColor` | `#429321` | The secondary color of the progress bar gradient.
`innerStrokeColor` | `#323232` | Background color of the progress bar.
`strokeWidth` | `10` | The width of the progress bar.
`animateSpeed` | `1000` | The amount of time in milliseconds to animate one step.
`fps` | `60` | The frames per second that the animation should run.
`timingFunc` | `linear` | The transition timing function to use for the CSS transition. See [transition-timing-function](https://developer.mozilla.org/en-US/docs/Web/CSS/transition-timing-function).
# Lint
> npm run lint
# Dev
> npm run dev
# License
[The MIT License](LICENSE)
| {
"content_hash": "a3eb6206f00941ed0cd6fd59103d0798",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 198,
"avg_line_length": 28.235294117647058,
"alnum_prop": 0.6817708333333333,
"repo_name": "hezhongchen09/vue-radial-progress",
"id": "0a4cf960b5245cdffa5c7a7399209f78e6e14bc4",
"size": "1943",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "4258"
},
{
"name": "JavaScript",
"bytes": "1339"
},
{
"name": "Vue",
"bytes": "17296"
}
],
"symlink_target": ""
} |
package com.github.pedrovgs.kuronometer.free.algebra
import cats.free.{Free, Inject}
import com.github.pedrovgs.kuronometer.KuronometerResults.KuronometerResult
import com.github.pedrovgs.kuronometer.free.domain.{
BuildExecution,
Report,
SummaryBuildStagesExecution
}
sealed trait ReporterOp[A]
final case class ReportBuildExecution(buildExecution: BuildExecution,
report: Report)
extends ReporterOp[KuronometerResult[BuildExecution]]
final case class GetTotalBuildExecution()
extends ReporterOp[KuronometerResult[SummaryBuildStagesExecution]]
final case class GetTodayBuildExecution()
extends ReporterOp[KuronometerResult[SummaryBuildStagesExecution]]
class ReporterOps[F[_]](implicit I: Inject[ReporterOp, F]) {
def reportBuildExecution[A](
buildExecution: BuildExecution,
reporter: Report): Free[F, KuronometerResult[BuildExecution]] =
Free.inject[ReporterOp, F](ReportBuildExecution(buildExecution, reporter))
def getTotalBuildExecution[A]
: Free[F, KuronometerResult[SummaryBuildStagesExecution]] =
Free.inject[ReporterOp, F](GetTotalBuildExecution())
def getTodayBuildExecution[A]
: Free[F, KuronometerResult[SummaryBuildStagesExecution]] =
Free.inject[ReporterOp, F](GetTodayBuildExecution())
}
object ReporterOps {
implicit def R[F[_]](implicit I: Inject[ReporterOp, F]): ReporterOps[F] =
new ReporterOps[F]
}
| {
"content_hash": "cfdb5bc09fa49d689a803e7517aa48cf",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 78,
"avg_line_length": 34.80487804878049,
"alnum_prop": 0.767344078486335,
"repo_name": "pedrovgs/Kuronometer",
"id": "a122f60c6cfc6382d83746bbc0cd1500a27adc44",
"size": "1427",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kuronometer-core/src/main/scala/com/github/pedrovgs/kuronometer/free/algebra/ReporterOps.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "5056"
},
{
"name": "Scala",
"bytes": "69008"
}
],
"symlink_target": ""
} |
package com.googlecode.blaisemath.graph.test;
import com.google.common.base.Functions;
import com.google.common.graph.Graph;
import com.googlecode.blaisemath.geom.Points;
import com.googlecode.blaisemath.graph.generate.EdgeLikelihoodGenerator;
import com.googlecode.blaisemath.graph.generate.EdgeLikelihoodGenerator.EdgeLikelihoodParameters;
import com.googlecode.blaisemath.graph.layout.CircleLayout;
import com.googlecode.blaisemath.graph.layout.CircleLayout.CircleLayoutParameters;
import com.googlecode.blaisemath.graph.layout.RandomBoxLayout;
import com.googlecode.blaisemath.graph.layout.RandomBoxLayout.BoxLayoutParameters;
import com.googlecode.blaisemath.graph.layout.SpringLayout;
import com.googlecode.blaisemath.graph.layout.SpringLayoutParameters;
import com.googlecode.blaisemath.graph.view.GraphComponent;
import com.googlecode.blaisemath.graph.view.VisualGraph;
import com.googlecode.blaisemath.graphics.Graphic;
import com.googlecode.blaisemath.graphics.swing.PanAndZoomHandler;
import com.googlecode.blaisemath.style.Styles;
import com.googlecode.blaisemath.util.Instrument;
import com.googlecode.blaisemath.util.swing.CanvasPainter;
import com.googlecode.blaisemath.firestarter.editor.EditorRegistration;
import com.googlecode.blaisemath.firestarter.property.PropertySheet;
import com.googlecode.blaisemath.firestarter.swing.RollupPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
@SuppressWarnings("ALL")
public class GraphTestFrame extends javax.swing.JFrame {
VisualGraph pga;
/** Flag for when el needs points updated */
private boolean updateEL = true;
private SpringLayout energyLayout;
private final SpringLayoutParameters layoutParams;
/** Creates new form TestPlaneVisometry */
private GraphTestFrame() {
EditorRegistration.registerEditors();
initComponents();
// BASIC ELEMENTS
final Graph<Integer> graph = new EdgeLikelihoodGenerator().apply(new EdgeLikelihoodParameters(false, 50, .05f));
plot.setGraph(graph);
plot.getAdapter().getViewGraph().setPointSelectionEnabled(true);
plot.getAdapter().getViewGraph().setDragEnabled(true);
plot.getLayoutManager().applyLayout(CircleLayout.getInstance(), null, new CircleLayoutParameters(100.0));
PanAndZoomHandler.zoomBoxAnimated(plot, Points.boundingBox(plot.getLayoutManager().getNodeLocationCopy().values(), 5));
plot.getAdapter().getNodeStyler().setStyleDelegate(o -> Styles.DEFAULT_POINT_STYLE.copy()
.and(Styles.FILL, Color.lightGray)
.and(Styles.STROKE, Color.gray)
.and(Styles.STROKE_WIDTH, .5f)
.and(Styles.MARKER_RADIUS, 2+Math.sqrt((Integer) o)));
plot.getAdapter().getNodeStyler().setLabelDelegate(Functions.toStringFunction());
plot.addContextMenuInitializer("Graph", (menu, src, point, focus, selection) -> {
if (menu.getComponentCount() > 0) {
menu.addSeparator();
}
if (focus != null) {
menu.add("Graph Focus: " + focus);
}
menu.add("Selection: " + (selection == null ? 0 : selection.size()) + " selected items");
});
plot.addContextMenuInitializer("Node", (menu, src, point, focus, selection) -> {
if (menu.getComponentCount() > 0) {
menu.addSeparator();
}
if (focus != null) {
menu.add("Node: " + focus);
}
});
plot.addContextMenuInitializer("Edge", (menu, src, point, focus, selection) -> {
if (menu.getComponentCount() > 0) {
menu.addSeparator();
}
if (focus != null) {
menu.add("Edge: " + focus);
}
});
// PANELS
energyLayout = new SpringLayout();
layoutParams = energyLayout.createParameters();
rollupPanel1.add("Energy Layout", PropertySheet.forBean(layoutParams));
for (Graphic p : plot.getGraphicRoot().getGraphics()) {
rollupPanel1.add(p.toString(), PropertySheet.forBean(p));
}
addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e) {
Instrument.print(System.out, 50);
}
});
// OVERLAY
plot.getOverlays().add((CanvasPainter<Graphics2D>) (component, canvas) -> {
canvas.setColor(Color.black);
canvas.drawLine(50, 50, 150, 50);
canvas.drawLine(50, 40, 50, 60);
canvas.drawLine(150, 40, 150, 60);
});
plot.getSelectionModel().addPropertyChangeListener(evt -> selectionL.setText(String.format("<html><b>Selection:</b> %s", evt.getNewValue())));
}
/** 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() {
jToolBar1 = new javax.swing.JToolBar();
randomLB = new javax.swing.JButton();
circleLB = new javax.swing.JButton();
jSeparator1 = new javax.swing.JToolBar.Separator();
jLabel1 = new javax.swing.JLabel();
energyIB = new javax.swing.JButton();
energyAB = new javax.swing.JButton();
energySB = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
rollupPanel1 = new RollupPanel();
plot = new GraphComponent();
selectionL = new JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(0, 0, 0));
jToolBar1.setRollover(true);
randomLB.setText("Random Layout");
randomLB.setFocusable(false);
randomLB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
randomLB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
randomLB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
randomLBActionPerformed(evt);
}
});
jToolBar1.add(randomLB);
circleLB.setText("Circle Layout");
circleLB.setFocusable(false);
circleLB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
circleLB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
circleLB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
circleLBActionPerformed(evt);
}
});
jToolBar1.add(circleLB);
jToolBar1.add(jSeparator1);
jLabel1.setText("ENERGY:");
jToolBar1.add(jLabel1);
energyIB.setText("iterate");
energyIB.setFocusable(false);
energyIB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
energyIB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
energyIB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
energyIBActionPerformed(evt);
}
});
jToolBar1.add(energyIB);
energyAB.setText("animate");
energyAB.setFocusable(false);
energyAB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
energyAB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
energyAB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
energyABActionPerformed(evt);
}
});
jToolBar1.add(energyAB);
energySB.setText("stop");
energySB.setFocusable(false);
energySB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
energySB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
energySB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
energySBActionPerformed(evt);
}
});
jToolBar1.add(energySB);
getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START);
jScrollPane1.setViewportView(rollupPanel1);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.EAST);
getContentPane().add(plot, java.awt.BorderLayout.CENTER);
getContentPane().add(selectionL, BorderLayout.SOUTH);
pack();
}// </editor-fold>//GEN-END:initComponents
private void randomLBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_randomLBActionPerformed
updateEL = true;
double d = SpringLayoutParameters.DEFAULT_DIST_SCALE*2;
plot.getLayoutManager().applyLayout(RandomBoxLayout.getInstance(), null, new BoxLayoutParameters(new Rectangle2D.Double(-d, -d, 2*d, 2*d)));
}//GEN-LAST:event_randomLBActionPerformed
private void circleLBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_circleLBActionPerformed
updateEL = true;
plot.getLayoutManager().applyLayout(CircleLayout.getInstance(), null, new CircleLayoutParameters(SpringLayoutParameters.DEFAULT_DIST_SCALE*2));
}//GEN-LAST:event_circleLBActionPerformed
private void energyIBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_energyIBActionPerformed
if (energyLayout == null) {
energyLayout = new SpringLayout();
}
plot.getLayoutManager().setLayoutAlgorithm(energyLayout);
plot.getLayoutManager().setLayoutParameters(layoutParams);
plot.getLayoutManager().iterateLayout();
updateEL = false;
}//GEN-LAST:event_energyIBActionPerformed
private void energyABActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_energyABActionPerformed
if (energyLayout == null) {
energyLayout = new SpringLayout();
}
plot.getLayoutManager().setLayoutAlgorithm(energyLayout);
plot.getLayoutManager().setLayoutParameters(layoutParams);
plot.getLayoutManager().setLayoutTaskActive(true);
}//GEN-LAST:event_energyABActionPerformed
private void energySBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_energySBActionPerformed
plot.getLayoutManager().setLayoutTaskActive(false);
}//GEN-LAST:event_energySBActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(() -> new GraphTestFrame().setVisible(true));
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton circleLB;
private javax.swing.JButton energyAB;
private javax.swing.JButton energyIB;
private javax.swing.JButton energySB;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JToolBar.Separator jSeparator1;
private javax.swing.JToolBar jToolBar1;
private GraphComponent plot;
private javax.swing.JButton randomLB;
private RollupPanel rollupPanel1;
private JLabel selectionL;
// End of variables declaration//GEN-END:variables
}
| {
"content_hash": "7555f95c847dc153c68721c3c4590910",
"timestamp": "",
"source": "github",
"line_count": 270,
"max_line_length": 151,
"avg_line_length": 43.24444444444445,
"alnum_prop": 0.6797704693388147,
"repo_name": "triathematician/blaisemath",
"id": "ae66e4be1dd878a93d5c8b630c905a9f7561f0c1",
"size": "12332",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blaise-graph-theory-ui/src/test/java/com/googlecode/blaisemath/graph/test/GraphTestFrame.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1445045"
}
],
"symlink_target": ""
} |
<?php
use yii\helpers\Html;
use yii\helpers\Url;
?>
<div class="centrBoxText"> <p>МосСпецТранс – это портал, где встречаются арендаторы и владельцы спецтехники широкого профиля.
На этой площадке частные лица и компании дают объявления о найме спецтехники, позволяющем успешно решать задачи в сфере строительства,
реконструкции и ремонта. Если вас интересует аренда спецтехники в Москве и Московской области или вы сами готовы предоставить технические средства в прокат,
мы поможем вам подобрать наиболее оптимальные решения и разместить интересные предложения.</p>
</div>
<div class="centrBoxText">
<h2>Востребованные единицы</h2>
</div>
<?php if (!empty($category)):?>
<?php foreach ($category as $categori):?>
<a href="<?= Url::to(['category/view', 'id' => $categori->id])?>">
<div class="categorii">
<div class="NameCategori"><?= $categori ->name?></div>
<div class="ImgCategori"><?= Html::img("@web/images/$categori->img", ['alt' =>$categori->name])?></div>
</div>
</a>
<?php endforeach; ?>
<?php else:?>
Категорий не найдено
<?php endif; ?>
<div class="clear"></div>
<div class="centrBoxText">
<p>Наш сайт гарантирует следующие возможности и преимущества:
<ul type="disc">
<li>Удобный структурированный по категориям каталог;</li>
<li>Четко работающая система быстрого поиска;</li>
<li>Возможность публиковать объявления и делать запрос на конкретную разновидность спецтехники;</li>
<li>Простая регистрация с перспективой отслеживания статистики в личном кабинете;</li>
<li>Отсутствие платы за предоставляемые услуги.</li>
</ul>
Наш проект с каждым днем охватывает все больше вариантов аренды строительной техники в Москве и Московской области.<br>
Благодаря ему вы сможете оперативно отыскать предложение, которое устроит вас по всем знаковым позициям.
</p></div> | {
"content_hash": "92b0c0a2121e0c7b41ab4e1ef1e475e2",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 168,
"avg_line_length": 49.256410256410255,
"alnum_prop": 0.69807391983342,
"repo_name": "gromm2010/www",
"id": "6a5c13f717fd210263a48d107109ec3f6dd33855",
"size": "2873",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "views/category/index.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "534"
},
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "611133"
},
{
"name": "HTML",
"bytes": "975492"
},
{
"name": "JavaScript",
"bytes": "428420"
},
{
"name": "PHP",
"bytes": "63289"
},
{
"name": "PowerShell",
"bytes": "471"
},
{
"name": "Ruby",
"bytes": "2373"
}
],
"symlink_target": ""
} |
typedef struct {
SCARDHANDLE hCard;
DWORD dwAP;
} CONN_PARAMS, *LPCONN_PARAMS;
void InitializeReaders();
void ReleaseReaders();
void MonitorReaders();
void ListReaders(std::string msgid);
void Connect(std::string msgid, int index, unsigned int sharemode);
void Disconnect(std::string msgid, int index);
void Transcieve(std::string msgid, int index, std::string apdu); | {
"content_hash": "b26ff63a5633cf8af00fd7b64afb6d3b",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 67,
"avg_line_length": 30.916666666666668,
"alnum_prop": 0.7654986522911051,
"repo_name": "cardid/WebCard",
"id": "8ca3f5c584ce214816d2066fb3b94fd420489ff9",
"size": "575",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "native/webcard.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "816"
},
{
"name": "C++",
"bytes": "19946"
},
{
"name": "CMake",
"bytes": "12327"
},
{
"name": "HTML",
"bytes": "2919"
},
{
"name": "Rebol",
"bytes": "340"
}
],
"symlink_target": ""
} |
<?php
namespace Ukey1\ApiClient;
use Ukey1\App;
use Ukey1\Exceptions\EndpointException;
use GuzzleHttp;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\TransferException;
/**
* An instance of API request
*
* @package Ukey1
* @author Zdenek Hofler <developers@asaritech.com>
*/
class Request
{
/**
* GET method
*/
const GET = "GET";
/**
* POST method
*/
const POST = "POST";
/**
* DELETE method
*/
const DELETE = "DELETE";
/**
* Request timeout
*/
const TIMEOUT = 10;
/**
* User-Agent prefix
*/
const USER_AGENT = "ukey1-php-sdk/";
/**
* Request method
*
* @var string
*/
private $method;
/**
* API host
*
* @var string
*/
private $host;
/**
* Endpoint
*
* @var string
*/
private $endpoint;
/**
* Your App ID
*
* @var string
*/
private $appId;
/**
* Your secret key
*
* @var string
*/
private $secretKey;
/**
* User's access token
*
* @var string
*/
private $accessToken;
/**
* An instance of \GuzzleHttp\Client
*
* @var \GuzzleHttp\Client
*/
private $httpClient;
/**
* Creates an instance of a API request
*
* @param string $method Request method
*/
public function __construct($method = self::GET)
{
$this->method = $method;
}
/**
* Sets an API host
*
* @param string $host Host
*
* @return \Ukey1\ApiClient\Request
*/
public function setHost($host)
{
$this->host = $host;
return $this;
}
/**
* Sets an endpoint
*
* @param string $endpoint Endpoint
*
* @return \Ukey1\ApiClient\Request
*/
public function setEndpoint($endpoint)
{
$this->endpoint = $endpoint;
return $this;
}
/**
* Sets App credentials
*
* @param string $appId App ID
* @param string $secretKey Secret key
*
* @return \Ukey1\ApiClient\Request
*/
public function setCredentials($appId, $secretKey)
{
$this->appId = $appId;
$this->secretKey = $secretKey;
return $this;
}
/**
* Sets a user's access token
*
* @param string $accessToken Access token
*
* @return \Ukey1\ApiClient\Request
*/
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
return $this;
}
/**
* Sends a HTTP request
*
* @param array|null $body Array of parameters that will be send in JSON body
*
* @return \Ukey1\ApiClient\Result
* @throws \Ukey1\Exceptions\EndpointException
*/
public function send(array $body = null)
{
$json = $this->createJsonBody($body);
$signature = $this->createSignature($json);
$headers = $options = [];
$headers["User-Agent"] = self::prepareUserAgent();
if ($body) {
$headers["Content-Type"] = "application/json";
$headers["Content-Length"] = strlen($json);
$options["body"] = $json;
}
$options["headers"] = $this->prepareHeaders($signature, $headers);
try {
$this->httpClient = new Client(
[
"base_uri" => $this->host,
"timeout" => self::TIMEOUT
]
);
return new Result(
$this->httpClient->request(
$this->method,
$this->endpoint,
$options
)
);
} catch (TransferException $e) {
throw new EndpointException($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Creates a JSON string
*
* @param array|null $body Array of request parameters
*
* @return string|null
*/
private function createJsonBody(&$body)
{
if ($body && $this->method != self::GET) {
return GuzzleHttp\json_encode($body);
}
return;
}
/**
* Creates a request signature
*
* @param string|null $json JSON string
*
* @return string
* @throws \Ukey1\Exceptions\EndpointException
*/
private function createSignature(&$json)
{
$string = $this->appId . $this->method . $this->endpoint;
if ($json) {
$string .= $json;
}
if ($this->accessToken) {
$string .= $this->accessToken;
}
$digest = hash("sha512", $string);
$sign = "";
$result = openssl_public_encrypt($digest, $sign, $this->secretKey, OPENSSL_PKCS1_OAEP_PADDING);
if (!$result) {
throw new EndpointException("Request signing failed");
}
return rawurlencode(base64_encode($sign));
}
/**
* Prepares request headers
*
* @param string $signature Request signature
* @param array $headers Array of predefined headers
*
* @return array
*/
private function prepareHeaders(&$signature, array $headers = [])
{
$headers["X-Origin"] = self::prepareOrigin();
$headers["X-Ukey1-App"] = $this->appId;
$headers["X-Ukey1-Signature"] = $signature;
if ($this->accessToken) {
$headers["Authorization"] = "Bearer " . $this->accessToken;
}
return $headers;
}
/**
* Prepares a value of User-Agent header
*
* @return string
*/
private static function prepareUserAgent()
{
return self::USER_AGENT . App::SDK_VERSION . " " . GuzzleHttp\default_user_agent();
}
/**
* Prepares X-Origin value
*
* @return string
*/
private static function prepareOrigin()
{
$origin = App::getDomain();
if (!$origin) {
$origin = (isset($_SERVER["REQUEST_SCHEME"]) ? $_SERVER["REQUEST_SCHEME"] : "http" . (isset($_SERVER["HTTPS"]) ? "s" : "")) . "://" . (isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : $_SERVER["SERVER_NAME"]);
}
return $origin;
}
}
| {
"content_hash": "349ccc686cd0eb195820331fab4cce03",
"timestamp": "",
"source": "github",
"line_count": 297,
"max_line_length": 225,
"avg_line_length": 21.80808080808081,
"alnum_prop": 0.49235757295044,
"repo_name": "asaritech/ukey1-php-sdk",
"id": "4e6a4e406d4102a7570de4c062ac34fe7c883584",
"size": "7624",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Ukey1/ApiClient/Request.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "58125"
}
],
"symlink_target": ""
} |
require 'psych'
require 'mongoid'
require 'pathname'
require 'base64'
require 'parallel'
require 'sinatra/activerecord'
require 'json'
require 'set'
require_relative '../app'
path = Pathname.new(File.dirname(__FILE__)).realpath.parent
Mongoid.load!("#{path}/config/mongoid.yml", :production)
Dir["#{path}/models/*.rb"].each { |file| load file }
Dir["#{path}/helpers/*.rb"].each { |file| load file }
Mongoid.logger.level = Logger::INFO
Mongo::Logger.logger.level = Logger::INFO
maps = [461,462,463,464,465,466]
[4,3,2,1].each do |level|
maps.each do |map|
content = "lv,choose,pass\n"
SelectRankRecord.where(:mapareaId => map, :rank => level).distinct(:teitokuLv).to_a.each do |lv|
content += lv.to_s + ","
content += SelectRankRecord.where(:mapareaId => map, :rank => level, :teitokuLv => lv).count.to_s + ","
content += PassEventRecord.where(:mapId => map, :mapLv => level, :teitokuLv => lv).count.to_s + "\n"
end
cache = StatisticCache.find_or_create_by(
name: "wiki-SelectRankRecord-#{map}-#{level}"
)
cache.content = content
cache.save
end
end
| {
"content_hash": "d5325304b06c693de6642b9c6c8667f8",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 109,
"avg_line_length": 30.805555555555557,
"alnum_prop": 0.6573489630297565,
"repo_name": "Gizeta/poi-statistics",
"id": "fb4ea99819b46c01dd5bbaf991fa9bcba468e82f",
"size": "1109",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/staticify_detail.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3365"
},
{
"name": "HTML",
"bytes": "20231"
},
{
"name": "Haml",
"bytes": "102748"
},
{
"name": "JavaScript",
"bytes": "58274"
},
{
"name": "Ruby",
"bytes": "481710"
},
{
"name": "Shell",
"bytes": "432"
}
],
"symlink_target": ""
} |
/*
* Device : Evalutate platform informations & stylesheet validation
*
* <pre>
* - Chrome
* Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36
*
* - iPhone user agent
* Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3
*
* - iPod Touch user agent
* Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A101a Safari/419.3
*
* - iPad user agent
* Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10
*
* - Android user agent
* Mozilla/5.0 (Linux; U; Android 1.1; en-gb; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2
* Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17
*
* - NetFront
* SAMSUNG-C5212/C5212XDIK1 NetFront/3.4 Profile/MIDP-2.0 Configuration/CLDC-1.1
* MozillaMozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.5 (screen 824x1200;rotate)
* Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.5 (screen 824x1200;rotate)
* Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.5 (screen 824x1200; rotate)
* Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.5 (screen 600x800; rotate)
* Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.5 (screen 1200x824; rotate)
* Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.3 (screen 600x800; rotate)
* Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.3 (screen 1200x824; rotate)
* Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.1 (screen 824x1200; rotate)
* Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.0 (screen 824x1200; rotate)
* Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.0 (screen 600x800)
* Mozilla/4.0 (compatible; Linux 2.6.10) NetFront/3.4 Kindle/1.0 (screen 600x800)
* NetFront 3.3
* SonyEricssonK800c/R8BF Browser/NetFront/3.3 Profile/MIDP-2.0 Configuration/CLDC-1.1
* SonyEricssonK530i/R6BA Browser/NetFront/3.3 Profile/MIDP-2.0 Configuration/CLDC-1.1
* SonyEricssonK530c/R8BA Browser/NetFront/3.3 Profile/MIDP-2.0 Configuration/CLDC-1.1
* SonyEricssonK510c/R4EA Browser/NetFront/3.3 Profile/MIDP-2.0 Configuration/CLDC-1.1
* Mozilla/4.0 (compatible; Linux 2.6.10) NetFront/3.3 Kindle/1.0 (screen 600x800)
*
* - BlackBerry user agent
* BlackBerry9000/4.6.0.266 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/120
* </pre>
*
* @author: joje(joje.attrs@gmail.com)
*/
var Device = (function() {
// class device
var Device = function() {
"use strict";
var agent = navigator.userAgent;
var platform = {
name: '',
version: '',
codename: '',
type: ''
};
var device = 'desktop';
var engine;
var browser;
var fullversion;
var retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1);
var touchable = 'ontouchstart' in window;
var prefix;
var hasTransform = false;
var has3d = false;
var resolution = {
width: screen.width,
height: screen.height
};
if( ~agent.indexOf('Seamonkey') ) engine = 'gecko', browser = 'seamonkey', prefix = '-moz-';
else if( ~agent.indexOf('Firefox') ) engine = 'gecko', browser = 'firefox', prefix = '-moz-';
else if( ~agent.indexOf('Opera') ) engine = 'presto', browser = 'opera', prefix = '-o-';
else if( ~agent.indexOf('MSIE ') ) engine = 'trident', browser = 'msie', prefix = '-ms-';
else if( ~agent.indexOf('webOS/') ) engine = 'webkit', browser = 'webos', prefix = '-webkit-';
else if( ~agent.indexOf('Chromium') ) engine = 'webkit', browser = 'chromium', prefix = '-webkit-';
else if( ~agent.indexOf('Chrome') ) engine = 'webkit', browser = 'chrome', prefix = '-webkit-';
else if( ~agent.indexOf('Android') ) engine = 'webkit', browser = 'android', prefix = '-webkit-';
else if( ~agent.indexOf('Safari') ) engine = 'webkit', browser = 'safari', prefix = '-webkit-';
else if( ~agent.indexOf('Kindle')) engine = 'netfront', browser = 'kindle', prefix = '', platform = {name: 'kindle', type: 'tablet'};
else if( ~agent.indexOf('NetFront')) engine = 'netfront', browser = 'netfront', prefix = '';
else if( ~agent.indexOf('BlackBerry')) engine = 'webkit', browser = 'blackberry', prefix = '', platform = {name: 'blackberry', type: 'phone'};
else if( ~agent.indexOf('AppleWebKit') ) engine = 'webkit', browser = 'webkit', prefix = '-webkit-';
else if( ~agent.indexOf('Gecko') ) engine = 'gecko', browser = 'gecko', prefix = '-moz-';
if( !platform.name ) {
if( ~agent.indexOf('iPad') ) device = 'ipad', platform = {name: 'ios', type: 'tablet'};
else if( ~agent.indexOf('iPhone') ) device = 'iphone', platform = {name: 'ios', type: 'phone'};
else if( ~agent.indexOf('iPod') ) device = 'ipod', platform = {name: 'ios', type: 'phone'};
else if( ~agent.indexOf('Android') && ~agent.indexOf('Mobile') ) device = 'android', platform = {name: 'android', type: 'phone'};
else if( ~agent.indexOf('Android') ) device = 'android', platform = {name: 'android', type: 'tablet'};
}
if( !platform.type ) {
if( (/ipad|android 3|xoom|sch-i800|playbook|tablet|kindle/i.test(agent.toLowerCase())) ) platform.type = 'tablet';
else if( (/iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/i.test(agent.toLowerCase())) ) platform.type = 'phone';
}
if( !platform.name ) {
if( ~agent.indexOf('Mac OS X') ) platform = {name: 'osx', type: 'desktop'};
else if( ~agent.indexOf('Mac OS') ) platform = {name: 'mac', type: 'desktop'};
else if( ~agent.indexOf('Windows') || navigator.platform === 'Win32' ) platform = {name: 'windows', type: 'desktop'};
else if( ~agent.indexOf('Linux') ) platform = {name: 'linux', type: 'desktop'};
else platform.name = navigator.platform;
}
(function() {
var style = document.documentElement.style;
if( engine == 'webkit' ) hasTransform = ('webkitTransform' in style), has3d = ('WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix());
else if( engine == 'gecko' ) hasTransform = ('MozTransform' in style);
else if( engine == 'presto' ) hasTransform = ('OTransform' in style);
else if( engine == 'trident' ) hasTransform = ('MSTransform' in style);
if( !hasTransform ) hasTransform = ('Transform' in style);
var index;
if( browser === 'android' && ~(index = agent.indexOf('Android')) ) fullversion = platform.version = agent.substring(index + 7, agent.indexOf(' ', index + 1));
else if( browser === 'msie' && ~(index = agent.indexOf('MSIE ')) ) fullversion = agent.substring(index + 5, agent.indexOf(';', index + 1));
else if( browser === 'chrome' && ~(index = agent.indexOf('Chrome/')) ) fullversion = agent.substring(index + 7, agent.indexOf(' ', index + 1));
else if( browser === 'safari' && ~(index = agent.indexOf('Version/')) ) fullversion = agent.substring(index + 8, agent.indexOf(' ', index + 1));
})();
var version = fullversion ? parseInt(fullversion.split('.')[0]) || fullversion : fullversion;
// represent attributes
var gecko = (engine === 'gecko');
var webkit = (engine === 'webkit');
var blink = (browser === 'chrome' && version > 28);
var firefox = (browser === 'firefox');
var ie = (browser === 'msie');
var opera = (browser === 'opera');
var chrome = (browser === 'chrome');
var safari = (browser === 'safari');
var iphone = (device === 'iphone');
var ipad = (device === 'ipad');
var ipod = (device === 'ios');
var ios = (platform.name === 'ios');
var android = (platform.name === 'android');
var osx = (platform.name === 'osx');
var windows = (platform.name === 'windows');
var linux = (platform.name === 'linux');
var phone = (platform.type === 'phone');
var tablet = (platform.type === 'tablet');
var mobile = phone || tablet;
var desktop = (platform.type === 'desktop');
this.is = function(query) {
try {
return eval(query) || false;
} catch(err) {
console.warn('incorrect query [' + query + ']', err.message);
return false;
}
};
this.toJSON = function() {
return {
agent: agent,
platform: platform,
device: device,
engine: engine,
browser: browser,
fullversion: fullversion,
retina: retina,
touchable: touchable,
prefix: prefix,
hasTransform: hasTransform,
has3d: has3d,
resolution: resolution,
version: version,
gecko: gecko,
webkit: webkit,
blink: blink,
firefox: firefox,
ie: ie,
opera: opera,
chrome: chrome,
safari: safari,
iphone: iphone,
ipad: ipad,
ipod: ipod,
ios: ios,
android: android,
osx: osx,
windows: windows,
linux: linux,
phone: phone,
mobile: mobile,
tablet: tablet,
desktop: desktop
};
};
//console.log('device', JSON.stringify(this, null, '\t'));
}
return new Device();
})();
//console.log('Device', Device.is('webkit && version > 40 && desktop')); | {
"content_hash": "2b2f34437d06a7f53ab6e3e1ed896771",
"timestamp": "",
"source": "github",
"line_count": 208,
"max_line_length": 161,
"avg_line_length": 43.84615384615385,
"alnum_prop": 0.6428728070175439,
"repo_name": "attrs/ui-aliens",
"id": "ee411da206cdd5889d5c52a59f2d1b4b2e81c922",
"size": "9120",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/common/Device.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2644"
},
{
"name": "C#",
"bytes": "83"
},
{
"name": "C++",
"bytes": "193"
},
{
"name": "CSS",
"bytes": "156735"
},
{
"name": "Clojure",
"bytes": "794"
},
{
"name": "CoffeeScript",
"bytes": "403"
},
{
"name": "ColdFusion",
"bytes": "86"
},
{
"name": "GLSL",
"bytes": "512"
},
{
"name": "Go",
"bytes": "641"
},
{
"name": "Groovy",
"bytes": "1080"
},
{
"name": "HTML",
"bytes": "4082250"
},
{
"name": "Haxe",
"bytes": "447"
},
{
"name": "Java",
"bytes": "396"
},
{
"name": "JavaScript",
"bytes": "17916059"
},
{
"name": "Liquid",
"bytes": "1883"
},
{
"name": "Lua",
"bytes": "959"
},
{
"name": "OCaml",
"bytes": "539"
},
{
"name": "OpenSCAD",
"bytes": "333"
},
{
"name": "PHP",
"bytes": "351"
},
{
"name": "Perl",
"bytes": "637"
},
{
"name": "PowerShell",
"bytes": "418"
},
{
"name": "Python",
"bytes": "478"
},
{
"name": "Ruby",
"bytes": "164"
},
{
"name": "Scala",
"bytes": "1541"
},
{
"name": "Shell",
"bytes": "1142"
},
{
"name": "Tcl",
"bytes": "899"
},
{
"name": "TeX",
"bytes": "875"
},
{
"name": "XQuery",
"bytes": "114"
}
],
"symlink_target": ""
} |
package cli
import (
"encoding/json"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/ory/hydra/internal/httpclient/client/admin"
"github.com/ory/hydra/internal/httpclient/models"
"github.com/ory/hydra/x"
"github.com/ory/x/cmdx"
"github.com/ory/x/flagx"
"github.com/ory/x/pointerx"
)
type ClientHandler struct{}
func newClientHandler() *ClientHandler {
return &ClientHandler{}
}
func (h *ClientHandler) ImportClients(cmd *cobra.Command, args []string) {
cmdx.MinArgs(cmd, args, 1)
m := configureClient(cmd)
ek, encryptSecret, err := newEncryptionKey(cmd, nil)
cmdx.Must(err, "Failed to load encryption key: %s", err)
for _, path := range args {
reader, err := os.Open(path)
cmdx.Must(err, "Could not open file %s: %s", path, err)
var c models.OAuth2Client
err = json.NewDecoder(reader).Decode(&c)
cmdx.Must(err, "Could not parse JSON from file %s: %s", path, err)
response, err := m.Admin.CreateOAuth2Client(admin.NewCreateOAuth2ClientParams().WithBody(&c))
cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
result := response.Payload
if c.ClientSecret == "" {
if encryptSecret {
enc, err := ek.Encrypt([]byte(result.ClientSecret))
if err == nil {
fmt.Printf("Imported OAuth 2.0 Client %s from: %s\n", result.ClientID, path)
fmt.Printf("OAuth 2.0 Encrypted Client Secret: %s\n\n", enc.Base64Encode())
continue
}
fmt.Printf("Imported OAuth 2.0 Client %s:%s from: %s\n", result.ClientID, result.ClientSecret, path)
cmdx.Must(err, "Failed to encrypt client secret: %s", err)
}
fmt.Printf("Imported OAuth 2.0 Client %s:%s from: %s\n", result.ClientID, result.ClientSecret, path)
} else {
fmt.Printf("Imported OAuth 2.0 Client %s from: %s\n", result.ClientID, path)
}
}
}
func (h *ClientHandler) CreateClient(cmd *cobra.Command, args []string) {
var err error
m := configureClient(cmd)
secret := flagx.MustGetString(cmd, "secret")
var echoSecret bool
if secret == "" {
var secretb []byte
secretb, err = x.GenerateSecret(26)
cmdx.Must(err, "Could not generate OAuth 2.0 Client Secret: %s", err)
secret = string(secretb)
echoSecret = true
} else {
fmt.Println("You should not provide secrets using command line flags, the secret might leak to bash history and similar systems")
}
ek, encryptSecret, err := newEncryptionKey(cmd, nil)
cmdx.Must(err, "Failed to load encryption key: %s", err)
cc := models.OAuth2Client{
ClientID: flagx.MustGetString(cmd, "id"),
ClientSecret: secret,
ResponseTypes: flagx.MustGetStringSlice(cmd, "response-types"),
Scope: strings.Join(flagx.MustGetStringSlice(cmd, "scope"), " "),
GrantTypes: flagx.MustGetStringSlice(cmd, "grant-types"),
RedirectUris: flagx.MustGetStringSlice(cmd, "callbacks"),
ClientName: flagx.MustGetString(cmd, "name"),
TokenEndpointAuthMethod: flagx.MustGetString(cmd, "token-endpoint-auth-method"),
JwksURI: flagx.MustGetString(cmd, "jwks-uri"),
TosURI: flagx.MustGetString(cmd, "tos-uri"),
PolicyURI: flagx.MustGetString(cmd, "policy-uri"),
LogoURI: flagx.MustGetString(cmd, "logo-uri"),
ClientURI: flagx.MustGetString(cmd, "client-uri"),
AllowedCorsOrigins: flagx.MustGetStringSlice(cmd, "allowed-cors-origins"),
SubjectType: flagx.MustGetString(cmd, "subject-type"),
Audience: flagx.MustGetStringSlice(cmd, "audience"),
PostLogoutRedirectUris: flagx.MustGetStringSlice(cmd, "post-logout-callbacks"),
BackchannelLogoutSessionRequired: flagx.MustGetBool(cmd, "backchannel-logout-session-required"),
BackchannelLogoutURI: flagx.MustGetString(cmd, "backchannel-logout-callback"),
FrontchannelLogoutSessionRequired: flagx.MustGetBool(cmd, "frontchannel-logout-session-required"),
FrontchannelLogoutURI: flagx.MustGetString(cmd, "frontchannel-logout-callback"),
}
response, err := m.Admin.CreateOAuth2Client(admin.NewCreateOAuth2ClientParams().WithBody(&cc))
cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
result := response.Payload
fmt.Printf("OAuth 2.0 Client ID: %s\n", result.ClientID)
if result.ClientSecret == "" {
fmt.Println("This OAuth 2.0 Client has no secret")
} else {
if echoSecret {
if encryptSecret {
enc, err := ek.Encrypt([]byte(result.ClientSecret))
if err == nil {
fmt.Printf("OAuth 2.0 Encrypted Client Secret: %s\n", enc.Base64Encode())
return
}
// executes this at last to print raw client secret
// because if executes immediately, nobody knows client secret
defer cmdx.Must(err, "Failed to encrypt client secret: %s", err)
}
fmt.Printf("OAuth 2.0 Client Secret: %s\n", result.ClientSecret)
}
}
}
func (h *ClientHandler) UpdateClient(cmd *cobra.Command, args []string) {
cmdx.ExactArgs(cmd, args, 1)
m := configureClient(cmd)
newSecret := flagx.MustGetString(cmd, "secret")
var echoSecret bool
if newSecret != "" {
echoSecret = true
fmt.Println("You should not provide secrets using command line flags, the secret might leak to bash history and similar systems")
}
ek, encryptSecret, err := newEncryptionKey(cmd, nil)
cmdx.Must(err, "Failed to load encryption key: %s", err)
id := args[0]
cc := models.OAuth2Client{
ClientID: id,
ClientSecret: newSecret,
ResponseTypes: flagx.MustGetStringSlice(cmd, "response-types"),
Scope: strings.Join(flagx.MustGetStringSlice(cmd, "scope"), " "),
GrantTypes: flagx.MustGetStringSlice(cmd, "grant-types"),
RedirectUris: flagx.MustGetStringSlice(cmd, "callbacks"),
ClientName: flagx.MustGetString(cmd, "name"),
TokenEndpointAuthMethod: flagx.MustGetString(cmd, "token-endpoint-auth-method"),
JwksURI: flagx.MustGetString(cmd, "jwks-uri"),
TosURI: flagx.MustGetString(cmd, "tos-uri"),
PolicyURI: flagx.MustGetString(cmd, "policy-uri"),
LogoURI: flagx.MustGetString(cmd, "logo-uri"),
ClientURI: flagx.MustGetString(cmd, "client-uri"),
AllowedCorsOrigins: flagx.MustGetStringSlice(cmd, "allowed-cors-origins"),
SubjectType: flagx.MustGetString(cmd, "subject-type"),
Audience: flagx.MustGetStringSlice(cmd, "audience"),
PostLogoutRedirectUris: flagx.MustGetStringSlice(cmd, "post-logout-callbacks"),
BackchannelLogoutSessionRequired: flagx.MustGetBool(cmd, "backchannel-logout-session-required"),
BackchannelLogoutURI: flagx.MustGetString(cmd, "backchannel-logout-callback"),
FrontchannelLogoutSessionRequired: flagx.MustGetBool(cmd, "frontchannel-logout-session-required"),
FrontchannelLogoutURI: flagx.MustGetString(cmd, "frontchannel-logout-callback"),
}
response, err := m.Admin.UpdateOAuth2Client(admin.NewUpdateOAuth2ClientParams().WithID(id).WithBody(&cc))
cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
result := response.Payload
fmt.Printf("%s OAuth 2.0 Client updated\n", result.ClientID)
if echoSecret {
if encryptSecret {
enc, err := ek.Encrypt([]byte(result.ClientSecret))
if err == nil {
fmt.Printf("OAuth 2.0 Encrypted Client Secret: %s\n", enc.Base64Encode())
return
}
// executes this at last to print raw client secret
// because if executes immediately, nobody knows client secret
defer cmdx.Must(err, "Failed to encrypt client secret: %s", err)
}
fmt.Printf("Updated OAuth 2.0 Client Secret: %s\n", result.ClientSecret)
}
}
func (h *ClientHandler) DeleteClient(cmd *cobra.Command, args []string) {
cmdx.MinArgs(cmd, args, 1)
m := configureClient(cmd)
for _, c := range args {
_, err := m.Admin.DeleteOAuth2Client(admin.NewDeleteOAuth2ClientParams().WithID(c))
cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
}
fmt.Println("OAuth 2.0 Client(s) deleted")
}
func (h *ClientHandler) GetClient(cmd *cobra.Command, args []string) {
m := configureClient(cmd)
if len(args) == 0 {
fmt.Print(cmd.UsageString())
return
}
response, err := m.Admin.GetOAuth2Client(admin.NewGetOAuth2ClientParams().WithID(args[0]))
cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
cl := response.Payload
fmt.Println(cmdx.FormatResponse(cl))
}
func (h *ClientHandler) ListClients(cmd *cobra.Command, args []string) {
m := configureClient(cmd)
limit := flagx.MustGetInt(cmd, "limit")
page := flagx.MustGetInt(cmd, "page")
offset := (limit * page) - limit
response, err := m.Admin.ListOAuth2Clients(admin.NewListOAuth2ClientsParams().WithLimit(pointerx.Int64(int64(limit))).WithOffset(pointerx.Int64(int64(offset))))
cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
cls := response.Payload
table := newTable()
table.SetHeader([]string{
"Client ID",
"Name",
"Response Types",
"Scope",
"Redirect Uris",
"Grant Types",
"Token Endpoint Auth Method",
})
data := make([][]string, len(cls))
for i, cl := range cls {
data[i] = []string{
cl.ClientID,
cl.ClientName,
strings.Join(cl.ResponseTypes, ","),
cl.Scope,
strings.Join(cl.RedirectUris, "\n"),
strings.Join(cl.GrantTypes, ","),
cl.TokenEndpointAuthMethod,
}
}
table.AppendBulk(data)
table.Render()
}
| {
"content_hash": "5d68ec723360eae36399790d0306dd15",
"timestamp": "",
"source": "github",
"line_count": 259,
"max_line_length": 161,
"avg_line_length": 38.47876447876448,
"alnum_prop": 0.6622516556291391,
"repo_name": "ory-am/hydra",
"id": "3476f28484fefe7e179233137422ad09045c9ffe",
"size": "10731",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cmd/cli/handler_client.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "322097"
}
],
"symlink_target": ""
} |
layout: model
title: English BertForQuestionAnswering model (from husnu)
author: John Snow Labs
name: bert_qa_xtremedistil_l6_h256_uncased_TQUAD_finetuned_lr_2e_05_epochs_9
date: 2022-06-02
tags: [en, open_source, question_answering, bert]
task: Question Answering
language: en
edition: Spark NLP 4.0.0
spark_version: 3.0
supported: true
annotator: BertForQuestionAnswering
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---
## Description
Pretrained Question Answering model, adapted from Hugging Face and curated to provide scalability and production-readiness using Spark NLP. `xtremedistil-l6-h256-uncased-TQUAD-finetuned_lr-2e-05_epochs-9` is a English model orginally trained by `husnu`.
{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/bert_qa_xtremedistil_l6_h256_uncased_TQUAD_finetuned_lr_2e_05_epochs_9_en_4.0.0_3.0_1654192611826.zip){:.button.button-orange.button-orange-trans.arr.button-icon}
## How to use
<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
document_assembler = MultiDocumentAssembler() \
.setInputCols(["question", "context"]) \
.setOutputCols(["document_question", "document_context"])
spanClassifier = BertForQuestionAnswering.pretrained("bert_qa_xtremedistil_l6_h256_uncased_TQUAD_finetuned_lr_2e_05_epochs_9","en") \
.setInputCols(["document_question", "document_context"]) \
.setOutputCol("answer") \
.setCaseSensitive(True)
pipeline = Pipeline().setStages([
document_assembler,
spanClassifier
])
example = spark.createDataFrame([["What's my name?", "My name is Clara and I live in Berkeley."]]).toDF("question", "context")
result = pipeline.fit(example).transform(example)
```
```scala
val document = new MultiDocumentAssembler()
.setInputCols("question", "context")
.setOutputCols("document_question", "document_context")
val spanClassifier = BertForQuestionAnswering
.pretrained("bert_qa_xtremedistil_l6_h256_uncased_TQUAD_finetuned_lr_2e_05_epochs_9","en")
.setInputCols(Array("document_question", "document_context"))
.setOutputCol("answer")
.setCaseSensitive(true)
.setMaxSentenceLength(512)
val pipeline = new Pipeline().setStages(Array(document, spanClassifier))
val example = Seq(
("Where was John Lenon born?", "John Lenon was born in London and lived in Paris. My name is Sarah and I live in London."),
("What's my name?", "My name is Clara and I live in Berkeley."))
.toDF("question", "context")
val result = pipeline.fit(example).transform(example)
```
{:.nlu-block}
```python
import nlu
nlu.load("en.answer_question.tquad.bert.xtremedistiled_uncased").predict("""What's my name?|||"My name is Clara and I live in Berkeley.""")
```
</div>
{:.model-param}
## Model Information
{:.table-model}
|---|---|
|Model Name:|bert_qa_xtremedistil_l6_h256_uncased_TQUAD_finetuned_lr_2e_05_epochs_9|
|Compatibility:|Spark NLP 4.0.0+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[sentence, token]|
|Output Labels:|[embeddings]|
|Language:|en|
|Size:|47.7 MB|
|Case sensitive:|false|
|Max sentence length:|512|
## References
- https://huggingface.co/husnu/xtremedistil-l6-h256-uncased-TQUAD-finetuned_lr-2e-05_epochs-9 | {
"content_hash": "fe0f55868cd7a67d332ad4f55173ba5b",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 253,
"avg_line_length": 33.05940594059406,
"alnum_prop": 0.7541179994010183,
"repo_name": "JohnSnowLabs/spark-nlp",
"id": "175aeeea2f0a125004fc1babf5203822a63da088",
"size": "3343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/_posts/gadde5300/2022-06-02-bert_qa_xtremedistil_l6_h256_uncased_TQUAD_finetuned_lr_2e_05_epochs_9_en_3_0.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "14452"
},
{
"name": "Java",
"bytes": "223289"
},
{
"name": "Makefile",
"bytes": "819"
},
{
"name": "Python",
"bytes": "1694517"
},
{
"name": "Scala",
"bytes": "4116435"
},
{
"name": "Shell",
"bytes": "5286"
}
],
"symlink_target": ""
} |
#undef NDEBUG
#include <string>
#include "TestBase.h"
#include "Catch.h"
#include "HTTPIntegrationBase.h"
#include "HTTPHandlers.h"
#include "processors/TailFile.h"
#include "state/ProcessorController.h"
#include "utils/file/FileUtils.h"
class VerifyC2DescribeCoreComponentState : public VerifyC2Describe {
public:
explicit VerifyC2DescribeCoreComponentState(std::atomic_bool& verified)
: VerifyC2Describe(verified) {
temp_dir_ = testController.createTempDirectory();
test_file_1_ = utils::file::FileUtils::concat_path(temp_dir_, "test1.txt");
test_file_2_ = utils::file::FileUtils::concat_path(temp_dir_, "test2.txt");
std::ofstream f1(test_file_1_, std::ios::out | std::ios::binary);
f1 << "foo\n";
std::ofstream f2(test_file_2_, std::ios::out | std::ios::binary);
f2 << "foobar\n";
}
protected:
void updateProperties(minifi::FlowController& flow_controller) override {
auto setFileName = [] (const std::string& fileName, minifi::state::StateController& component){
auto& processor = dynamic_cast<minifi::state::ProcessorController&>(component).getProcessor();
processor.setProperty(minifi::processors::TailFile::FileName, fileName);
};
flow_controller.executeOnComponent("TailFile1",
[&](minifi::state::StateController& component) {setFileName(test_file_1_, component);});
flow_controller.executeOnComponent("TailFile2",
[&](minifi::state::StateController& component) {setFileName(test_file_2_, component);});
}
TestController testController;
std::string temp_dir_;
std::string test_file_1_;
std::string test_file_2_;
};
class DescribeCoreComponentStateHandler: public HeartbeatHandler {
public:
explicit DescribeCoreComponentStateHandler(std::shared_ptr<minifi::Configure> configuration, std::atomic_bool& verified)
: HeartbeatHandler(std::move(configuration)),
verified_(verified) {
}
void handleHeartbeat(const rapidjson::Document&, struct mg_connection * conn) override {
sendHeartbeatResponse("DESCRIBE", "corecomponentstate", "889345", conn);
}
void handleAcknowledge(const rapidjson::Document& root) override {
assert(root.HasMember("corecomponentstate"));
auto assertExpectedTailFileState = [&](const char* uuid, const char* name, const char* position) {
assert(root["corecomponentstate"].HasMember(uuid));
const auto& tf = root["corecomponentstate"][uuid];
assert(tf.HasMember("file.0.name"));
assert(std::string(tf["file.0.name"].GetString()) == name);
assert(tf.HasMember("file.0.position"));
assert(std::string(tf["file.0.position"].GetString()) == position);
assert(tf.HasMember("file.0.current"));
assert(strlen(tf["file.0.current"].GetString()) > 0U);
};
assertExpectedTailFileState("2438e3c8-015a-1000-79ca-83af40ec1993", "test1.txt", "4");
assertExpectedTailFileState("2438e3c8-015a-1000-79ca-83af40ec1994", "test2.txt", "7");
verified_ = true;
}
private:
std::atomic_bool& verified_;
};
int main(int argc, char **argv) {
std::atomic_bool verified{false};
const cmd_args args = parse_cmdline_args(argc, argv, "api/heartbeat");
VerifyC2DescribeCoreComponentState harness(verified);
harness.setKeyDir(args.key_dir);
DescribeCoreComponentStateHandler handler(harness.getConfiguration(), verified);
harness.setUrl(args.url, &handler);
harness.run(args.test_file);
return 0;
}
| {
"content_hash": "80a138b08ed96439b6923adb420db599",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 122,
"avg_line_length": 37.53846153846154,
"alnum_prop": 0.7110655737704918,
"repo_name": "dtrodrigues/nifi-minifi-cpp",
"id": "1439df0896a73d4352679d0dea59213ace870c37",
"size": "4221",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "extensions/http-curl/tests/C2DescribeCoreComponentStateTest.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "12771"
},
{
"name": "C",
"bytes": "194133"
},
{
"name": "C++",
"bytes": "7328208"
},
{
"name": "CMake",
"bytes": "454842"
},
{
"name": "Dockerfile",
"bytes": "14380"
},
{
"name": "Gherkin",
"bytes": "159174"
},
{
"name": "Java",
"bytes": "86800"
},
{
"name": "LLVM",
"bytes": "2594"
},
{
"name": "Lua",
"bytes": "3132"
},
{
"name": "Python",
"bytes": "330016"
},
{
"name": "Shell",
"bytes": "91629"
},
{
"name": "Yacc",
"bytes": "7064"
}
],
"symlink_target": ""
} |
<?php
use yii\db\Schema;
use yii\db\Migration;
class m150903_065022_lang extends Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('lang', [
'id' => Schema::TYPE_PK,
'url' => Schema::TYPE_STRING . '(255) NOT NULL',
'local' => Schema::TYPE_STRING . '(255) NOT NULL',
'name' => Schema::TYPE_STRING . '(255) NOT NULL',
'default' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 0',
], $tableOptions);
$this->batchInsert('lang', ['url', 'local', 'name', 'default'], [
['en', 'en-EN', 'English', 1],
['ru', 'ru-RU', 'Русский', 0],
]);
}
public function down()
{
$this->dropTable('lang');
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
| {
"content_hash": "05cb2e052f62e309790fbeeb0b958ae9",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 87,
"avg_line_length": 24.727272727272727,
"alnum_prop": 0.5128676470588235,
"repo_name": "ovasileva/songCreator",
"id": "b43e910ca02ebf734f2d6bec8c8b0b644f344561",
"size": "1095",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "migrations/m150903_065022_lang.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "217"
},
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "2444"
},
{
"name": "PHP",
"bytes": "97719"
}
],
"symlink_target": ""
} |
package org.opensaml.saml1.core;
import javax.xml.namespace.QName;
import org.opensaml.common.SAMLObject;
import org.opensaml.common.xml.SAMLConstants;
/**
* This interface defines how the object representing a SAML 1 <code> Status</code> element behaves.
*/
public interface Status extends SAMLObject {
/** Element name, no namespace. */
public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Status";
/** Default element name */
public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX);
/** Local name of the XSI type */
public final static String TYPE_LOCAL_NAME = "StatusType";
/** QName of the XSI type */
public final static QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX);
/** Return the object representing the <code>StatusMessage<code> (element). */
public StatusMessage getStatusMessage();
/** Set the object representing the <code>StatusMessage<code> (element). */
public void setStatusMessage(StatusMessage statusMessage) throws IllegalArgumentException;
/** Return the object representing the <code>StatusCode<code> (element). */
public StatusCode getStatusCode();
/** Set the object representing the <code>StatusCode<code> (element). */
public void setStatusCode(StatusCode statusCode) throws IllegalArgumentException;
/** Return the object representing the <code>StatusDetail<code> (element). */
public StatusDetail getStatusDetail();
/** Set the object representing the <code>StatusDetail<code> (element). */
public void setStatusDetail(StatusDetail statusDetail) throws IllegalArgumentException;
} | {
"content_hash": "2d1b8e3e8e87f6e556c7f0112b311a29",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 146,
"avg_line_length": 39.28888888888889,
"alnum_prop": 0.7335972850678733,
"repo_name": "Safewhere/kombit-web-java",
"id": "00234813b25d0670f464af538f89db99da99ffdb",
"size": "2612",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "kombit-opensaml-2.5.1/src/org/opensaml/saml1/core/Status.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3700"
},
{
"name": "HTML",
"bytes": "153980"
},
{
"name": "Java",
"bytes": "4040323"
}
],
"symlink_target": ""
} |
package model
import (
"fmt"
"strings"
"istio.io/istio/pkg/util/identifier"
"istio.io/istio/pkg/util/sets"
)
// ProxyView provides a restricted view of mesh endpoints for a Proxy.
type ProxyView interface {
fmt.Stringer
IsVisible(ep *IstioEndpoint) bool
}
// ProxyViewAll is a ProxyView where all endpoints are visible.
var ProxyViewAll ProxyView = proxyViewAll{}
type proxyViewAll struct{}
func (v proxyViewAll) IsVisible(*IstioEndpoint) bool {
return true
}
func (v proxyViewAll) String() string {
return ""
}
func newProxyView(node *Proxy) ProxyView {
if node == nil || node.Metadata == nil || len(node.Metadata.RequestedNetworkView) == 0 {
return ProxyViewAll
}
// Restrict the view to the requested networks.
return &proxyViewImpl{
visible: sets.New(node.Metadata.RequestedNetworkView...).Insert(identifier.Undefined),
getValue: func(ep *IstioEndpoint) string {
return ep.Network.String()
},
}
}
type proxyViewImpl struct {
visible sets.String
getValue func(ep *IstioEndpoint) string
}
func (v *proxyViewImpl) IsVisible(ep *IstioEndpoint) bool {
return v.visible.Contains(v.getValue(ep))
}
func (v *proxyViewImpl) String() string {
return strings.Join(sets.SortedList(v.visible), ",")
}
| {
"content_hash": "2b3b7028f8e9f32a84036f290a37ff65",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 89,
"avg_line_length": 22.418181818181818,
"alnum_prop": 0.7364152473641524,
"repo_name": "istio/istio",
"id": "8be5d07a851d176f02cc4e0623885569e6728f68",
"size": "1841",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pilot/pkg/model/proxy_view.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1273"
},
{
"name": "Go",
"bytes": "12352993"
},
{
"name": "Java",
"bytes": "1080"
},
{
"name": "Makefile",
"bytes": "59962"
},
{
"name": "Python",
"bytes": "11895"
},
{
"name": "Ruby",
"bytes": "317"
},
{
"name": "Shell",
"bytes": "149235"
},
{
"name": "Smarty",
"bytes": "7998"
}
],
"symlink_target": ""
} |
var IdTopBar = "topbar";
var IdMain = "main";
var IdPhotoGallery = "photoGallery";
var IdHomeRoot = "homeRoot";
var IdSlideBar = "slideBar";
var IdSlideButton = "slideButton";
var ParagraphWidth = dip(700); //Maximum width
var SlideMenuItems = ["Bookmark", "Share", "Translate", "Exit"];
var Images = ["castle.jpg", "clouds.jpg", "nature.jpg"];
function createHomeRoot() : LayoutData {
return {
ref: View,
id: IdHomeRoot,
fillParent: true,
scrollableX: false,
children: [
createTopBar(),
createMainContainer(),
createSideSlider()
]
};
}
function createTopBar() : LayoutData {
return {
ref: OverflowLayout,
id: IdTopBar,
bindLeft: $parent().anchorLeft(),
bindTop: $parent().anchorTop(),
bindRight: $parent().anchorRight(),
wrapHeight: true,
gravity: Gravity.Center,
background: new ColorDrawable(Color.Black),
//scrollableX: false, //TODO should not be needed
zIndex: 1,
children: [
mergeLayouts(utils.createButton("\u2194", dip(50)), {
id: IdSlideButton,
onClick: toggleSideBar
}),
utils.createButton("Home", dip(120)),
utils.createButton("Learn", dip(120)),
utils.createButton("Develop", dip(120)),
utils.createButton("Discuss", dip(120)),
mergeLayouts(utils.createView(EditText, "", dip(150)), {
marginLeft: dip(20), //TODO causes scroll overflow...
}),
]
};
}
function toggleSideBar(view : View) {
var bar = App.$(IdHomeRoot);
var button = App.$(IdSlideButton);
var slider = App.$(IdSlideBar);
var animation = new Animation();
if (bar.translationX() > 0) {
button.selected(false);
animation.animate("translationX", 0);
}
else {
button.selected(true);
animation.animate("translationX", slider.width());
}
animation.duration(250);
animation.restoreStartValues(false);
animation.start(bar);
}
function createSideSlider() : LayoutData {
return {
ref: ListLayout,
id: IdSlideBar,
wrapWidth: true,
zIndex: 2,
bindTop: $parent().anchorTop(),
bindRight: $id(IdHomeRoot).anchorLeft(),
bindBottom: $parent().anchorBottom(),
background: new ColorDrawable(Color.Black),
adapter: new LayoutDataAdapter(utils.createListViewItem, SlideMenuItems)
};
}
function createMainContainer() : LayoutData {
return {
ref: View,
id: IdMain,
bindLeft: $parent().anchorLeft(),
bindTop: $id(IdTopBar).anchorBottom(),
bindRight: $parent().anchorRight(),
bindBottom: $parent().anchorBottom(),
children: [
createMainBody()
]
};
}
function createMainBody() : LayoutData {
return {
ref: LinearLayout,
minWidth: dip(300),
maxWidth: dip(900),
wrapHeight: true,
bindTop: $id(IdMain).anchorTop(),
bindLeft: $parent().anchorLeft(),
bindRight: $parent().anchorRight(),
gravity: Gravity.CenterHorizontal | Gravity.StretchX,
margins: dip(10),
clipChildren: false,
children: [
createIntroLayout(),
mergeLayouts(utils.createTextView("intro", 1), {
marginTop: dip(30),
maxWidth: ParagraphWidth
}),
createPagesLayout(Color.RGB8(200, 128, 128), "critic1", "critic2", "critic3", "critic4"),
mergeLayouts(utils.createTextView("explain", 1), {
marginTop: dip(30),
maxWidth: ParagraphWidth
}),
createInfoBoxLayout(),
mergeLayouts(utils.createTextView("relax", 1), {
marginTop: dip(30),
maxWidth: ParagraphWidth
}),
mergeLayouts(utils.createButton("Relax", 1), {
marginTop: dip(30),
maxWidth: ParagraphWidth / 2,
onClick: function(view : View) {
throwPhotos();
}
}),
createPhotoGalleryLayout(),
mergeLayouts(utils.createTextView("userStories", 1), {
marginTop: dip(30),
maxWidth: ParagraphWidth
}),
mergeLayouts(createPagesLayout(Color.RGB8(120, 200, 128), "customer1", "customer2", "customer3", "customer4"), {
onTransformView: utils.transformUserPage
}),
mergeLayouts(utils.createTextView("end", 1), {
marginTop: dip(30),
maxWidth: ParagraphWidth
}),
]
};
}
function createIntroLayout() : LayoutData {
return {
ref: View,
wrapHeight: true,
maxWidth: ParagraphWidth * 0.6,
textElement: document.getElementById("title"),
textAlign: TextAlign.CenterHorizontal,
margins: dip(10),
padding: dip(30),
background: new RoundedDrawable(Color.RGB8(200, 200, 128))
};
}
function createInfoBoxLayout() : LayoutData {
return {
ref: FlowLayout,
wrapHeight: true,
maxWidth: ParagraphWidth,
margins: dip(10),
gravity: Gravity.Center,
rowGravity: Gravity.CenterHorizontal,
children: [
utils.createTextView("info1", dip(200)),
utils.createTextView("info2", dip(200)),
utils.createTextView("info3", dip(200)),
]
};
}
function createPagesLayout(color : Color, ... textIds : string[]) : LayoutData {
var pages : LayoutData[] = [];
for (var i=0; i < textIds.length; ++i) {
pages.push(utils.createPageView(textIds[i], color));
}
return {
ref: PageLayout,
wrapHeight: true,
maxWidth: ParagraphWidth,
margins: dip(10),
childWidth: 0.9,
snapDuration: 500,
onTransformView: utils.transformCriticPage,
clipChildren: false,
zIndex: -1,
children: pages
};
}
function createPhotoGalleryLayout() : LayoutData {
return {
ref: FlowLayout,
id: IdPhotoGallery,
wrapHeight: true,
maxWidth: ParagraphWidth,
margins: dip(10),
clipChildren: false,
gravity: Gravity.Center,
rowGravity: Gravity.CenterHorizontal,
layoutAnimator: new TranslationLayoutAnimator(),
};
}
function throwPhotos() {
var gallery = <FlowLayout>App.$(IdPhotoGallery);
gallery.destroyChildren();
for (var i=0; i < 5; ++i) {
var imageUrl = Images[MathUtils.randomValue(0, Images.length)];
gallery.inflate(utils.createPhotoImageView(imageUrl, imageUrl));
}
}
function showSource(name : string) {
try {
window.open("home/" + name + ".ts.txt");
}
catch (err) {
}
}
var App = new Application();
function initApp() {
var canvas = <HTMLCanvasElement>document.getElementById("rootCanvas");
App.setCanvas(canvas);
App.root.inflate(createHomeRoot());
resizeCanvas();
}
function resizeCanvas() {
var canvas = <HTMLCanvasElement>document.getElementById("rootCanvas");
App.setSize(window.innerWidth, window.innerHeight);
}
| {
"content_hash": "caaea1eefdab60f8c1dbb2e1a264a128",
"timestamp": "",
"source": "github",
"line_count": 251,
"max_line_length": 124,
"avg_line_length": 29.50199203187251,
"alnum_prop": 0.5681296421336934,
"repo_name": "heikkisa/tsgui",
"id": "6aacc35961b7a5bee755797ca0ae93659468b2d2",
"size": "7445",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/home/home.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2426"
},
{
"name": "TypeScript",
"bytes": "281154"
}
],
"symlink_target": ""
} |
#include <stdint.h>
#include <stdio.h>
#include <rthw.h>
#include <rtdevice.h>
#include <rtthread.h>
#include <dfs_posix.h>
#include "posix_aio.h"
struct rt_workqueue* aio_queue = NULL;
/**
* The aio_cancel() function shall attempt to cancel one or more asynchronous I/O
* requests currently outstanding against file descriptor fildes. The aiocbp
* argument points to the asynchronous I/O control block for a particular request
* to be canceled. If aiocbp is NULL, then all outstanding cancelable asynchronous
* I/O requests against fildes shall be canceled.
*
* Normal asynchronous notification shall occur for asynchronous I/O operations
* that are successfully canceled. If there are requests that cannot be canceled,
* then the normal asynchronous completion process shall take place for those
* requests when they are completed.
*
* For requested operations that are successfully canceled, the associated error
* status shall be set to [ECANCELED] and the return status shall be -1. For
* requested operations that are not successfully canceled, the aiocbp shall not
* be modified by aio_cancel().
*
* If aiocbp is not NULL, then if fildes does not have the same value as the file
* descriptor with which the asynchronous operation was initiated, unspecified results occur.
*
* Which operations are cancelable is implementation-defined.
*/
int aio_cancel(int fd, struct aiocb *cb)
{
rt_err_t ret;
if (!cb) return -EINVAL;
if (cb->aio_fildes != fd) return -EINVAL;
ret = rt_workqueue_cancel_work_sync(aio_queue, &(cb->aio_work));
if (ret == RT_EOK)
{
errno = -ECANCELED;
return -1;
}
return 0;
}
/**
* The aio_error() function shall return the error status associated with the
* aiocb structure referenced by the aiocbp argument. The error status for an
* asynchronous I/O operation is the errno value that would be set by the corresponding
* read(), write(),
*/
int aio_error (const struct aiocb *cb)
{
if (cb)
{
return cb->aio_result;
}
return -EINVAL;
}
/**
* The aio_fsync() function shall asynchronously perform a file synchronization
* operation, as specified by the op argument, for I/O operations associated with
* the file indicated by the file descriptor aio_fildes member of the aiocb
* structure referenced by the aiocbp argument and queued at the time of the
* call to aio_fsync(). The function call shall return when the synchronization
* request has been initiated or queued to the file or device (even when the data
* cannot be synchronized immediately).
*
* option: If op is O_DSYNC, all currently queued I/O operations shall be completed
* as if by a call to fdatasync(); that is, as defined for synchronized I/O data
* integrity completion.
*
* option: If op is O_SYNC, all currently queued I/O operations shall be completed
* as if by a call to fsync(); that is, as defined for synchronized I/O file integrity
* completion. If the aio_fsync() function fails, or if the operation queued by
* aio_fsync() fails, then outstanding I/O operations are not guaranteed to have
* been completed.
*
* If aio_fsync() succeeds, then it is only the I/O that was queued at the time
* of the call to aio_fsync() that is guaranteed to be forced to the relevant
* completion state. The completion of subsequent I/O on the file descriptor is
* not guaranteed to be completed in a synchronized fashion.
*
* The aiocbp argument refers to an asynchronous I/O control block. The aiocbp
* value may be used as an argument to aio_error() and aio_return() in order to
* determine the error status and return status, respectively, of the asynchronous
* operation while it is proceeding. When the request is queued, the error status
* for the operation is [EINPROGRESS]. When all data has been successfully transferred,
* the error status shall be reset to reflect the success or failure of the operation.
* If the operation does not complete successfully, the error status for the
* operation shall be set to indicate the error. The aio_sigevent member determines
* the asynchronous notification to occur as specified in Signal Generation and
* Delivery when all operations have achieved synchronized I/O completion. All
* other members of the structure referenced by aiocbp are ignored. If the control
* block referenced by aiocbp becomes an illegal address prior to asynchronous
* I/O completion, then the behavior is undefined.
*
* If the aio_fsync() function fails or aiocbp indicates an error condition,
* data is not guaranteed to have been successfully transferred.
*/
static void aio_fync_work(struct rt_work* work, void* work_data)
{
int result;
rt_ubase_t level;
struct aiocb *cb = (struct aiocb*)work_data;
RT_ASSERT(cb != RT_NULL);
result = fsync(cb->aio_fildes);
/* modify result */
level = rt_hw_interrupt_disable();
if (result < 0)
cb->aio_result = errno;
else
cb->aio_result = 0;
rt_hw_interrupt_enable(level);
return ;
}
int aio_fsync(int op, struct aiocb *cb)
{
rt_ubase_t level;
if (!cb) return -EINVAL;
level = rt_hw_interrupt_disable();
cb->aio_result = -EINPROGRESS;
rt_hw_interrupt_enable(level);
rt_work_init(&(cb->aio_work), aio_fync_work, cb);
rt_workqueue_dowork(aio_queue, &(cb->aio_work));
return 0;
}
static void aio_read_work(struct rt_work* work, void* work_data)
{
int len;
rt_ubase_t level;
uint8_t *buf_ptr;
struct aiocb *cb = (struct aiocb*)work_data;
buf_ptr = (uint8_t*)cb->aio_buf;
/* seek to offset */
lseek(cb->aio_fildes, cb->aio_offset, SEEK_SET);
len = read(cb->aio_fildes, &buf_ptr[cb->aio_offset], cb->aio_nbytes);
/* modify result */
level = rt_hw_interrupt_disable();
if (len <= 0)
cb->aio_result = errno;
else
cb->aio_result = 0;
rt_hw_interrupt_enable(level);
return ;
}
/**
* The aio_read() function shall read aiocbp->aio_nbytes from the file associated
* with aiocbp->aio_fildes into the buffer pointed to by aiocbp->aio_buf. The
* function call shall return when the read request has been initiated or queued
* to the file or device (even when the data cannot be delivered immediately).
*
* If prioritized I/O is supported for this file, then the asynchronous operation
* shall be submitted at a priority equal to a base scheduling priority minus
* aiocbp->aio_reqprio. If Thread Execution Scheduling is not supported, then
* the base scheduling priority is that of the calling process;
*
* otherwise, the base scheduling priority is that of the calling thread.
*
* The aiocbp value may be used as an argument to aio_error() and aio_return()
* in order to determine the error status and return status, respectively, of
* the asynchronous operation while it is proceeding. If an error condition is
* encountered during queuing, the function call shall return without having
* initiated or queued the request. The requested operation takes place at the
* absolute position in the file as given by aio_offset, as if lseek() were called
* immediately prior to the operation with an offset equal to aio_offset and a
* whence equal to SEEK_SET. After a successful call to enqueue an asynchronous
* I/O operation, the value of the file offset for the file is unspecified.
*
* The aio_sigevent member specifies the notification which occurs when the
* request is completed.
*
* The aiocbp->aio_lio_opcode field shall be ignored by aio_read().
*
* The aiocbp argument points to an aiocb structure. If the buffer pointed to by
* aiocbp->aio_buf or the control block pointed to by aiocbp becomes an illegal
* address prior to asynchronous I/O completion, then the behavior is undefined.
*
* Simultaneous asynchronous operations using the same aiocbp produce undefined
* results.
*
* If synchronized I/O is enabled on the file associated with aiocbp->aio_fildes,
* the behavior of this function shall be according to the definitions of synchronized
* I/O data integrity completion and synchronized I/O file integrity completion.
*
* For any system action that changes the process memory space while an asynchronous
* I/O is outstanding to the address range being changed, the result of that action
* is undefined.
*
* For regular files, no data transfer shall occur past the offset maximum
* established in the open file description associated with aiocbp->aio_fildes.
*
*/
int aio_read(struct aiocb *cb)
{
rt_ubase_t level;
if (!cb) return -EINVAL;
if (cb->aio_offset < 0) return -EINVAL;
level = rt_hw_interrupt_disable();
cb->aio_result = -EINPROGRESS;
rt_hw_interrupt_enable(level);
/* en-queue read work */
rt_work_init(&(cb->aio_work), aio_read_work, cb);
rt_workqueue_dowork(aio_queue, &(cb->aio_work));
return 0;
}
/**
* The aio_return() function shall return the return status associated with the
* aiocb structure referenced by the aiocbp argument. The return status for an
* asynchronous I/O operation is the value that would be returned by the corresponding
* read(), write(), or fsync() function call. If the error status for the operation
* is equal to [EINPROGRESS], then the return status for the operation is undefined.
* The aio_return() function may be called exactly once to retrieve the return
* status of a given asynchronous operation; thereafter, if the same aiocb structure
* is used in a call to aio_return() or aio_error(), an error may be returned.
* When the aiocb structure referred to by aiocbp is used to submit another asynchronous
* operation, then aio_return() may be successfully used to retrieve the return
* status of that operation.
*/
ssize_t aio_return(struct aiocb *cb)
{
if (cb)
{
if (cb->aio_result < 0)
rt_set_errno(cb->aio_result);
return cb->aio_result;
}
return -EINVAL;
}
/**
* The aio_suspend() function shall suspend the calling thread until at least
* one of the asynchronous I/O operations referenced by the list argument has
* completed, until a signal interrupts the function, or, if timeout is not NULL,
* until the time interval specified by timeout has passed. If any of the aiocb
* structures in the list correspond to completed asynchronous I/O operations
* (that is, the error status for the operation is not equal to [EINPROGRESS])
* at the time of the call, the function shall return without suspending the
* calling thread. The list argument is an array of pointers to asynchronous I/O
* control blocks. The nent argument indicates the number of elements in the
* array. Each aiocb structure pointed to has been used in initiating an asynchronous
* I/O request via aio_read(), aio_write(), or lio_listio(). This array may
* contain null pointers, which are ignored. If this array contains pointers
* that refer to aiocb structures that have not been used in submitting asynchronous
* I/O, the effect is undefined.
*
* If the time interval indicated in the timespec structure pointed to by timeout
* passes before any of the I/O operations referenced by list are completed, then
* aio_suspend() shall return with an error.
*/
int aio_suspend(const struct aiocb *const list[], int nent,
const struct timespec *timeout)
{
return -ENOSYS;
}
static void aio_write_work(struct rt_work* work, void* work_data)
{
int len, oflags, level;
uint8_t *buf_ptr;
struct aiocb *cb = (struct aiocb*)work_data;
buf_ptr = (uint8_t*)cb->aio_buf;
/* whether seek offset */
oflags = fcntl(cb->aio_fildes, F_GETFL, 0);
if ((oflags & O_APPEND) == 0)
{
lseek(cb->aio_fildes, SEEK_SET, cb->aio_offset);
}
/* write data */
len = write(cb->aio_fildes, buf_ptr, cb->aio_nbytes);
/* modify result */
level = rt_hw_interrupt_disable();
if (len <= 0)
cb->aio_result = errno;
else
cb->aio_result = len;
rt_hw_interrupt_enable(level);
return;
}
/**
* The aio_write() function shall write aiocbp->aio_nbytes to the file associated
* with aiocbp->aio_fildes from the buffer pointed to by aiocbp->aio_buf. The
* function shall return when the write request has been initiated or, at a minimum,
* queued to the file or device.
*
* The aiocbp argument may be used as an argument to aio_error() and aio_return()
* in order to determine the error status and return status, respectively, of the
* asynchronous operation while it is proceeding.
*
* The aiocbp argument points to an aiocb structure. If the buffer pointed to by
* aiocbp->aio_buf or the control block pointed to by aiocbp becomes an illegal
* address prior to asynchronous I/O completion, then the behavior is undefined.
*
* If O_APPEND is not set for the file descriptor aio_fildes, then the requested
* operation shall take place at the absolute position in the file as given by
* aio_offset, as if lseek() were called immediately prior to the operation with
* an offset equal to aio_offset and a whence equal to SEEK_SET. If O_APPEND is
* set for the file descriptor, or if aio_fildes is associated with a device that
* is incapable of seeking, write operations append to the file in the same order
* as the calls were made, except under circumstances described in Asynchronous
* I/O. After a successful call to enqueue an asynchronous I/O operation, the value
* of the file offset for the file is unspecified.
*
* The aio_sigevent member specifies the notification which occurs when the request
* is completed.
*
* The aiocbp->aio_lio_opcode field shall be ignored by aio_write().
*
* Simultaneous asynchronous operations using the same aiocbp produce undefined
* results.
*
* If synchronized I/O is enabled on the file associated with aiocbp->aio_fildes,
* the behavior of this function shall be according to the definitions of synchronized
* I/O data integrity completion, and synchronized I/O file integrity completion.
*
* For regular files, no data transfer shall occur past the offset maximum established
* in the open file description associated with aiocbp->aio_fildes.
*/
int aio_write(struct aiocb *cb)
{
int oflags;
rt_ubase_t level;
if (!cb || (cb->aio_buf == NULL)) return -EINVAL;
/* check access mode */
oflags = fcntl(cb->aio_fildes, F_GETFL, 0);
if ((oflags & O_ACCMODE) != O_WRONLY ||
(oflags & O_ACCMODE) != O_RDWR)
return -EINVAL;
level = rt_hw_interrupt_disable();
cb->aio_result = -EINPROGRESS;
rt_hw_interrupt_enable(level);
rt_work_init(&(cb->aio_work), aio_write_work, cb);
rt_workqueue_dowork(aio_queue, &(cb->aio_work));
return 0;
}
/**
* The lio_listio() function shall initiate a list of I/O requests with a single
* function call.
*
* The mode argument takes one of the values LIO_WAIT or LIO_NOWAIT declared in
* <aio.h> and determines whether the function returns when the I/O operations
* have been completed, or as soon as the operations have been queued. If the
* mode argument is LIO_WAIT, the function shall wait until all I/O is complete
* and the sig argument shall be ignored.
*
* If the mode argument is LIO_NOWAIT, the function shall return immediately, and
* asynchronous notification shall occur, according to the sig argument, when all
* the I/O operations complete. If sig is NULL, then no asynchronous notification
* shall occur. If sig is not NULL, asynchronous notification occurs as specified
* in Signal Generation and Delivery when all the requests in list have completed.
*
* The I/O requests enumerated by list are submitted in an unspecified order.
*
* The list argument is an array of pointers to aiocb structures. The array contains
* nent elements. The array may contain NULL elements, which shall be ignored.
*
* If the buffer pointed to by list or the aiocb structures pointed to by the
* elements of the array list become illegal addresses before all asynchronous I/O
* completed and, if necessary, the notification is sent, then the behavior is
* undefined. If the buffers pointed to by the aio_buf member of the aiocb structure
* pointed to by the elements of the array list become illegal addresses prior to
* the asynchronous I/O associated with that aiocb structure being completed, the
* behavior is undefined.
*
* The aio_lio_opcode field of each aiocb structure specifies the operation to be
* performed. The supported operations are LIO_READ, LIO_WRITE, and LIO_NOP; these
* symbols are defined in <aio.h>. The LIO_NOP operation causes the list entry to
* be ignored. If the aio_lio_opcode element is equal to LIO_READ, then an I/O operation
* is submitted as if by a call to aio_read() with the aiocbp equal to the address
* of the aiocb structure. If the aio_lio_opcode element is equal to LIO_WRITE, then
* an I/O operation is submitted as if by a call to aio_write() with the aiocbp equal
* to the address of the aiocb structure.
*
* The aio_fildes member specifies the file descriptor on which the operation is to
* be performed.
*
* The aio_buf member specifies the address of the buffer to or from which the data
* is transferred.
*
* The aio_nbytes member specifies the number of bytes of data to be transferred.
*
* The members of the aiocb structure further describe the I/O operation to be
* performed, in a manner identical to that of the corresponding aiocb structure
* when used by the aio_read() and aio_write() functions.
*
* The nent argument specifies how many elements are members of the list; that is,
* the length of the array.
*
* The behavior of this function is altered according to the definitions of synchronized
* I/O data integrity completion and synchronized I/O file integrity completion if
* synchronized I/O is enabled on the file associated with aio_fildes.
*
* For regular files, no data transfer shall occur past the offset maximum established
* in the open file description associated with aiocbp->aio_fildes.
*
* If sig->sigev_notify is SIGEV_THREAD and sig->sigev_notify_attributes is a
* non-null pointer and the block pointed to by this pointer becomes an illegal
* address prior to all asynchronous I/O being completed, then the behavior is
* undefined.
*/
int lio_listio(int mode, struct aiocb * const list[], int nent,
struct sigevent *sig)
{
return -ENOSYS;
}
int aio_system_init(void)
{
aio_queue = rt_workqueue_create("aio", 2048, RT_THREAD_PRIORITY_MAX/2);
RT_ASSERT(aio_queue != NULL);
return 0;
}
INIT_COMPONENT_EXPORT(aio_system_init);
| {
"content_hash": "75f0a5f2dfa1102a54c02c9b7638cc7f",
"timestamp": "",
"source": "github",
"line_count": 456,
"max_line_length": 93,
"avg_line_length": 41.203947368421055,
"alnum_prop": 0.7177071690882963,
"repo_name": "wolfgangz2013/rt-thread",
"id": "75e7de9ce329a96ad5c1e6f17c8ea87cc3b06ffc",
"size": "18998",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "components/libc/aio/posix_aio.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "16995634"
},
{
"name": "Batchfile",
"bytes": "179660"
},
{
"name": "C",
"bytes": "705913788"
},
{
"name": "C++",
"bytes": "7764376"
},
{
"name": "CMake",
"bytes": "148026"
},
{
"name": "CSS",
"bytes": "9978"
},
{
"name": "DIGITAL Command Language",
"bytes": "13234"
},
{
"name": "GDB",
"bytes": "11796"
},
{
"name": "HTML",
"bytes": "6039932"
},
{
"name": "Lex",
"bytes": "7026"
},
{
"name": "Logos",
"bytes": "7078"
},
{
"name": "M4",
"bytes": "17515"
},
{
"name": "Makefile",
"bytes": "268009"
},
{
"name": "Module Management System",
"bytes": "1548"
},
{
"name": "Objective-C",
"bytes": "4093973"
},
{
"name": "Pawn",
"bytes": "1427"
},
{
"name": "Perl",
"bytes": "9520"
},
{
"name": "Python",
"bytes": "1203710"
},
{
"name": "RPC",
"bytes": "14162"
},
{
"name": "Roff",
"bytes": "4486"
},
{
"name": "Ruby",
"bytes": "869"
},
{
"name": "Shell",
"bytes": "407723"
},
{
"name": "TeX",
"bytes": "3113"
},
{
"name": "Yacc",
"bytes": "16084"
}
],
"symlink_target": ""
} |
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>LongShouldWrapper - ScalaTest 1.9.1 - org.scalatest.matchers.ShouldMatchers.LongShouldWrapper</title>
<meta name="description" content="LongShouldWrapper - ScalaTest 1.9.1 - org.scalatest.matchers.ShouldMatchers.LongShouldWrapper" />
<meta name="keywords" content="LongShouldWrapper ScalaTest 1.9.1 org.scalatest.matchers.ShouldMatchers.LongShouldWrapper" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script>
<script type="text/javascript" src="../../../lib/jquery-ui.js"></script>
<script type="text/javascript" src="../../../lib/template.js"></script>
<script type="text/javascript" src="../../../lib/tools.tooltip.js"></script>
<script type="text/javascript">
if(top === self) {
var url = '../../../index.html';
var hash = 'org.scalatest.matchers.ShouldMatchers$LongShouldWrapper';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
<!-- gtag [javascript] -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-71294502-1"></script>
<script defer>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-71294502-1');
</script>
</head>
<body class="type">
<!-- Top of doc.scalatest.org [javascript] -->
<script type="text/javascript">
var rnd = window.rnd || Math.floor(Math.random()*10e6);
var pid204546 = window.pid204546 || rnd;
var plc204546 = window.plc204546 || 0;
var abkw = window.abkw || '';
var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER';
document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>');
</script>
<div id="definition">
<img src="../../../lib/class_big.png" />
<p id="owner"><a href="../../package.html" class="extype" name="org">org</a>.<a href="../package.html" class="extype" name="org.scalatest">scalatest</a>.<a href="package.html" class="extype" name="org.scalatest.matchers">matchers</a>.<a href="ShouldMatchers.html" class="extype" name="org.scalatest.matchers.ShouldMatchers">ShouldMatchers</a></p>
<h1>LongShouldWrapper</h1>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">class</span>
</span>
<span class="symbol">
<span class="name">LongShouldWrapper</span><span class="result"> extends <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="comment cmt"><p>This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="ShouldMatchers.html"><code>ShouldMatchers</code></a> or <a href="MustMatchers.html"><code>MustMatchers</code></a> for an overview of
the matchers DSL.</p><p>This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
be invoked on <code>Long</code>s.</p></div><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent"><span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By inheritance</span></li>
</ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="org.scalatest.matchers.ShouldMatchers.LongShouldWrapper"><span>LongShouldWrapper</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div id="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show all</span></li>
</ol>
<a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="constructors" class="members">
<h3>Instance Constructors</h3>
<ol><li name="org.scalatest.matchers.ShouldMatchers.LongShouldWrapper#<init>" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="<init>(left:Long):ShouldMatchers.this.LongShouldWrapper"></a>
<a id="<init>:LongShouldWrapper"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">new</span>
</span>
<span class="symbol">
<span class="name">LongShouldWrapper</span><span class="params">(<span name="left">left: <span class="extype" name="scala.Long">Long</span></span>)</span>
</span>
</h4>
</li></ol>
</div>
<div id="values" class="values members">
<h3>Value Members</h3>
<ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:AnyRef):Boolean"></a>
<a id="!=(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a>
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<a id="##():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:AnyRef):Boolean"></a>
<a id="==(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a>
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a>
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<span class="extype" name="java.lang">java.lang</span>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a>
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a>
<a id="equals(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<span class="extype" name="java.lang">java.lang</span>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<a id="getClass():Class[_]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="hashCode():Int"></a>
<a id="hashCode():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a>
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="org.scalatest.matchers.ShouldMatchers.LongShouldWrapper#should" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="should(notWord:ShouldMatchers.this.NotWord):ShouldMatchers.this.ResultOfNotWordForLong"></a>
<a id="should(ShouldMatchers.NotWord):ShouldMatchers.ResultOfNotWordForLong"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">should</span><span class="params">(<span name="notWord">notWord: <a href="ShouldMatchers.html#NotWordextendsObject" class="extmbr" name="org.scalatest.matchers.ClassicMatchers.NotWord">ShouldMatchers.NotWord</a></span>)</span><span class="result">: <a href="ShouldMatchers.html#ResultOfNotWordForLongextendsClassicMatchers.this.ResultOfNotWord[Long]" class="extmbr" name="org.scalatest.matchers.ClassicMatchers.ResultOfNotWordForLong">ShouldMatchers.ResultOfNotWordForLong</a></span>
</span>
</h4>
<p class="shortcomment cmt">This method enables syntax such as the following:</p><div class="fullcomment"><div class="comment cmt"><p>This method enables syntax such as the following:</p><p><pre class="stHighlighted">
result should not equal (<span class="stLiteral">88L</span>)
^
</pre>
</p></div></div>
</li><li name="org.scalatest.matchers.ShouldMatchers.LongShouldWrapper#should" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="should(rightMatcher:org.scalatest.matchers.Matcher[Long]):Unit"></a>
<a id="should(Matcher[Long]):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">should</span><span class="params">(<span name="rightMatcher">rightMatcher: <a href="Matcher.html" class="extype" name="org.scalatest.matchers.Matcher">Matcher</a>[<span class="extype" name="scala.Long">Long</span>]</span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<p class="shortcomment cmt">This method enables syntax such as the following:</p><div class="fullcomment"><div class="comment cmt"><p>This method enables syntax such as the following:</p><p><pre class="stHighlighted">
aLong should equal (<span class="stLiteral">3L</span>)
^
</pre>
</p></div></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a>
<a id="synchronized[T0](⇒T0):T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<a id="toString():String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a>
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a>
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</html> | {
"content_hash": "c7f619ebe33c5a78f4f5ac9771f51d03",
"timestamp": "",
"source": "github",
"line_count": 500,
"max_line_length": 510,
"avg_line_length": 51.908,
"alnum_prop": 0.5982507513292749,
"repo_name": "scalatest/scalatest-website",
"id": "898b80f396cc938fe10f9e9242b0337cead5d644",
"size": "25968",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/scaladoc/1.9.1/org/scalatest/matchers/ShouldMatchers$LongShouldWrapper.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8401192"
},
{
"name": "HTML",
"bytes": "4508833233"
},
{
"name": "JavaScript",
"bytes": "12256885"
},
{
"name": "Procfile",
"bytes": "62"
},
{
"name": "Scala",
"bytes": "136544"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/menu_slide"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
| {
"content_hash": "7f226942cd883d177de18c91be69a53c",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 71,
"avg_line_length": 34.57142857142857,
"alnum_prop": 0.7066115702479339,
"repo_name": "efrozaq/DailyQuotes",
"id": "37477fa53f95574aa912b420f059722f698850f8",
"size": "242",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/menu_slide.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "256863"
}
],
"symlink_target": ""
} |
"""
=================================================
fastas.py
=================================================
Purpose:
"""
import collections
import gzip
import os
import sys
import tempfile
import math
from spartan.utils.errors import InvalidFileFormatError, SanityCheckError
from spartan.utils.externals import run_external_app
from spartan.utils.misc import fold_seq
__author__ = 'Gus Dunn'
class ParseFastA(object):
"""Returns a record-by-record fastA parser analogous to file.readline()."""
def __init__(self, filePath, joinWith='', key=None):
"""Returns a record-by-record fastA parser analogous to file.readline().
Exmpl: parser.next()
Its ALSO an iterator so "for rec in parser" works too!
<joinWith> is string to use to join rec lines with.
joinWith='' results in a single line with no breaks (usually what you want!)
<key> is func used to parse the recName from HeaderInfo.
"""
if filePath.endswith('.gz'):
self._file = gzip.open(filePath)
else:
self._file = open(filePath, 'rU')
if key:
self._key = key
else:
self._key = lambda x:x[1:].split()[0]
self.bufferLine = None # stores next headerLine between records.
self.joinWith = joinWith
self._stop = False
def __iter__(self):
return self
def next(self):
"""Reads in next element, parses, and does minimal verification.
Returns: tuple: (seqName,seqStr)"""
if not self._stop:
pass
else:
raise StopIteration
# ++++ Get A Record ++++
recHead = ''
recData = []
# ++++ Check to see if we already have a headerLine ++++
if self.bufferLine:
recHead = self.bufferLine
else:
# ++++ If not, seek one ++++
while 1:
try:
line = self._file.next()
except StopIteration:
self._stop = True
break
if line.startswith('>'):
recHead = line
break
elif not line:
raise InvalidFileFormatError, "CheckFastaFile: Encountered EOF before any data."
elif line == '\n':
continue
else:
raise InvalidFileFormatError, 'CheckFastaFile: The first line containing text does not start with ">".'
# ++++ Collect recData ++++
while 1:
try:
line = self._file.next()
except StopIteration:
self._stop = True
break
if line.startswith('>'):
self.bufferLine = line.strip('\n')
break
elif not line.startswith('>'):
recData.append(line.strip('\n'))
# ++++ Minor Seq Validation ++++
## AddHere
# ++++ Format Rec For Return ++++
if not recData:
recHead = self._key(recHead)
return (recHead,'')
else:
recHead = self._key(recHead)
return (recHead,self.joinWith.join(recData))
def to_dict(self):
"""Returns a single Dict populated with the fastaRecs
contained in self._file."""
fasDict = {}
while 1:
try:
fasRec = self.next()
except StopIteration:
break
if fasRec:
if not fasRec[0] in fasDict:
fasDict[fasRec[0]] = fasRec[1]
else:
raise InvalidFileFormatError, "DuplicateFastaRec: %s occurs in your file more than once."
else:
break
return fasDict
def rewrite_headers(self, outPath, lineLen=70, delim=' ', order=[], ow=False, chmod=755):
"""
PURPOSE
* reorganize the headers of a fasta file:
>supercontig:CpipQ1:supercont3.1:1:3873040:1 supercontig supercont3.1
to
>supercont3.1 supercontig:CpipQ1:supercont3.1:1:3873040:1 supercontig
NOTES
1) If ow, ignores outPath
2) delim is what to spilt on
3) order is a list of index numbers from the original header, reorganized for the new header.
Exp: delim=' ',order=[2,0,1] would produce what is seen above.
4) chmod= set new file with this mode (exp: 755)
5) lineLen sets fastaSeq line length in new file.
"""
if ow:
outPath = tempfile.NamedTemporaryFile(suffix='.renamed.fas')
else:
outPath = open(outPath, 'w')
while 1:
try:
f = self.next()
except StopIteration:
break
fSplit = f[0].lstrip('>').rstrip('\n').split(delim)
newHead = delim.join([fSplit[x] for x in order])
outPath.write('>%s\n%s\n' % (newHead, '\n'.join(fold_seq(f[1], lineLen))))
self._file.close()
absPath = os.path.abspath
if ow:
outPath.flush()
outPath.delete = False
os.rename(absPath(outPath.name), absPath(self._file.name))
try:
chmodResult = run_external_app('chmod', '%s %s' % (chmod, absPath(self._file.name)))
except ExternalError as err:
sys.stderr.write('%s\n' % (err))
else:
try:
outPath.close()
chmodResult = run_external_app('chmod', '%s %s' % (chmod, absPath(outPath.name)))
except ExternalError as err:
sys.stderr.write('%s\n' % (err))
def rename_fasta_headers(in_path, out_path, header_func):
"""
:param in_path: path to original fasta file
:param out_path: path to future altered fasta file
:param header_func: function to take a header line and return an altered string version of it
:returns: `None`
GIVEN:
- in_path
- out_path
- header_func
DOES:
- Reads in in_path file one line at a time
- If the line is a fasta header (starts with '>')
uses header_func logic to rearrange the header and
writes out the changed line to out_path.
- If not a header, writes same line out to out_path.
- Closes both file objects.
RETURNS:
- None
"""
in_file = open(in_path,'rU')
out_file = open(out_path,'w')
for line in in_file:
if line.startswith('>'):
line = header_func(line)
# Handle and ensure that each modified line has one and only one \n
line = line.rstrip('\n') + '\n'
else:
pass
out_file.write(line)
in_file.close()
out_file.close()
def fastaRec_length_indexer(fastaFiles):
"""
GIVEN:
1) fastaFiles: list of fasta files or dirs containing fasta files
DO:
1) iterate through all fasta files recording recName and length to a dict
RETURN:
1) dict with recName and lengths
NOTES:
1) will complain if it sees more than one fastaRec with the same name ONLY
if one of the length values disagrees with those already seen.
"""
recDict = {}
seqDict = {}
tmpDict = collections.defaultdict(list)
for each in fastaFiles:
try:
# if each is a directory, measure all recs in all fasta files in that dir (ignore subdirs)
paths = os.listdir(each)
for p in paths:
try:
p = ParseFastA(p)
for name,seq in p:
tmpDict[name].append(len(seq))
seqDict[name] = seq
except IOError:
# most likely p was a dir, ignore
## TODO: logging code here to inform when this happens
pass
except InvalidFileFormatError:
# most likely p did not have valid fasta format, ignore
## TODO: logging code here to inform when this happens
pass
except OSError as errTxt:
if not ('Not a directory' in errTxt):
raise
else:
# if each is a file, measure all recs in file
try:
p = ParseFastA(each)
for name,seq in p:
tmpDict[name].append(len(seq))
seqDict[name] = seq
except InvalidFileFormatError:
# most likely p did not have valid fasta format, ignore
## TODO: logging code here to inform when this happens
pass
for rec,lengths in tmpDict.iteritems():
if not (len(set(lengths)) == 1):
# SANITY_CHECK: make sure that any duplicate fastaRecs gave the same length, if not: complain and die
raise SanityCheckError("Encountered fastaRec with lengths that do not agree: %s:%s" % (rec,lengths))
else:
# consolodate the lengths lists to a single number
recDict[rec] = lengths[0]
return (recDict,seqDict)
def count_fasta_recs_in_file(fasta_path):
"""
Returns number of records contained in a fasta file.
:param fasta_path: Path to fasta file
"""
return len(ParseFastA(fasta_path).to_dict().keys())
def divide_fasta_file(fasta_path, divide_by=2, out_path_base=None):
"""
Returns tuple of paths to resulting files.
Splits and writes out records in ``fasta_path`` to new files.
Default ``out_path_base`` derived from ``fasta_path``.
:param fasta_path: Path to fasta file
:param divide_by: Number of files to divide the fasta records into
:param out_path_base: Base path for resulting fasta files
"""
assert isinstance(divide_by, int)
num_fastas = count_fasta_recs_in_file(fasta_path)
recs_per_file = math.ceil(num_fastas/divide_by)
out_paths = []
ext = '.fas'
if out_path_base is None:
out_path_base, ext = os.path.splitext(fasta_path)
out_path_template = "{out_base}.{file_num}{ext}"
fasta_seq_template = ">{header}\n{seq_lines}\n"
for index, (header, seq) in enumerate(ParseFastA(fasta_path).to_dict().iteritems()):
# create a switch after every `recs_per_file` records that opens a new file for writing
if index % recs_per_file == 0:
current_out_path = out_path_template.format(out_base=out_path_base,
file_num=index,
ext=ext)
# Record out_path
out_paths.append(current_out_path)
# Close current file if it exists
try:
out_file.close()
except NameError:
pass
# create new out_file with current path
out_file = open(current_out_path, 'w')
# with this fasta dict item,
# fold seqs into '\n' delimited string
# append to new header
# write to file
seq_lines = fold_seq(seq, lineLen=100)
fasta_record = fasta_seq_template.format(header=header,
seq_lines='\n'.join(seq_lines))
out_file.write(fasta_record)
return out_paths
| {
"content_hash": "407bfd05c58ef49d113f6b1a4c49e282",
"timestamp": "",
"source": "github",
"line_count": 349,
"max_line_length": 123,
"avg_line_length": 32.7163323782235,
"alnum_prop": 0.5380977404098791,
"repo_name": "xguse/spartan",
"id": "1b5fc6d0311fdf7dc219846a5f59ca1f6ab52d22",
"size": "11590",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/spartan/utils/fastas.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "118082"
}
],
"symlink_target": ""
} |
#include <string>
#include <LibUtilities/Memory/NekMemoryManager.hpp>
#include <PulseWaveSolver/EquationSystems/PulseWaveBoundary.h>
namespace Nektar
{
// Forward declarations
class UndefinedInOutflow;
/// Pointer to a PulseWaveOutflow object.
typedef boost::shared_ptr<UndefinedInOutflow> UndefinedInOutflowSharedPtr;
/// A global linear system.
class UndefinedInOutflow : public PulseWaveBoundary
{
public:
/// Creates an instance of this class
static PulseWaveBoundarySharedPtr create(Array<OneD, MultiRegions::ExpListSharedPtr>& pVessel,
const LibUtilities::SessionReaderSharedPtr& pSession,
PulseWavePressureAreaSharedPtr& pressureArea)
{
return MemoryManager<UndefinedInOutflow>::AllocateSharedPtr(pVessel,pSession,pressureArea);
}
/// Name of class
static std::string className;
UndefinedInOutflow(Array<OneD, MultiRegions::ExpListSharedPtr> pVessel,
const LibUtilities::SessionReaderSharedPtr pSession,
PulseWavePressureAreaSharedPtr pressureArea);
virtual ~UndefinedInOutflow();
protected:
virtual void v_DoBoundary(
const Array<OneD,const Array<OneD, NekDouble> > &inarray,
Array<OneD, Array<OneD, NekDouble> > &A_0,
Array<OneD, Array<OneD, NekDouble> > &beta,
const NekDouble time,
int omega,int offset,int n);
private:
};
}
#endif
| {
"content_hash": "b5926a25c4c6b839342778415e9812c5",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 103,
"avg_line_length": 35.255319148936174,
"alnum_prop": 0.6125528062764032,
"repo_name": "certik/nektar",
"id": "4468f5f9fef71c536579ebbbf3845898d4c69797",
"size": "3460",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "solvers/PulseWaveSolver/EquationSystems/UndefinedInOutflow.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "97273"
},
{
"name": "C++",
"bytes": "14353038"
},
{
"name": "CMake",
"bytes": "249012"
},
{
"name": "GLSL",
"bytes": "16406"
},
{
"name": "Objective-C",
"bytes": "3161"
},
{
"name": "Scilab",
"bytes": "375620"
},
{
"name": "Shell",
"bytes": "16892"
}
],
"symlink_target": ""
} |
package org.fusesource.gateway.fabric.config;
import org.apache.curator.framework.CuratorFramework;
import org.fusesource.common.util.Strings;
import org.fusesource.fabric.zookeeper.ZkPath;
import org.fusesource.gateway.ServiceMap;
import org.fusesource.gateway.fabric.FabricGateway;
import org.fusesource.gateway.fabric.GatewayListener;
import org.fusesource.gateway.handlers.Gateway;
import org.fusesource.gateway.handlers.http.HttpGateway;
import org.fusesource.gateway.handlers.tcp.TcpGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vertx.java.core.Vertx;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a listener
*/
public class ListenConfig {
private static final transient Logger LOG = LoggerFactory.getLogger(ListenConfig.class);
private int port;
private String host;
private String protocol;
private List<RuleConfig> rules = new ArrayList<RuleConfig>();
@Override
public String toString() {
return "ListenConfig{" +
"protocol='" + protocol + '\'' +
", port=" + port +
", host='" + host + '\'' +
", rules=" + rules +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ListenConfig that = (ListenConfig) o;
if (port != that.port) return false;
if (host != null ? !host.equals(that.host) : that.host != null) return false;
if (protocol != null ? !protocol.equals(that.protocol) : that.protocol != null) return false;
if (rules != null ? !rules.equals(that.rules) : that.rules != null) return false;
return true;
}
@Override
public int hashCode() {
int result = port;
result = 31 * result + (host != null ? host.hashCode() : 0);
result = 31 * result + (protocol != null ? protocol.hashCode() : 0);
result = 31 * result + (rules != null ? rules.hashCode() : 0);
return result;
}
public boolean isWebProtocol() {
return protocol == null || protocol.equals("http") || protocol.equals("https");
}
/**
* Factory method to create a new gateway for this configuration
*/
public Gateway createGateway(FabricGateway owner, ServiceMap serviceMap) {
Vertx vertx = owner.getVertx();
Gateway answer;
if (isWebProtocol()) {
answer = new HttpGateway(vertx, serviceMap, port);
} else {
answer = new TcpGateway(vertx, serviceMap, port, protocol);
}
if (Strings.isNotBlank(host)) {
answer.setHost(host);
}
return answer;
}
// Properties
//-------------------------------------------------------------------------
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public List<RuleConfig> getRules() {
return rules;
}
public void setRules(List<RuleConfig> rules) {
this.rules = rules;
}
}
| {
"content_hash": "b47933fc753278279e265bd2f9e9156a",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 101,
"avg_line_length": 28.223140495867767,
"alnum_prop": 0.5991215226939971,
"repo_name": "gnodet/fuse",
"id": "1aee8824eb9d27f9357c40814e8f621b2df2d738",
"size": "4038",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "gateway/gateway-fabric/src/main/java/org/fusesource/gateway/fabric/config/ListenConfig.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "345444"
},
{
"name": "CoffeeScript",
"bytes": "278706"
},
{
"name": "Java",
"bytes": "7881745"
},
{
"name": "JavaScript",
"bytes": "2481282"
},
{
"name": "Kotlin",
"bytes": "14362"
},
{
"name": "Scala",
"bytes": "484463"
},
{
"name": "Shell",
"bytes": "21380"
},
{
"name": "XSLT",
"bytes": "26098"
}
],
"symlink_target": ""
} |
'use strict';
/**
* Returns the data label.
*
* @private
* @returns {string} label
*/
function get() {
/* eslint-disable no-invalid-this */
return this._label;
}
// EXPORTS //
module.exports = get;
| {
"content_hash": "2306611d2c800eecf8de36fb8d80eabc",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 37,
"avg_line_length": 10.842105263157896,
"alnum_prop": 0.6213592233009708,
"repo_name": "stdlib-js/stdlib",
"id": "0288e4ed674b2eb5e213d295dfceaf44b9fd7053",
"size": "822",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "lib/node_modules/@stdlib/plot/sparklines/base/ctor/lib/props/label/get.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "21739"
},
{
"name": "C",
"bytes": "15336495"
},
{
"name": "C++",
"bytes": "1349482"
},
{
"name": "CSS",
"bytes": "58039"
},
{
"name": "Fortran",
"bytes": "198059"
},
{
"name": "HTML",
"bytes": "56181"
},
{
"name": "Handlebars",
"bytes": "16114"
},
{
"name": "JavaScript",
"bytes": "85975525"
},
{
"name": "Julia",
"bytes": "1508654"
},
{
"name": "Makefile",
"bytes": "4806816"
},
{
"name": "Python",
"bytes": "3343697"
},
{
"name": "R",
"bytes": "576612"
},
{
"name": "Shell",
"bytes": "559315"
},
{
"name": "TypeScript",
"bytes": "19309407"
},
{
"name": "WebAssembly",
"bytes": "5980"
}
],
"symlink_target": ""
} |
package logs_test
import (
. "github.com/cloudfoundry/cli/cf/api/logs"
"github.com/cloudfoundry/sonde-go/events"
"github.com/gogo/protobuf/proto"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("NoaaMessageQueue", func() {
It("sorts messages based on their timestamp, clearing after it's enumerated over", func() {
pq := NewNoaaMessageQueue()
msg3 := noaaMessageWithTime("message 3", 130)
msg2 := noaaMessageWithTime("message 2", 120)
msg4 := noaaMessageWithTime("message 4", 140)
msg1 := noaaMessageWithTime("message 1", 110)
pq.PushMessage(msg3)
pq.PushMessage(msg2)
pq.PushMessage(msg4)
pq.PushMessage(msg1)
var messages []*events.LogMessage
pq.EnumerateAndClear(func(m *events.LogMessage) {
messages = append(messages, m)
})
Expect(messages).To(Equal([]*events.LogMessage{
msg1,
msg2,
msg3,
msg4,
}))
var messagesAfter []*events.LogMessage
pq.EnumerateAndClear(func(m *events.LogMessage) {
messagesAfter = append(messagesAfter, m)
})
Expect(messagesAfter).To(BeEmpty())
})
})
func noaaMessageWithTime(messageString string, timestamp int) *events.LogMessage {
return generateNoaaMessage(messageString, int64(timestamp))
}
func generateNoaaMessage(messageString string, timestamp int64) *events.LogMessage {
messageType := events.LogMessage_OUT
sourceType := "DEA"
return &events.LogMessage{
Message: []byte(messageString),
AppId: proto.String("my-app-guid"),
MessageType: &messageType,
SourceType: &sourceType,
Timestamp: proto.Int64(timestamp),
}
}
| {
"content_hash": "b7df7620ff4e64446ec4030d9fbf0704",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 92,
"avg_line_length": 25.467741935483872,
"alnum_prop": 0.7169094363521216,
"repo_name": "mcintyred/cli",
"id": "812dcc2d57b820f0a2cdc90e7bb18748ef6ae9cb",
"size": "1579",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "cf/api/logs/noaa_message_queue_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3724"
},
{
"name": "Go",
"bytes": "5963597"
},
{
"name": "HTML",
"bytes": "1728"
},
{
"name": "Inno Setup",
"bytes": "1837"
},
{
"name": "PowerShell",
"bytes": "667"
},
{
"name": "Ruby",
"bytes": "1775"
},
{
"name": "Shell",
"bytes": "7484"
}
],
"symlink_target": ""
} |
namespace mojo {
TraceProviderImpl::TraceProviderImpl()
: binding_(this), tracing_forced_(false), weak_factory_(this) {}
TraceProviderImpl::~TraceProviderImpl() {}
void TraceProviderImpl::Bind(InterfaceRequest<tracing::TraceProvider> request) {
if (!binding_.is_bound()) {
binding_.Bind(std::move(request));
} else {
LOG(ERROR) << "Cannot accept two connections to TraceProvider.";
}
}
void TraceProviderImpl::StartTracing(const String& categories,
tracing::TraceRecorderPtr recorder) {
DCHECK(!recorder_);
recorder_ = std::move(recorder);
tracing_forced_ = false;
if (!base::trace_event::TraceLog::GetInstance()->IsEnabled()) {
std::string categories_str = categories.To<std::string>();
base::trace_event::TraceLog::GetInstance()->SetEnabled(
base::trace_event::TraceConfig(categories_str,
base::trace_event::RECORD_UNTIL_FULL),
base::trace_event::TraceLog::RECORDING_MODE);
}
}
void TraceProviderImpl::StopTracing() {
DCHECK(recorder_);
base::trace_event::TraceLog::GetInstance()->SetDisabled();
base::trace_event::TraceLog::GetInstance()->Flush(
base::Bind(&TraceProviderImpl::SendChunk, base::Unretained(this)));
}
void TraceProviderImpl::ForceEnableTracing() {
base::trace_event::TraceLog::GetInstance()->SetEnabled(
base::trace_event::TraceConfig("*", base::trace_event::RECORD_UNTIL_FULL),
base::trace_event::TraceLog::RECORDING_MODE);
tracing_forced_ = true;
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&TraceProviderImpl::DelayedStop, weak_factory_.GetWeakPtr()));
}
void TraceProviderImpl::DelayedStop() {
// We use this indirection to account for cases where the Initialize app
// method (within which TraceProviderImpl is created) takes more than one
// second to finish; thus we start the countdown only when the current thread
// is unblocked.
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&TraceProviderImpl::StopIfForced, weak_factory_.GetWeakPtr()),
base::TimeDelta::FromSeconds(1));
}
void TraceProviderImpl::StopIfForced() {
if (!tracing_forced_) {
return;
}
base::trace_event::TraceLog::GetInstance()->SetDisabled();
base::trace_event::TraceLog::GetInstance()->Flush(
base::Callback<void(const scoped_refptr<base::RefCountedString>&,
bool)>());
}
void TraceProviderImpl::SendChunk(
const scoped_refptr<base::RefCountedString>& events_str,
bool has_more_events) {
DCHECK(recorder_);
// The string will be empty if an error eccured or there were no trace
// events. Empty string is not a valid chunk to record so skip in this case.
if (!events_str->data().empty()) {
recorder_->Record(mojo::String(events_str->data()));
}
if (!has_more_events) {
recorder_.reset();
}
}
} // namespace mojo
| {
"content_hash": "f83a6a2059d10065460fcdcb9fc652ab",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 80,
"avg_line_length": 35.325301204819276,
"alnum_prop": 0.6753069577080492,
"repo_name": "joone/chromium-crosswalk",
"id": "d37149e73fb77a2820f6d1aa6a0bf64370aeddd3",
"size": "3496",
"binary": false,
"copies": "6",
"ref": "refs/heads/2016.04.css-round-display-edtior-draft-1",
"path": "mojo/services/tracing/public/cpp/trace_provider_impl.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/modules/PageObjects-example.iml" filepath="$PROJECT_DIR$/.idea/modules/PageObjects-example.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/modules/PageObjects-example_main.iml" filepath="$PROJECT_DIR$/.idea/modules/PageObjects-example_main.iml" group="PageObjects-example" />
<module fileurl="file://$PROJECT_DIR$/.idea/modules/PageObjects-example_test.iml" filepath="$PROJECT_DIR$/.idea/modules/PageObjects-example_test.iml" group="PageObjects-example" />
</modules>
</component>
</project> | {
"content_hash": "9b26f2d147fcc8c435aded16b6cd2dd4",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 186,
"avg_line_length": 68,
"alnum_prop": 0.7220588235294118,
"repo_name": "tkulaha/SeWebDriver_Homework",
"id": "bcf3d47767824b03e8bcdc0a5c9950f8f596d778",
"size": "680",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Exercise11.19/.idea/modules.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "69687"
}
],
"symlink_target": ""
} |
function PQUEUE_2 (processArray, initialProcessID, queueName) {
"use strict";
if (typeof processArray !== 'object') return;
return new function () {
var _self = this;
var _pstat = {
ticking : false,
error : false,
autoProceed : false,
/* name of queue */
name : String(queueName ? queueName : (new Date()).getTime()),
/* array of processes */
processes : [],
processIndex : [],
/* process counter */
pc : 0,
};
/* for temporary storage for processes */
var _heap = {};
/* helper functions */
function _overflow () {
return _pstat.pc >= _pstat.processes.length;
}
function _error () {
_pstat.error = true;
}
function _isFunction (object) {
return typeof object === 'function';
}
function _isHalt (process) {
return process === PQUEUE_HALT;
}
/* start running */
this.tick = function () {
/* if already ticking, halt */
if (_pstat.ticking) return;
_pstat.ticking = true;
// console.group('PQUEUE[' + prototype.name + '].tick');
/* autoProceed by default */
_pstat.autoProceed = true;
/* cant process with error */
if (_pstat.error !== false) {
// console.warn('error');
} else {
// console.log('PC = %i', prototype.pc);
if (_overflow()) {
// console.warn('stack overflow');
_error();
} else {
var currentProcess = _pstat.processes[_pstat.pc];
if (!_isFunction(currentProcess)) {
// console.warn('invalid current process');
_error();
} else if (_isHalt(currentProcess)) {
// console.log('halt');
} else {
++_pstat.pc;
// console.log('PC = %i', prototype.pc);
/**
* pass _api over so client script
* can only harm _api
*/
var _api = {
heap : _heap,
heap_dump : function () {
var result = '';
for (var key in _heap) {
if (result !== '') result += ', \n';
result += key + ':' + _heap[key];
}
return '{\n' + result + '\n}';
},
wait : function () {_pstat.autoProceed = false;},
walk : function () {_pstat.autoProceed = true;_self.tick();},
pc : {
increment : function () {++_pstat.pc;},
decrement : function () {--_pstat.pc;},
offset : function (value) {_pstat.pc += Number(value) || 0;},
goto : function (value) {_pstat.pc = Number(value) || -1;},
locate : function (funcName) {return _pstat.processIndex[String(funcName)] || -1;}
}
};
currentProcess.call(_api, _api);
}
}
}
_pstat.ticking = false;
// console.groupEnd();
if (_pstat.autoProceed === true)
window.setTimeout(function () {_self.tick()}, 0);
};
for (var key in processArray) {
var process = processArray[key];
var index = _pstat.processes.length;
var name = process.name;
_pstat.processes.push(process);
if (name !== '')
_pstat.processIndex[name] = index;
}
_pstat.pc = parseInt(initialProcessID, 10) || 0;
};
}
function PQUEUE_HALT (q) {}
if (typeof PQUEUE == 'undefined') var PQUEUE = PQUEUE_2; | {
"content_hash": "cf1d727ceffab06949e800ab3cf6b28d",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 90,
"avg_line_length": 28.89622641509434,
"alnum_prop": 0.5566438132549788,
"repo_name": "Zodiase/PQUEUE",
"id": "d3655a3fb076ac43645ffffed543e6cade0136d4",
"size": "3156",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "archive/2.0.0.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "134151"
}
],
"symlink_target": ""
} |
//-CRE-
using Glass.Mapper.Configuration;
namespace Glass.Mapper.Sc.Configuration
{
/// <summary>
/// Class SitecoreNodeConfiguration
/// </summary>
public class SitecoreNodeConfiguration : NodeConfiguration
{
}
}
| {
"content_hash": "7d86d61dbbab624832be363ab7b4dee2",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 62,
"avg_line_length": 13,
"alnum_prop": 0.6639676113360324,
"repo_name": "efocus-nl/sugnl-demo",
"id": "cec068d4eab05534f8fd352bc58cb6df98483170",
"size": "841",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "packages/BoC.Glass.Mapper.Sc.1.0.3/src/Source/Glass.Mapper.Sc/Configuration/SitecoreNodeConfiguration.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "134"
},
{
"name": "C#",
"bytes": "12595"
},
{
"name": "CSS",
"bytes": "632"
}
],
"symlink_target": ""
} |
package client
import (
"errors"
"fmt"
"golang.org/x/net/context"
"github.com/docker/engine-api/types"
Cli "github.com/hyperhq/hypercli/cli"
"github.com/hyperhq/hypercli/pkg/jsonmessage"
flag "github.com/hyperhq/hypercli/pkg/mflag"
"github.com/hyperhq/hypercli/reference"
"github.com/hyperhq/hypercli/registry"
)
// CmdPull pulls an image or a repository from the registry.
//
// Usage: docker pull [OPTIONS] IMAGENAME[:TAG|@DIGEST]
func (cli *DockerCli) CmdPull(args ...string) error {
cmd := Cli.Subcmd("pull", []string{"NAME[:TAG|@DIGEST]"}, Cli.DockerCommands["pull"].Description, true)
allTags := cmd.Bool([]string{}, false, "Download all tagged images in the repository")
addTrustedFlags(cmd, true)
cmd.Require(flag.Exact, 1)
cmd.ParseFlags(args, true)
remote := cmd.Arg(0)
distributionRef, err := reference.ParseNamed(remote)
if err != nil {
return err
}
if *allTags && !reference.IsNameOnly(distributionRef) {
return errors.New("tag can't be used with --all-tags/-a")
}
if err = cli.checkCloudConfig(); err != nil {
return err
}
if !*allTags && reference.IsNameOnly(distributionRef) {
distributionRef = reference.WithDefaultTag(distributionRef)
fmt.Fprintf(cli.out, "Using default tag: %s\n", reference.DefaultTag)
}
var tag string
switch x := distributionRef.(type) {
case reference.Canonical:
tag = x.Digest().String()
case reference.NamedTagged:
tag = x.Tag()
}
ref := registry.ParseReference(tag)
// Resolve the Repository name from fqn to RepositoryInfo
repoInfo, err := registry.ParseRepositoryInfo(distributionRef)
if err != nil {
return err
}
ctx := context.Background()
authConfig := cli.resolveAuthConfig(ctx, cli.configFile.AuthConfigs, repoInfo.Index)
requestPrivilege := cli.registryAuthenticationPrivilegedFunc(repoInfo.Index, "pull")
if isTrusted() && !ref.HasDigest() {
// Check if tag is digest
return cli.trustedPull(ctx, repoInfo, ref, authConfig, requestPrivilege)
}
return cli.imagePullPrivileged(ctx, authConfig, distributionRef.String(), requestPrivilege, *allTags)
}
func (cli *DockerCli) imagePullPrivileged(ctx context.Context, authConfig types.AuthConfig, ref string, requestPrivilege types.RequestPrivilegeFunc, all bool) error {
encodedAuth, err := encodeAuthToBase64(authConfig)
if err != nil {
return err
}
options := types.ImagePullOptions{
PrivilegeFunc: requestPrivilege,
RegistryAuth: encodedAuth,
All: all,
}
responseBody, err := cli.client.ImagePull(context.Background(), ref, options)
if err != nil {
return err
}
defer responseBody.Close()
return jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut, nil)
}
| {
"content_hash": "775abb5d899f0dd62d0d0c773e31cbb4",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 166,
"avg_line_length": 28.74468085106383,
"alnum_prop": 0.7331606217616581,
"repo_name": "imeoer/hypercli",
"id": "d033e26993804e4efe6e052b156dd41e067efbad",
"size": "2702",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/client/pull.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3652"
},
{
"name": "Go",
"bytes": "4496873"
},
{
"name": "Makefile",
"bytes": "5344"
},
{
"name": "PowerShell",
"bytes": "5978"
},
{
"name": "Shell",
"bytes": "353785"
},
{
"name": "Vim script",
"bytes": "1332"
}
],
"symlink_target": ""
} |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
namespace Lada.ComponentModel
{
[Serializable]
public class ObservableObject : INotifyPropertyChanged
{
#region INotifyPropertyChanged
/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region Methods
/// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
if (GetType().GetProperty(propertyName) == null)
{
string msg = "Invalid property name: " + propertyName;
if (this.ThrowOnInvalidPropertyName)
throw new Exception(msg);
else
Debug.Fail(msg);
}
}
#endregion
#region Overridables
/// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property's getter to return true.
/// </summary>
protected virtual bool ThrowOnInvalidPropertyName { get { return false; } }
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
VerifyPropertyName(e.PropertyName);
if (PropertyChanged != null)
PropertyChanged(this, e);
}
protected virtual void OnPropertyChanged(params string[] propertyNames)
{
if (PropertyChanged != null)
foreach(var propertyName in propertyNames)
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
| {
"content_hash": "c63ccecdd01aadf50a4d16eee58de680",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 81,
"avg_line_length": 30.578125,
"alnum_prop": 0.6755237608584568,
"repo_name": "rvuistin/WpfMouseWheelLib",
"id": "f6ba2041064943e44dac3b558a9a9fcd89f7f562",
"size": "1959",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Lib/ComponentModel/ObservableObject.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "293386"
}
],
"symlink_target": ""
} |
By Pauli "Gwaur" Marttinen
Just a simple ircbot project in C# for the purposes of programming practice and irc fun.
| {
"content_hash": "ee4ea02487ec8104b3d8456a81141c0e",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 88,
"avg_line_length": 39,
"alnum_prop": 0.7863247863247863,
"repo_name": "Gwaur/ircbot",
"id": "07b261cb5da5ec2bc4cb0dc61421847892c1a632",
"size": "126",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3039"
},
{
"name": "Shell",
"bytes": "51"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>lxml.etree.ETCompatXMLParser</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="lxml-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://codespeak.net/lxml/">lxml API</a></th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="lxml-module.html">Package lxml</a> ::
<a href="lxml.etree-module.html">Module etree</a> ::
Class ETCompatXMLParser
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="lxml.etree.ETCompatXMLParser-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class ETCompatXMLParser</h1><p class="nomargin-top"></p>
<pre class="base-tree">
object --+
|
<a href="lxml.etree._BaseParser-class.html" onclick="show_private();">_BaseParser</a> --+
|
<a href="lxml.etree._FeedParser-class.html" onclick="show_private();">_FeedParser</a> --+
|
<a href="lxml.etree.XMLParser-class.html">XMLParser</a> --+
|
<strong class="uidshort">ETCompatXMLParser</strong>
</pre>
<hr />
<p>ETCompatXMLParser(self, encoding=None, attribute_defaults=False, dtd_validation=False, load_dtd=False, no_network=True, ns_clean=False, recover=False, schema=None, huge_tree=False, remove_blank_text=False, resolve_entities=True, remove_comments=True, remove_pis=True, strip_cdata=True, target=None, compact=True)</p>
<p>An XML parser with an ElementTree compatible default setup.</p>
<p>See the XMLParser class for details.</p>
<p>This parser has <tt class="rst-docutils literal">remove_comments</tt> and <tt class="rst-docutils literal">remove_pis</tt> enabled by default
and thus ignores comments and processing instructions.</p>
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="lxml.etree.ETCompatXMLParser-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">encoding</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">attribute_defaults</span>=<span class="summary-sig-default">False</span>,
<span class="summary-sig-arg">dtd_validation</span>=<span class="summary-sig-default">False</span>,
<span class="summary-sig-arg">load_dtd</span>=<span class="summary-sig-default">False</span>,
<span class="summary-sig-arg">no_network</span>=<span class="summary-sig-default">True</span>,
<span class="summary-sig-arg">ns_clean</span>=<span class="summary-sig-default">False</span>,
<span class="summary-sig-arg">recover</span>=<span class="summary-sig-default">False</span>,
<span class="summary-sig-arg">schema</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">huge_tree</span>=<span class="summary-sig-default">False</span>,
<span class="summary-sig-arg">remove_blank_text</span>=<span class="summary-sig-default">False</span>,
<span class="summary-sig-arg">resolve_entities</span>=<span class="summary-sig-default">True</span>,
<span class="summary-sig-arg">remove_comments</span>=<span class="summary-sig-default">True</span>,
<span class="summary-sig-arg">remove_pis</span>=<span class="summary-sig-default">True</span>,
<span class="summary-sig-arg">strip_cdata</span>=<span class="summary-sig-default">True</span>,
<span class="summary-sig-arg">target</span>=<span class="summary-sig-default">None</span>,
<span class="summary-sig-arg">compact</span>=<span class="summary-sig-default">True</span>)</span><br />
x.__init__(...) initializes x; see x.__class__.__doc__ for signature</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type">a new object with type S, a subtype of T</span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="lxml.etree.ETCompatXMLParser-class.html#__new__" class="summary-sig-name">__new__</a>(<span class="summary-sig-arg">T</span>,
<span class="summary-sig-arg">S</span>,
<span class="summary-sig-arg">...</span>)</span></td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="lxml.etree._FeedParser-class.html" onclick="show_private();">_FeedParser</a></code></b>:
<code><a href="lxml.etree._FeedParser-class.html#close">close</a></code>,
<code><a href="lxml.etree._FeedParser-class.html#feed">feed</a></code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="lxml.etree._BaseParser-class.html" onclick="show_private();">_BaseParser</a></code></b>:
<code><a href="lxml.etree._BaseParser-class.html#copy">copy</a></code>,
<code><a href="lxml.etree._BaseParser-class.html#makeelement">makeelement</a></code>,
<code><a href="lxml.etree._BaseParser-class.html#setElementClassLookup">setElementClassLookup</a></code>,
<code><a href="lxml.etree._BaseParser-class.html#set_element_class_lookup">set_element_class_lookup</a></code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__delattr__</code>,
<code>__format__</code>,
<code>__getattribute__</code>,
<code>__hash__</code>,
<code>__reduce__</code>,
<code>__reduce_ex__</code>,
<code>__repr__</code>,
<code>__setattr__</code>,
<code>__sizeof__</code>,
<code>__str__</code>,
<code>__subclasshook__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== PROPERTIES ==================== -->
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="lxml.etree._FeedParser-class.html" onclick="show_private();">_FeedParser</a></code></b>:
<code><a href="lxml.etree._FeedParser-class.html#feed_error_log">feed_error_log</a></code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code><a href="lxml.etree._BaseParser-class.html" onclick="show_private();">_BaseParser</a></code></b>:
<code><a href="lxml.etree._BaseParser-class.html#error_log">error_log</a></code>,
<code><a href="lxml.etree._BaseParser-class.html#resolvers">resolvers</a></code>,
<code><a href="lxml.etree._BaseParser-class.html#target">target</a></code>,
<code><a href="lxml.etree._BaseParser-class.html#version">version</a></code>
</p>
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__class__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== METHOD DETAILS ==================== -->
<a name="section-MethodDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Method Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-MethodDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="__init__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">encoding</span>=<span class="sig-default">None</span>,
<span class="sig-arg">attribute_defaults</span>=<span class="sig-default">False</span>,
<span class="sig-arg">dtd_validation</span>=<span class="sig-default">False</span>,
<span class="sig-arg">load_dtd</span>=<span class="sig-default">False</span>,
<span class="sig-arg">no_network</span>=<span class="sig-default">True</span>,
<span class="sig-arg">ns_clean</span>=<span class="sig-default">False</span>,
<span class="sig-arg">recover</span>=<span class="sig-default">False</span>,
<span class="sig-arg">schema</span>=<span class="sig-default">None</span>,
<span class="sig-arg">huge_tree</span>=<span class="sig-default">False</span>,
<span class="sig-arg">remove_blank_text</span>=<span class="sig-default">False</span>,
<span class="sig-arg">resolve_entities</span>=<span class="sig-default">True</span>,
<span class="sig-arg">remove_comments</span>=<span class="sig-default">True</span>,
<span class="sig-arg">remove_pis</span>=<span class="sig-default">True</span>,
<span class="sig-arg">strip_cdata</span>=<span class="sig-default">True</span>,
<span class="sig-arg">target</span>=<span class="sig-default">None</span>,
<span class="sig-arg">compact</span>=<span class="sig-default">True</span>)</span>
<br /><em class="fname">(Constructor)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
<dl class="fields">
<dt>Overrides:
object.__init__
</dt>
</dl>
</td></tr></table>
</div>
<a name="__new__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__new__</span>(<span class="sig-arg">T</span>,
<span class="sig-arg">S</span>,
<span class="sig-arg">...</span>)</span>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<dl class="fields">
<dt>Returns: a new object with type S, a subtype of T</dt>
<dt>Overrides:
object.__new__
</dt>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="lxml-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://codespeak.net/lxml/">lxml API</a></th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Sun Feb 6 20:25:12 2011
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| {
"content_hash": "bf09dae9a8def89024e9260c693ed2cf",
"timestamp": "",
"source": "github",
"line_count": 347,
"max_line_length": 404,
"avg_line_length": 45.02593659942363,
"alnum_prop": 0.5895417306707629,
"repo_name": "rajendrakrp/GeoMicroFormat",
"id": "7f9600009d9765e37ec0bf3e650dce800eb87034",
"size": "15624",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/lxml/doc/html/api/lxml.etree.ETCompatXMLParser-class.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "8209471"
},
{
"name": "JavaScript",
"bytes": "107717"
},
{
"name": "Python",
"bytes": "6752796"
},
{
"name": "Shell",
"bytes": "627"
}
],
"symlink_target": ""
} |
require_relative "../test_helper"
require "stringio"
require "fileutils"
module SymmetricEncryption
class FileTest < Minitest::Test
describe SymmetricEncryption::Keystore::File do
let :the_test_path do
path = "tmp/keystore/file_test"
FileUtils.makedirs(path) unless ::File.exist?(path)
path
end
after do
# Cleanup generated encryption key files.
`rm #{the_test_path}/* 2> /dev/null`
end
describe ".generate_data_key" do
let :version do
10
end
let :key_config do
SymmetricEncryption::Keystore::File.generate_data_key(
key_path: the_test_path,
cipher_name: "aes-256-cbc",
app_name: "tester",
environment: "test",
version: version
)
end
it "increments the version" do
assert_equal 11, key_config[:version]
end
describe "with 255 version" do
let :version do
255
end
it "handles version wrap" do
assert_equal 1, key_config[:version]
end
end
describe "with 0 version" do
let :version do
0
end
it "increments version" do
assert_equal 1, key_config[:version]
end
end
it "creates the encrypted key file with the correct permissions" do
file_name = "#{the_test_path}/tester_test_v11.encrypted_key"
assert_equal file_name, key_config[:key_filename]
assert File.exist?(file_name)
assert_equal File.stat(file_name).mode.to_s(8), "100600"
end
it "retains cipher_name" do
assert_equal "aes-256-cbc", key_config[:cipher_name]
end
it "is readable by Key.from_config" do
key_config.delete(:version)
assert SymmetricEncryption::Keystore.read_key(**key_config)
end
end
describe "#write, #read" do
let :keystore do
SymmetricEncryption::Keystore::File.new(key_filename: "#{the_test_path}/tester.key", key_encrypting_key: SymmetricEncryption::Key.new)
end
after do
FileUtils.chmod 0o600, Dir.glob("#{the_test_path}/*")
end
it "stores the key" do
keystore.write("TEST")
assert_equal "TEST", keystore.read
end
it "raises an exception when the file can be read/written by others" do
keystore.write("TEST")
FileUtils.chmod 0o666, Dir.glob("#{the_test_path}/*")
assert_raises { keystore.read }
end
end
end
end
end
| {
"content_hash": "127af86100d37c6931a9870bf0ba09ee",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 144,
"avg_line_length": 27.54639175257732,
"alnum_prop": 0.5625,
"repo_name": "rocketjob/symmetric-encryption",
"id": "f10e53466157b46a626f8ed82f45c7ae93b67d02",
"size": "2672",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/keystore/file_test.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "250095"
}
],
"symlink_target": ""
} |
package org.locationtech.geomesa.core.process.query
import com.vividsolutions.jts.geom.Geometry
import org.geotools.data.DataStoreFinder
import org.geotools.factory.Hints
import org.geotools.feature.DefaultFeatureCollection
import org.geotools.filter.text.cql2.CQL
import org.joda.time.{DateTime, DateTimeZone}
import org.junit.runner.RunWith
import org.locationtech.geomesa.core.data.{AccumuloDataStore, AccumuloFeatureStore}
import org.locationtech.geomesa.core.index.Constants
import org.locationtech.geomesa.feature.AvroSimpleFeatureFactory
import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes
import org.locationtech.geomesa.utils.text.WKTUtils
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner
import scala.collection.JavaConversions._
@RunWith(classOf[JUnitRunner])
class QueryProcessTest extends Specification {
sequential
val dtgField = org.locationtech.geomesa.core.process.tube.DEFAULT_DTG_FIELD
val geotimeAttributes = s"*geom:Geometry:srid=4326,$dtgField:Date"
def createStore: AccumuloDataStore =
// the specific parameter values should not matter, as we
// are requesting a mock data store connection to Accumulo
DataStoreFinder.getDataStore(Map(
"instanceId" -> "mycloud",
"zookeepers" -> "zoo1:2181,zoo2:2181,zoo3:2181",
"user" -> "myuser",
"password" -> "mypassword",
"auths" -> "A,B,C",
"tableName" -> "testwrite",
"useMock" -> "true",
"featureEncoding" -> "avro")).asInstanceOf[AccumuloDataStore]
val sftName = "geomesaQueryTestType"
val sft = SimpleFeatureTypes.createType(sftName, s"type:String,$geotimeAttributes")
sft.getUserData()(Constants.SF_PROPERTY_START_TIME) = dtgField
val ds = createStore
ds.createSchema(sft)
val fs = ds.getFeatureSource(sftName).asInstanceOf[AccumuloFeatureStore]
val featureCollection = new DefaultFeatureCollection(sftName, sft)
List("a", "b").foreach { name =>
List(1, 2, 3, 4).zip(List(45, 46, 47, 48)).foreach { case (i, lat) =>
val sf = AvroSimpleFeatureFactory.buildAvroFeature(sft, List(), name + i.toString)
sf.setDefaultGeometry(WKTUtils.read(f"POINT($lat%d $lat%d)"))
sf.setAttribute(org.locationtech.geomesa.core.process.tube.DEFAULT_DTG_FIELD, new DateTime("2011-01-01T00:00:00Z", DateTimeZone.UTC).toDate)
sf.setAttribute("type", name)
sf.getUserData()(Hints.USE_PROVIDED_FID) = java.lang.Boolean.TRUE
featureCollection.add(sf)
}
}
// write the feature to the store
val res = fs.addFeatures(featureCollection)
"GeomesaQuery" should {
"return things without a filter" in {
val features = fs.getFeatures()
val geomesaQuery = new QueryProcess
val results = geomesaQuery.execute(features, null)
val f = results.features()
while (f.hasNext) {
val sf = f.next
sf.getAttribute("type") should beOneOf("a", "b")
}
results.size mustEqual 8
}
"respect a parent filter" in {
val features = fs.getFeatures(CQL.toFilter("type = 'b'"))
val geomesaQuery = new QueryProcess
val results = geomesaQuery.execute(features, null)
val f = results.features()
while (f.hasNext) {
val sf = f.next
sf.getAttribute("type") mustEqual "b"
}
results.size mustEqual 4
}
"be able to use its own filter" in {
val features = fs.getFeatures(CQL.toFilter("type = 'b' OR type = 'a'"))
val geomesaQuery = new QueryProcess
val results = geomesaQuery.execute(features, CQL.toFilter("type = 'a'"))
val f = results.features()
while (f.hasNext) {
val sf = f.next
sf.getAttribute("type") mustEqual "a"
}
results.size mustEqual 4
}
"properly query geometry" in {
val features = fs.getFeatures()
val geomesaQuery = new QueryProcess
val results = geomesaQuery.execute(features, CQL.toFilter("bbox(geom, 45.0, 45.0, 46.0, 46.0)"))
var poly = WKTUtils.read("POLYGON((45 45, 46 45, 46 46, 45 46, 45 45))")
val f = results.features()
while (f.hasNext) {
val sf = f.next
poly.intersects(sf.getDefaultGeometry.asInstanceOf[Geometry]) must beTrue
}
results.size mustEqual 4
}
}
}
| {
"content_hash": "9cc1ecfd56999cd6d484adba69c86903",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 146,
"avg_line_length": 32.84090909090909,
"alnum_prop": 0.6805074971164936,
"repo_name": "drmathochist/geomesa",
"id": "c69ff9f66bf587a2568af0057155ef4614b5eeb0",
"size": "4335",
"binary": false,
"copies": "2",
"ref": "refs/heads/accumulo1.5.x/1.x",
"path": "geomesa-core/src/test/scala/org/locationtech/geomesa/core/process/query/QueryProcessTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
//
// @author raver119@gmail.com
//
#ifndef DEV_TESTS_EXTRAARGUMENTS_H
#define DEV_TESTS_EXTRAARGUMENTS_H
#include <dll.h>
#include <initializer_list>
#include <vector>
#include <array/DataType.h>
#include <pointercast.h>
#include <stdlib.h>
namespace nd4j {
class ND4J_EXPORT ExtraArguments {
private:
std::vector<double> _fpArgs;
std::vector<Nd4jLong> _intArgs;
std::vector<Nd4jPointer> _pointers;
template <typename T>
void convertAndCopy(Nd4jPointer pointer, Nd4jLong offset);
void* allocate(size_t length, size_t elementSize);
public:
explicit ExtraArguments(std::initializer_list<double> arguments);
explicit ExtraArguments(std::initializer_list<Nd4jLong> arguments);
explicit ExtraArguments(const std::vector<double> &arguments);
explicit ExtraArguments(const std::vector<int> &arguments);
explicit ExtraArguments(const std::vector<Nd4jLong> &arguments);
explicit ExtraArguments();
~ExtraArguments();
template <typename T>
void* argumentsAsT(Nd4jLong offset = 0);
void* argumentsAsT(nd4j::DataType dataType, Nd4jLong offset = 0);
size_t length();
};
}
#endif //DEV_TESTS_EXTRAARGUMENTS_H
| {
"content_hash": "429255dd5bbe0d1b105be979d64b75a9",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 75,
"avg_line_length": 24.764705882352942,
"alnum_prop": 0.6745843230403801,
"repo_name": "RobAltena/deeplearning4j",
"id": "e1f5a69bddb9e587c8ec287c5657b2c7fc84beb6",
"size": "2024",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libnd4j/include/array/ExtraArguments.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2469"
},
{
"name": "C",
"bytes": "144275"
},
{
"name": "C#",
"bytes": "138404"
},
{
"name": "C++",
"bytes": "16954560"
},
{
"name": "CMake",
"bytes": "77377"
},
{
"name": "CSS",
"bytes": "10363"
},
{
"name": "Cuda",
"bytes": "2324886"
},
{
"name": "Dockerfile",
"bytes": "1329"
},
{
"name": "FreeMarker",
"bytes": "77045"
},
{
"name": "HTML",
"bytes": "38914"
},
{
"name": "Java",
"bytes": "36293636"
},
{
"name": "JavaScript",
"bytes": "436278"
},
{
"name": "PureBasic",
"bytes": "12256"
},
{
"name": "Python",
"bytes": "325018"
},
{
"name": "Ruby",
"bytes": "4558"
},
{
"name": "Scala",
"bytes": "355054"
},
{
"name": "Shell",
"bytes": "80490"
},
{
"name": "Smarty",
"bytes": "900"
},
{
"name": "Starlark",
"bytes": "931"
},
{
"name": "TypeScript",
"bytes": "80252"
}
],
"symlink_target": ""
} |
var pro1 = new Button({
type: 'submit',
'class': 'btn btn-success',
label: '<span class="glyphicon glyphicon-music"></span> Click Click',
onClick: function (e) {
console.info('Clicked?');
return false;
}
}, 'pro1');
pro1.startup(); | {
"content_hash": "64a82dfa6cca52fd000c1667fbd2964b",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 73,
"avg_line_length": 24.363636363636363,
"alnum_prop": 0.5783582089552238,
"repo_name": "sirprize/dojo-form-controls-doc",
"id": "394cf8e499919cb8605999327dff5688914a3cf0",
"size": "268",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "html/_includes/index/button.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "217490"
},
{
"name": "JavaScript",
"bytes": "647474"
},
{
"name": "Shell",
"bytes": "273"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4a964f61a5efa48e7144428d6ab0a38f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "79788a2f1b6b00bd7524bf914ac9a649f4c1f06f",
"size": "202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Anthemis calcarea discoidea/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef HTTP_CLIENT_CONNECTUION_H
#define HTTP_CLIENT_CONNECTUION_H
#include "config.h"
#include "MC2SimpleString.h"
#include <list>
class HttpClientConnectionListener;
class SharedBuffer;
class TCPConnectionHandler;
/**
* Class describing a asynchronous connection using TCP.
*/
class TCPClientConnection {
public:
/**
* Enum describing the status of the different calls.
*/
enum status_t {
/// All is done.
OK = 0,
/// Some error occured.
ERROR = -1,
/// A timout occured
TIMEOUT = -2,
/// An operation of the same kind has been requested already.
ALREADY_REQUESTED = -3,
/// The connection was closed
CLOSED = -4,
};
/**
* To be called when the connection is established or has
* failed.
*/
virtual void connectDone(status_t status) = 0;
/**
* To be called when the last read is done.
* @param status The status of the read.
*/
virtual void readDone(status_t status,
const byte* bytes,
int nbrBytes) = 0;
/**
* Informs the ClientConnection that the last write is completed.
* @param status The status of the write.
*/
virtual void writeDone(status_t status) = 0;
/**
* Informs the ClientConnection that the connection is closed.
*/
virtual void connectionClosed(status_t status) = 0;
/**
* Informs the ClientConnection that the timer with id
* timerID has expired.
*/
virtual void timerExpired(int timerID) = 0;
};
class HttpClientConnectionReader;
class HttpClientConnectionWriter;
/**
* Class that handles a HttpConnection to one host and port.
*/
class HttpClientConnection : public TCPClientConnection {
public:
friend class HttpClientConnectionReader;
/**
* State of the
*/
enum state_t {
NOT_CONNECTED = 0,
CONNECTED = 1,
} m_state;
/**
* Creates a new HttpClientConnection to the supplied
* host and port.
*/
HttpClientConnection(const char* host, unsigned int port,
HttpClientConnectionListener* listener,
TCPConnectionHandler* connectionHandler);
/**
* Sets listener.
*/
void setListener(HttpClientConnectionListener* listener);
/**
* Deletes the data associated with the connection.
* Closes connection.
*/
virtual ~HttpClientConnection();
/**
* Sends a get-request for the supplied filespec, if there
* is enough place in the queue.
* @param filespec1 File from server.
* @param filespec2 Will be concatenated to filespec1 if not NULL.
* @param urlParams [Optional] The url parameters
* (for instance containing the session).
* Should begin with a "?".
* @return A positive number is a request id and a negative number
* means that the queue is full.
*/
int get(const char* filespec1,
const char* filespec2 = NULL,
const char* filespec3 = NULL,
const char* urlParams = "");
/**
* Sends a post-request for the supplied filespec.
* @param urlParams [Optional] The url parameters
* (for instance containing the session).
* Should begin with a "?".
*/
int post(const char* filespecPart1,
const char* filespecPart2,
const char* mimeType,
const SharedBuffer& body,
const char* urlParams = "");
/**
* To be called when the connection is established or has
* failed.
*/
void connectDone(status_t status);
/**
* To be called when a read is done.
*
*/
void readDone(status_t status,
const byte* bytes,
int nbrBytes);
/**
* Informs the ClientConnection that the last write is completed.
*/
void writeDone(status_t status);
/**
* Informs the ClientConnection that the connection is closed.
*/
void connectionClosed(status_t status);
/**
* Informs the HttpClientConnection that the timeout
* with id timerID has expired.
*/
void timerExpired(int timerID);
/**
* Returns the number of requests to send.
*/
int getNbrSent() const { return m_waitingFor.size(); }
/**
* Writes a new request
*/
void oneRequestComplete();
/**
* Returns the number of the current request we are
* waiting for.
*/
int getCurrentRequestNbr() const;
/**
* Sets hostname and port.
*/
void setHostAndPort(const char* host, unsigned int port);
protected:
/**
* Tries to write a request to the socket.
*/
void writeNextRequest();
/**
* Tries to read a request from the socket.
*/
void readNextRequest();
private:
/**
* Hostname.
*/
MC2SimpleString m_host;
/**
* Number of the port to use for the connection.
*/
unsigned int m_port;
/**
* User agent string to send to the server.
*/
MC2SimpleString m_userAgent;
/**
* Prefix all the url:s with this string.
* To be used when using proxy.
*/
MC2SimpleString m_urlPrefix;
/**
* Maximum number of requests to have at a certain time.
*/
int m_maxNbrGet;
/**
* Type of list to keep the requests in.
*/
typedef std::list<std::pair<int, SharedBuffer*> > requestList_t;
/**
* The outgoing requests.
*/
requestList_t m_requestsToSend;
/**
* The requests we are waiting for.
*/
requestList_t m_waitingFor;
/**
* List containing zero or one requests that are currently
* written.
*/
requestList_t m_currentlyWriting;
/**
* Next id for the requests.
*/
int m_nextID;
/**
* The connection handler.
*/
TCPConnectionHandler* m_connHandler;
/**
* True if the connection is connecting.
*/
bool m_connecting;
/**
* True if there is a pending read.
*/
bool m_reading;
/**
* True if there is a pending write.
*/
bool m_writing;
/**
* The number of written requests for which
* we haven't got any answers yet.
*/
int m_nbrWaiting;
/**
* The number of failed attempts in a row.
*/
int m_nbrRetries;
/**
* Handles all reads from the connection.
*/
HttpClientConnectionReader* m_connReader;
/**
* The listener.
*/
HttpClientConnectionListener* m_listener;
/**
* The maximum number of retries.
*/
const int m_maxNbrRetries;
/**
* Header lines that should only be used when using proxy.
*/
const char* m_proxyHeaderLines;
};
class TCPConnectionHandler {
public:
/**
* Tells the underlying layer to connect to the
* supplied host and port. When connected, connected
* should be called.
* Should call ccon->connectDone when done.
* Max one connect per ClientConnection is allowed simultaneously.
*/
virtual void connect(const char* host, unsigned int port,
TCPClientConnection* ccon) = 0;
/**
* Tells the underlying layer to disconnect the
* current connection.
*/
virtual void disconnect(TCPClientConnection* ccon) = 0;
/**
* Tells the underlying layer to write the supplied
* bytes. The underlying layer must keep the order
* of the write requests.
* Should call ccon->writeDone when done.
* Max one write per ClientConnection is allowed.
* Not allowed if not connected.
*/
virtual void write(const byte* bytes, int length,
TCPClientConnection* ccon) = 0;
/**
* Tells the underlying layer to start receiving reads
* with up to maxLength bytes from the
* socket. Max <code>length</code> bytes.
* Should call the ccon->readDone when done.
* Max one read per ClientConnection is allowed.
* Not allowed if not connected.
*/
virtual void read(int maxLength,
TCPClientConnection* ccon) = 0;
/**
* Removes the connection from the internal list of
* connections in the TCPConnectionHandler.
*/
virtual void remove(TCPClientConnection* conn) = 0;
/**
* Requests a timeout for the connection conn.
* After the timeout, the connectionhandler should call
* timerExpired on the connection.
* @param nbrMillis The number of milliseconds to wait before
* sending the timeout.
* @param conn The connection that should have the timeout.
* @return ID of the timeout.
*/
virtual int requestTimer(uint32 nbrMillis,
TCPClientConnection* conn) = 0;
/**
* Cancels the timer with id timerID.
*/
virtual void cancelTimer(int timerID) = 0;
};
#endif
| {
"content_hash": "a6e79baa1374681a7eb3f306d082ccd3",
"timestamp": "",
"source": "github",
"line_count": 368,
"max_line_length": 71,
"avg_line_length": 25.641304347826086,
"alnum_prop": 0.571534548537516,
"repo_name": "wayfinder/Wayfinder-S60-Navigator",
"id": "5a052df0821ee4f53cafcd065345f0fceec8f573",
"size": "10977",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CPP/Targets/MapLib/Shared/include/HttpClientConnection.h",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "6115731"
},
{
"name": "C++",
"bytes": "9504249"
},
{
"name": "Perl",
"bytes": "3690"
}
],
"symlink_target": ""
} |
namespace dreal {
/// Transforms a symbolic formula @p f into a CNF formula by
/// preserving its semantics.
///
/// @note This transform can increase the size exponentially. We are
/// using this transformation in TseitinCnfizer when we process the
/// nested formula in a universally quantified formula.
class NaiveCnfizer {
public:
/// Convert @p f into its CNF form.
Formula Convert(const Formula& f) const;
private:
Formula Visit(const Formula& f) const;
Formula VisitFalse(const Formula& f) const;
Formula VisitTrue(const Formula& f) const;
Formula VisitVariable(const Formula& f) const;
Formula VisitEqualTo(const Formula& f) const;
Formula VisitNotEqualTo(const Formula& f) const;
Formula VisitGreaterThan(const Formula& f) const;
Formula VisitGreaterThanOrEqualTo(const Formula& f) const;
Formula VisitLessThan(const Formula& f) const;
Formula VisitLessThanOrEqualTo(const Formula& f) const;
Formula VisitConjunction(const Formula& f) const;
Formula VisitDisjunction(const Formula& f) const;
Formula VisitNegation(const Formula& f) const;
Formula VisitForall(const Formula& f) const;
const Nnfizer nnfizer_{};
// Makes VisitFormula a friend of this class so that it can use private
// operator()s.
friend Formula drake::symbolic::VisitFormula<Formula>(const NaiveCnfizer*,
const Formula&);
};
} // namespace dreal
| {
"content_hash": "353e1c6bae663ebfef20e17ae4ebb252",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 76,
"avg_line_length": 39.583333333333336,
"alnum_prop": 0.7270175438596491,
"repo_name": "soonho-tri/dreal4",
"id": "affad0ee36fc1e2b28808fdc8f07f9bba152ca67",
"size": "1509",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dreal/util/naive_cnfizer.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "250"
},
{
"name": "C++",
"bytes": "638067"
},
{
"name": "Dockerfile",
"bytes": "1139"
},
{
"name": "Jupyter Notebook",
"bytes": "1745"
},
{
"name": "LLVM",
"bytes": "16721"
},
{
"name": "Python",
"bytes": "71679"
},
{
"name": "SMT",
"bytes": "1233609"
},
{
"name": "Shell",
"bytes": "12043"
},
{
"name": "Starlark",
"bytes": "68448"
},
{
"name": "Yacc",
"bytes": "29216"
}
],
"symlink_target": ""
} |
/**
* @file 生成flash html
* @author jon_neal
* jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
* http://jquery.thewikies.com/swfobject
*/
define(function (require) {
var jQuery = require('jquery');
(function ($, flash, Plugin) {
var OBJECT = 'object';
var ENCODE = true;
function compareArrayIntegers(a, b) {
var x = (a[0] || 0) - (b[0] || 0);
return x > 0 || (
!x
&& a.length > 0
&& compareArrayIntegers(a.slice(1), b.slice(1))
);
}
function objectToArguments(obj) {
if (typeof obj !== OBJECT) {
return obj;
}
var arr = [];
var str = '';
for (var i in obj) {
if (typeof obj[i] === OBJECT) {
str = objectToArguments(obj[i]);
}
else {
str = [i, (ENCODE) ? encodeURI(obj[i]) : obj[i]].join('=');
}
arr.push(str);
}
return arr.join('&');
}
function objectFromObject(obj) {
var arr = [];
for (var i in obj) {
if (obj[i]) {
arr.push([i, '="', obj[i], '"'].join(''));
}
}
return arr.join(' ');
}
function paramsFromObject(obj) {
var arr = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
arr.push([
'<param name="', i,
'" value="', objectToArguments(obj[i]), '" />'
].join(''));
}
}
return arr.join('');
}
try {
var flashVersion = Plugin.description || (function () {
var newPlugin = new Plugin('ShockwaveFlash.ShockwaveFlash');
/*eslint-disable */
return newPlugin.GetVariable('$version');
/*eslint-enable */
}());
}
catch (e) {
flashVersion = 'Unavailable';
}
var flashVersionMatchVersionNumbers = flashVersion.match(/\d+/g) || [0];
$[flash] = {
available: flashVersionMatchVersionNumbers[0] > 0,
activeX: Plugin && !Plugin.name,
version: {
original: flashVersion,
array: flashVersionMatchVersionNumbers,
string: flashVersionMatchVersionNumbers.join('.'),
major: parseInt(flashVersionMatchVersionNumbers[0], 10) || 0,
minor: parseInt(flashVersionMatchVersionNumbers[1], 10) || 0,
release: parseInt(flashVersionMatchVersionNumbers[2], 10) || 0
},
hasVersion: function (version) {
var versionArray = (/string|number/.test(typeof version))
? version.toString().split('.')
: (/object/.test(typeof version))
? [version.major, version.minor]
: version || [0, 0];
return compareArrayIntegers(
flashVersionMatchVersionNumbers,
versionArray
);
},
encodeParams: true,
expressInstall: 'expressInstall.swf',
expressInstallIsActive: false,
create: function (obj) {
var instance = this;
if (
!obj.swf
|| instance.expressInstallIsActive
|| (!instance.available && !obj.hasVersionFail)
) {
return false;
}
if (!instance.hasVersion(obj.hasVersion || 1)) {
instance.expressInstallIsActive = true;
if (typeof obj.hasVersionFail === 'function') {
if (!obj.hasVersionFail.apply(obj)) {
return false;
}
}
obj = {
swf: obj.expressInstall || instance.expressInstall,
height: 137,
width: 214,
flashvars: {
MMredirectURL: location.href,
MMplayerType: (instance.activeX)
? 'ActiveX' : 'PlugIn',
MMdoctitle: document.title.slice(0, 47)
+ ' - Flash Player Installation'
}
};
}
var attrs = {
data: obj.swf,
type: 'application/x-shockwave-flash',
id: obj.id || 'flash_' + Math.floor(Math.random() * 999999999),
width: obj.width || 320,
height: obj.height || 180,
style: obj.style || ''
};
ENCODE = typeof obj.useEncode !== 'undefined' ? obj.useEncode : instance.encodeParams;
obj.movie = obj.swf;
obj.wmode = obj.wmode || 'opaque';
delete obj.fallback;
delete obj.hasVersion;
delete obj.hasVersionFail;
delete obj.height;
delete obj.id;
delete obj.swf;
delete obj.useEncode;
delete obj.width;
var flashContainer = document.createElement('div');
flashContainer.innerHTML = [
'<object ', objectFromObject(attrs), '>',
paramsFromObject(obj),
'</object>'
].join('');
return flashContainer.firstChild;
}
};
$.fn[flash] = function (options) {
var $this = this.find(OBJECT).andSelf().filter(OBJECT);
if (/string|object/.test(typeof options)) {
this.each(
function () {
var $this = $(this);
var flashObject;
options = (typeof options === OBJECT) ? options : {
swf: options
};
options.fallback = this;
flashObject = $[flash].create(options);
if (flashObject) {
$this.children().remove();
$this.html(flashObject);
}
}
);
}
if (typeof options === 'function') {
$this.each(
function () {
var instance = this;
var jsInteractionTimeoutMs = 'jsInteractionTimeoutMs';
instance[jsInteractionTimeoutMs]
= instance[jsInteractionTimeoutMs] || 0;
if (instance[jsInteractionTimeoutMs] < 660) {
if (instance.clientWidth || instance.clientHeight) {
options.call(instance);
}
else {
setTimeout(
function () {
$(instance)[flash](options);
},
instance[jsInteractionTimeoutMs] + 66
);
}
}
}
);
}
return $this;
};
}(
jQuery,
'flash',
navigator.plugins['Shockwave Flash'] || window.ActiveXObject
));
});
| {
"content_hash": "3df14157e402cacb1ae9d2315cd9d022",
"timestamp": "",
"source": "github",
"line_count": 248,
"max_line_length": 102,
"avg_line_length": 31.955645161290324,
"alnum_prop": 0.3950788643533123,
"repo_name": "nagyistoce/ecomfe-ub-ria-ui",
"id": "f4a0974cdbc71df4ed3b9e08617466d943e505e8",
"size": "7929",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/helper/swfHelper.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "401884"
},
{
"name": "HTML",
"bytes": "77739"
},
{
"name": "JavaScript",
"bytes": "482933"
}
],
"symlink_target": ""
} |
package org.elasticsearch.gradle.internal.test.rerun;
import org.elasticsearch.gradle.internal.test.rerun.executer.RerunTestExecuter;
import org.gradle.api.Action;
import org.gradle.api.Task;
import org.gradle.api.internal.tasks.testing.JvmTestExecutionSpec;
import org.gradle.api.internal.tasks.testing.TestExecuter;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.tasks.testing.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public final class TestTaskConfigurer {
private TestTaskConfigurer() {}
public static void configureTestTask(Test test, ObjectFactory objectFactory) {
TestRerunTaskExtension extension = test.getExtensions()
.create(TestRerunTaskExtension.NAME, TestRerunTaskExtension.class, objectFactory);
test.doFirst(new InitTaskAction(extension));
}
private static RerunTestExecuter createRetryTestExecuter(Task task, TestRerunTaskExtension extension) {
TestExecuter<JvmTestExecutionSpec> delegate = getTestExecuter(task);
return new RerunTestExecuter(extension, delegate);
}
private static TestExecuter<JvmTestExecutionSpec> getTestExecuter(Task task) {
return invoke(declaredMethod(Test.class, "createTestExecuter"), task);
}
private static void setTestExecuter(Task task, RerunTestExecuter rerunTestExecuter) {
invoke(declaredMethod(Test.class, "setTestExecuter", TestExecuter.class), task, rerunTestExecuter);
}
private static class InitTaskAction implements Action<Task> {
private final TestRerunTaskExtension extension;
InitTaskAction(TestRerunTaskExtension extension) {
this.extension = extension;
}
@Override
public void execute(Task task) {
RerunTestExecuter retryTestExecuter = createRetryTestExecuter(task, extension);
setTestExecuter(task, retryTestExecuter);
}
}
private static Method declaredMethod(Class<?> type, String methodName, Class<?>... paramTypes) {
try {
return makeAccessible(type.getDeclaredMethod(methodName, paramTypes));
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private static Method makeAccessible(Method method) {
method.setAccessible(true);
return method;
}
private static <T> T invoke(Method method, Object instance, Object... args) {
try {
Object result = method.invoke(instance, args);
@SuppressWarnings("unchecked")
T cast = (T) result;
return cast;
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
| {
"content_hash": "21558742b8e8568b13ed0d490aa17689",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 107,
"avg_line_length": 35.52564102564103,
"alnum_prop": 0.7080476362324071,
"repo_name": "robin13/elasticsearch",
"id": "9d116bbe0d8d8ff6aff1a337adf20e17a44a9a29",
"size": "3124",
"binary": false,
"copies": "35",
"ref": "refs/heads/master",
"path": "buildSrc/src/main/java/org/elasticsearch/gradle/internal/test/rerun/TestTaskConfigurer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11082"
},
{
"name": "Batchfile",
"bytes": "14049"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "315863"
},
{
"name": "HTML",
"bytes": "3399"
},
{
"name": "Java",
"bytes": "40107206"
},
{
"name": "Perl",
"bytes": "7271"
},
{
"name": "Python",
"bytes": "54437"
},
{
"name": "Shell",
"bytes": "108937"
}
],
"symlink_target": ""
} |
package org.o2i2b2.test;
import junit.framework.TestCase;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.EventFilter;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.o2i2b2.i2b2.schema.Concepts;
import org.o2i2b2.i2b2.schema.Meta;
import org.o2i2b2.i2b2.schema.O2I2B2;
import org.o2i2b2.i2b2.schema.Ontology;
import org.o2i2b2.i2b2.schema.Source;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* Created by IntelliJ IDEA.
* User: sam
* Date: May 7, 2006
* Time: 11:00:39 AM
* To change this template use File | Settings | File Templates.
*/
public class ParseTest extends TestCase {
private long memstart;
@Override
public void setUp() throws Exception {
super.setUp();
System.gc();
System.gc();
memstart = Runtime.getRuntime().freeMemory();
}
public void testParseEntireDocument() throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(new Class[]{O2I2B2.class});
Unmarshaller um = ctx.createUnmarshaller();
O2I2B2 o2i2b2 = (O2I2B2) um.unmarshal(new File("c:/Users/slorenz/Desktop/i2b2Export.xml"));
assertEquals("PIH-MWI", o2i2b2.getOrgCode());
System.gc();
System.gc();
long memend = Runtime.getRuntime().freeMemory();
System.out.println("Memory used: " + (memstart - memend));
}
public void testParseEfficiently() throws IOException, XMLStreamException, JAXBException {
// Parse the data, filtering out the start elements
XMLInputFactory xmlif = XMLInputFactory.newInstance();
FileReader fr = new FileReader("c:/Users/slorenz/Desktop/i2b2Export.xml");
XMLEventReader xmler = xmlif.createXMLEventReader(fr);
EventFilter filter = new EventFilter() {
public boolean accept(XMLEvent event) {
return event.isStartElement();
}
};
XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter);
// Jump to the first element in the document, the enclosing BugCollection
StartElement e = (StartElement) xmlfer.nextEvent();
assertEquals("o2i2b2", e.getName().getLocalPart());
// Parse into typed objects
JAXBContext ctx = JAXBContext.newInstance("org.o2i2b2.i2b2.schema");
Unmarshaller um = ctx.createUnmarshaller();
int bugs = 0;
// BugInstance bi = null;
while (xmlfer.peek() != null) {
Object o = um.unmarshal(xmler);
if (o instanceof Ontology) {
Ontology ontology = (Ontology) o;
// process the bug instance
System.out.println("ontology: " + ontology.toString());
for (Meta meta : ontology.getMeta()) {
System.out.println("Meta: " + meta.getName());
}
bugs++;
}
}
// assertEquals(180, bugs);
fr.close();
System.gc();
System.gc();
long memend = Runtime.getRuntime().freeMemory();
System.out.println("Memory used: " + (memstart - memend));
// assertNotNull(bi);
}
}
| {
"content_hash": "886b55b57b39a9c89dacfa40bae5b818",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 99,
"avg_line_length": 34.15841584158416,
"alnum_prop": 0.6336231884057971,
"repo_name": "stephenlorenz/o2i2b2",
"id": "04edc2fb0977abb328e2cbc165378164a993b838",
"size": "3450",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/o2i2b2/test/ParseTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "368078"
}
],
"symlink_target": ""
} |
export PGPASSWORD=$dbpasswd
if test -z $dbname
then
echo dbname cant be nill
exit -1
fi
pg_dump -h $dbhost -Fc -U $dbuser $dbname 2> /dev/null |gzip -c | {
"content_hash": "2665eb05957c996c09e8f038ef28fff1",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 66,
"avg_line_length": 23.857142857142858,
"alnum_prop": 0.6526946107784432,
"repo_name": "EnginesOS/System",
"id": "b05c0903091a5e8f09c8194b286651ef2e2fe195",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "system/templates/services/backup/EnginesSystem/database/sql/pgsql/backup.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "101320"
},
{
"name": "HTML",
"bytes": "4478768"
},
{
"name": "JavaScript",
"bytes": "72060"
},
{
"name": "Makefile",
"bytes": "40933"
},
{
"name": "Ruby",
"bytes": "844890"
},
{
"name": "Shell",
"bytes": "118832"
},
{
"name": "TSQL",
"bytes": "3205"
}
],
"symlink_target": ""
} |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
// index.php
$string['titlepage'] = 'NeuroK Activity';
$string['plugininfo'] = 'This module allows to connect to NeuroK App.';
$string['pluginadministration'] = 'NeuroK Settings';
// settings.php
$string['modulename'] = 'NeuroK';
$string['modulenameplural'] = 'NeuroK';
$string['neurokname'] = 'NeuroK';
$string['neurokname_help'] = 'NeuroK information';
$string['neurokapiurl'] = 'NeuroK API URL';
$string['neurokapiurlinfo'] = 'NeuroK API URL used to connect Moodle to NeuroK';
$string['neurokapikey'] = 'NeuroK API Key';
$string['neurokapikeyinfo'] = 'NeuroK API Key used to validate connection between Moodle and NeuroK';
$string['neurokenableconnection'] = 'Enable NeuroK Connection';
$string['neurokenableconnectioninfo'] = 'It allows to enable NeuroK connection in Moodle installation';
// access.php
$string['neurok:view'] = 'View NeuroK Course URL';
$string['neurok:addinstance'] = 'Add NeuroK Course information';
// mod_form.php
$string['neurokcoursetitle'] = 'NeuroK course title';
$string['neurokcoursetitle_help'] = 'NeuroK course title';
$string['neurokcourselink'] = 'NeuroK course URL';
$string['neurokcourselink_help'] = 'URL to access NeuroK course';
$string['invalidurl'] = 'Entered URL is not a valid NeuroK course URL';
| {
"content_hash": "2b2f09d5247cc89fc39a44650a4b063d",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 103,
"avg_line_length": 46.04761904761905,
"alnum_prop": 0.733195449844881,
"repo_name": "aspgems/neuromoodle",
"id": "de6d50bbe9214dcee8e2214a2268c57ce0187881",
"size": "2126",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lang/en/neurok.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "43996"
}
],
"symlink_target": ""
} |
'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var Config = require('../lib/config');
var Jwt = require('../lib/jwt');
var tools = require('../lib/tools');
var USERS_CONFIG = tools.USERS_CONFIG;
module.exports = function (router) {
router.post('/auth/login', function* (next) {
var self = this;
var config = new Config();
var secret = yield config.get('secret');
var usersConfig = new Config(USERS_CONFIG);
var userName = self.request.body.username;
var permanent = !!self.request.body.permanent;
var user = yield usersConfig.get(userName);
var jwt = new Jwt({
secret: secret
});
var password = self.request.body.password || '';
var passwordHash = jwt.createHash(password);
if (!userName || !user || !password ||
user.passwordHash !== passwordHash) {
self.status = 401;
return;
}
self.body = {
token: jwt.format(_.extend(user, {
name: userName,
permanent: permanent
}))
};
self.status = 200;
});
router.post('/auth/refresh', function* (next) {
var self = this;
var config = new Config();
var secret = yield config.get('secret');
var jwt = new Jwt({
secret: secret
});
var payload = jwt.parse(self.request.body.token, { ignoreExpiry: true });
var permanent = !!payload.permanent;
if (!permanent) {
jwt.checkExpired(payload);
}
var usersConfig = new Config(USERS_CONFIG);
var userName = payload.name;
var user = yield usersConfig.get(userName);
if (!user || !payload ||
user.passwordHash !== payload.passwordHash) {
self.status = 401;
return;
}
self.body = {
token: jwt.format(_.extend(user, {
name: userName,
permanent: permanent
}))
};
self.status = 200;
});
router.post('/create/user', function* (next) {
var self = this;
var info = yield tools.getUser(this, { fullInfo: true, strongToken: true });
var user = info.user;
var jwt = info.jwt;
if (!user.admin) {
self.body = tools.prepareText('Access denied', { red: true, newLine: true });
self.status = 401;
return;
}
var username = self.request.body.username;
var password = self.request.body.password;
var admin = _.isBoolean(self.request.body.admin) ? self.request.body.admin : (
self.request.body.admin === 'true' ? true : false
);
var partitions = _.isString(self.request.body.partitions) ? _.compact(self.request.body.partitions.split(/[\s,;]+/ig)) : [];
if (!username || !password) {
self.body = tools.prepareText('Please, provide username and password', { red: true, newLine: true });
self.status = 400;
return;
}
var passwordHash = jwt.createHash(password);
var usersConfig = new Config(USERS_CONFIG);
var existingUser = yield usersConfig.get(username);
if (existingUser) {
self.body = tools.prepareText('User ' + username + ' already exists', { red: true, newLine: true });
self.status = 400;
return;
}
yield usersConfig.set(username, _.extend(existingUser, {
passwordHash: passwordHash,
admin: admin,
partitions: partitions
}));
self.body = tools.prepareText('User created: ' + username, { green: true, newLine: true });
self.status = 200;
});
router.post('/edit/user', function* (next) {
var self = this;
var info = yield tools.getUser(this, { fullInfo: true, strongToken: true });
var user = info.user;
var jwt = info.jwt;
var username = self.request.body.username;
var password = self.request.body.password;
var admin = _.isUndefined(self.request.body.admin) ? undefined : (
_.isBoolean(self.request.body.admin) ? self.request.body.admin : (
self.request.body.admin === 'true' ? true : false
)
);
var partitions = _.isUndefined(self.request.body.partitions) ? undefined : (
_.isString(self.request.body.partitions) ? _.compact(self.request.body.partitions.split(/[\s,;]+/ig)) : []
);
if (!username) {
self.body = tools.prepareText('Please, provide username', { red: true, newLine: true });
self.status = 400;
return;
}
if (!user.admin &&
(username !== user.name || !_.isUndefined(admin) || !_.isUndefined(partitions))) {
self.body = tools.prepareText('Access denied', { red: true, newLine: true });
self.status = 401;
return;
}
var passwordHash = password ? jwt.createHash(password) : undefined;
var usersConfig = new Config(USERS_CONFIG);
var existingUser = yield usersConfig.get(username);
if (!existingUser) {
self.body = tools.prepareText('User ' + username + ' does not exist', { red: true, newLine: true });
self.status = 400;
return;
}
yield usersConfig.set(username, _.defaults({
passwordHash: passwordHash,
admin: admin,
partitions: partitions
}, existingUser));
self.body = tools.prepareText('User updated: ' + username, { green: true, newLine: true });
self.status = 200;
});
router.post('/remove/user', function* (next) {
var self = this;
var info = yield tools.getUser(this, { fullInfo: true, strongToken: true });
var user = info.user;
var jwt = info.jwt;
if (!user.admin) {
self.body = tools.prepareText('Access denied', { red: true, newLine: true });
self.status = 401;
return;
}
var username = self.request.body.username;
if (!username) {
self.body = tools.prepareText('Please, provide username', { red: true, newLine: true });
self.status = 400;
return;
}
var usersConfig = new Config(USERS_CONFIG);
var existingUser = yield usersConfig.get(username);
if (!existingUser) {
self.body = tools.prepareText('User ' + username + ' does not exist', { red: true, newLine: true });
self.status = 400;
return;
}
yield usersConfig.set(username, null);
self.body = tools.prepareText('User removed: ' + username, { green: true, newLine: true });
self.status = 200;
});
router.post('/list/users', function* (next) {
var self = this;
var info = yield tools.getUser(this, { fullInfo: true, strongToken: true });
var user = info.user;
var jwt = info.jwt;
if (!user.admin) {
self.body = tools.prepareText('Access denied', { red: true, newLine: true });
self.status = 401;
return;
}
self.status = 200;
var usersConfig = new Config(USERS_CONFIG);
var users = yield usersConfig.list();
var result = {
data: _.map(users, function (user, username) {
return {
'UserName': username,
'Role': user.admin ? 'admin' : '',
'Partitions': user.partitions ? user.partitions.join(',') : ''
}
})
};
if (!tools.acceptsJson(self)) {
result = tools.formatTable(result.data, {
title: 'Listing All Users',
total: (result.data.length || 0) + ' users listed.'
})
}
self.body = result;
});
};
| {
"content_hash": "3b821560a478364501dcbf2554127147",
"timestamp": "",
"source": "github",
"line_count": 261,
"max_line_length": 132,
"avg_line_length": 30.911877394636015,
"alnum_prop": 0.5321021318790282,
"repo_name": "tredly/tredly-api",
"id": "67b460831058da07be4edf1b5976d34d1e0016d1",
"size": "8068",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/auth.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "48716"
},
{
"name": "Shell",
"bytes": "4178"
}
],
"symlink_target": ""
} |
@implementation UIView (UpdateAutoLayoutConstraints)
- (BOOL) setConstraintConstant:(CGFloat)constant forAttribute:(NSLayoutAttribute)attribute {
NSLayoutConstraint * constraint = [self constraintForAttribute:attribute];
if(constraint) {
[constraint setConstant:constant];
return YES;
} else {
[self.superview addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:attribute relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:constant]];
return NO;
}
}
- (CGFloat) constraintConstantforAttribute:(NSLayoutAttribute)attribute {
NSLayoutConstraint * constraint = [self constraintForAttribute:attribute];
if (constraint) {
return constraint.constant;
} else {
return NAN;
}
}
- (NSLayoutConstraint*) constraintForAttribute:(NSLayoutAttribute)attribute {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstAttribute = %d && firstItem = %@", attribute, self];
NSArray *fillteredArray = [[self.superview constraints] filteredArrayUsingPredicate:predicate];
if(fillteredArray.count == 0) {
return nil;
}else {
return fillteredArray.firstObject;
}
}
- (void)hideByHeight:(BOOL)hidden {
[self hideView:hidden byAttribute:NSLayoutAttributeHeight];
}
- (void)hideByWidth:(BOOL)hidden {
[self hideView:hidden byAttribute:NSLayoutAttributeWidth];
}
- (void)hideView:(BOOL)hidden byAttribute:(NSLayoutAttribute)attribute {
if (self.hidden != hidden) {
CGFloat constraintConstant = [self constraintConstantforAttribute:attribute];
if (hidden) {
if (!isnan(constraintConstant)) {
self.alpha = constraintConstant;
} else {
CGSize size = [self getSize];
self.alpha = (attribute == NSLayoutAttributeHeight)?size.height:size.width;
}
[self setConstraintConstant:0 forAttribute:attribute];
self.hidden = YES;
} else {
if (!isnan(constraintConstant) ) {
self.hidden = NO;
[self setConstraintConstant:self.alpha forAttribute:attribute];
self.alpha = 1;
}
}
}
}
- (CGSize) getSize {
[self updateSizes];
return CGSizeMake(self.bounds.size.width, self.bounds.size.height);
}
- (void)updateSizes {
[self setNeedsLayout];
[self layoutIfNeeded];
}
- (void)sizeToSubviews {
[self updateSizes];
CGSize fittingSize = [self systemLayoutSizeFittingSize: UILayoutFittingCompressedSize];
self.frame = CGRectMake(0, 0, 320, fittingSize.height);
}
@end | {
"content_hash": "0849d747aa74452e85c233de4928cdc4",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 223,
"avg_line_length": 31.011494252873565,
"alnum_prop": 0.6727205337286879,
"repo_name": "shsun/VideoAdView",
"id": "07dc8853767e92cb366dadc3eb50617fd9cb0113",
"size": "2841",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GUIPlayerView/Classes/UIView+UpdateAutoLayoutConstraints.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "25660"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2010 The Android Open Source Project
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.
-->
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/com_facebook_picker_list_pressed" />
<item android:drawable="@drawable/com_facebook_picker_list_longpressed" />
</transition>
<!-- From: file:/C:/Users/Pakkapon/Documents/GitHub/MuMu-android/facebook/res/drawable/com_facebook_picker_list_selector_background_transition.xml --><!-- From: file:/C:/Users/Pakkapon/Documents/GitHub/MuMu-android/facebook/build/intermediates/bundles/debug/res/drawable/com_facebook_picker_list_selector_background_transition.xml --> | {
"content_hash": "a8b75fa4c1d58067f622d4fff49507b6",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 334,
"avg_line_length": 59.38095238095238,
"alnum_prop": 0.7449879711307137,
"repo_name": "pureexe/mumu-android-0.0.1",
"id": "bff9727769e8b94d42588e5606c04d2783c0ec76",
"size": "1247",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "facebook/build/intermediates/res/test/debug/drawable/com_facebook_picker_list_selector_background_transition.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1590764"
}
],
"symlink_target": ""
} |
package com.satan.imageselectorandcrop;
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
public class ClipPictureActivity extends Activity implements OnTouchListener,
OnClickListener {
ImageView srcPic;
Button sure;
ClipView clipview;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
private static final String TAG = "11";
int mode = NONE;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
private String path;
private Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
path = getIntent().getStringExtra("path");
srcPic = (ImageView) this.findViewById(R.id.src_pic);
srcPic.setImageBitmap(BitmapFactory.decodeFile(path));
srcPic.setOnTouchListener(this);
srcPic.setScaleType(ImageView.ScaleType.MATRIX);
sure = (Button) this.findViewById(R.id.sure);
sure.setOnClickListener(this);
}
/*这里实现了多点触摸放大缩小,和单点移动图片的功能,参考了论坛的代码*/
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
// Handle touch events here...
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
// 設置初始點位置
start.set(event.getX(), event.getY());
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY()
- start.y);
} else if (mode == ZOOM) {
float newDist = spacing(event);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
}
view.setImageMatrix(matrix);
return true;
}
/**
* Determine the space between the first two fingers
*/
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
/**
* Calculate the mid point of the first two fingers
*/
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
public void onClick(View v) {
Bitmap fianBitmap = getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
fianBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bitmapByte = baos.toByteArray();
Intent intent = new Intent();
intent.putExtra("bitmap", bitmapByte);
setResult(Activity.RESULT_OK, intent);
finish();
}
/*获取矩形区域内的截图*/
private Bitmap getBitmap() {
getBarHeight();
Bitmap screenShoot = takeScreenShot();
clipview = (ClipView) this.findViewById(R.id.clipview);
int width = clipview.getWidth();
int height = clipview.getHeight();
Bitmap finalBitmap = Bitmap.createBitmap(screenShoot,
(width - height / 3) / 2, height / 3 + titleBarHeight + statusBarHeight, height / 3, height / 3);
return finalBitmap;
}
int statusBarHeight = 0;
int titleBarHeight = 0;
private void getBarHeight() {
// 获取状态栏高度
Rect frame = new Rect();
this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
statusBarHeight = frame.top;
int contenttop = this.getWindow()
.findViewById(Window.ID_ANDROID_CONTENT).getTop();
// statusBarHeight是上面所求的状态栏的高度
titleBarHeight = contenttop - statusBarHeight;
Log.v(TAG, "statusBarHeight = " + statusBarHeight
+ ", titleBarHeight = " + titleBarHeight);
}
// 获取Activity的截屏
private Bitmap takeScreenShot() {
View view = this.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
return view.getDrawingCache();
}
} | {
"content_hash": "d9045e0c0a4713d63f6c2f3cfda16458",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 113,
"avg_line_length": 31.4438202247191,
"alnum_prop": 0.5965695908522423,
"repo_name": "wenjue/ImageSelectorAndCrop",
"id": "a23fb2cb3ea0212af07be6169d8e9586a1754815",
"size": "5745",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/satan/imageselectorandcrop/ClipPictureActivity.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "23640"
}
],
"symlink_target": ""
} |
//=============================================================================
// AltMenuScreen.js
//=============================================================================
/*:
* @plugindesc Alternative menu screen layout.
* @author Yoji Ojima
*
* @help This plugin does not provide plugin commands.
*/
/*:ja
* @plugindesc メニュー画面のレイアウトを変更します。
* @author Yoji Ojima
*
* @help このプラグインには、プラグインコマンドはありません。
*/
(function() {
var _Scene_Menu_create = Scene_Menu.prototype.create;
Scene_Menu.prototype.create = function() {
_Scene_Menu_create.call(this);
this._statusWindow.x = 0;
this._statusWindow.y = this._commandWindow.height;
this._goldWindow.x = Graphics.boxWidth - this._goldWindow.width;
};
Window_MenuCommand.prototype.windowWidth = function() {
return Graphics.boxWidth;
};
Window_MenuCommand.prototype.maxCols = function() {
return 4;
};
Window_MenuCommand.prototype.numVisibleRows = function() {
return 2;
};
Window_MenuStatus.prototype.windowWidth = function() {
return Graphics.boxWidth;
};
Window_MenuStatus.prototype.windowHeight = function() {
var h1 = this.fittingHeight(1);
var h2 = this.fittingHeight(2);
return Graphics.boxHeight - h1 - h2;
};
Window_MenuStatus.prototype.maxCols = function() {
return 4;
};
Window_MenuStatus.prototype.numVisibleRows = function() {
return 1;
};
Window_MenuStatus.prototype.drawItemImage = function(index) {
var actor = $gameParty.members()[index];
var rect = this.itemRectForText(index);
var w = Math.min(rect.width, 144);
var h = Math.min(rect.height, 144);
var lineHeight = this.lineHeight();
this.changePaintOpacity(actor.isBattleMember());
this.drawActorFace(actor, rect.x, rect.y + lineHeight * 2.5, w, h);
this.changePaintOpacity(true);
};
Window_MenuStatus.prototype.drawItemStatus = function(index) {
var actor = $gameParty.members()[index];
var rect = this.itemRectForText(index);
var x = rect.x;
var y = rect.y;
var width = rect.width;
var bottom = y + rect.height;
var lineHeight = this.lineHeight();
this.drawActorName(actor, x, y + lineHeight * 0, width);
this.drawActorLevel(actor, x, y + lineHeight * 1, width);
this.drawActorClass(actor, x, bottom - lineHeight * 4, width);
this.drawActorHp(actor, x, bottom - lineHeight * 3, width);
this.drawActorMp(actor, x, bottom - lineHeight * 2, width);
this.drawActorIcons(actor, x, bottom - lineHeight * 1, width);
};
var _Window_MenuActor_initialize = Window_MenuActor.prototype.initialize;
Window_MenuActor.prototype.initialize = function() {
_Window_MenuActor_initialize.call(this);
this.y = this.fittingHeight(2);
};
})();
| {
"content_hash": "1975ee0198bb7e87f51651bc4d649b86",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 79,
"avg_line_length": 33.04347826086956,
"alnum_prop": 0.5792763157894737,
"repo_name": "lriki/TkoolMV",
"id": "f29247030faa39f1f438bdf2963093d694035072",
"size": "3130",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GS-Map/js/plugins/AltMenuScreen.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "80"
},
{
"name": "HTML",
"bytes": "2925"
},
{
"name": "JavaScript",
"bytes": "5206611"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" />
<title>Menu Design Guidelines | Android Developers</title>
<!-- STYLESHEETS -->
<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../assets/css/default.css" rel="stylesheet" type="text/css">
<!-- JAVASCRIPT -->
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="../../../assets/js/android_3p-bundle.js" type="text/javascript"></script>
<script type="text/javascript">
var toRoot = "../../../";
var devsite = false;
</script>
<script src="../../../assets/js/docs.js" type="text/javascript"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-5831155-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body class="gc-documentation
develop guide" itemscope itemtype="http://schema.org/Article">
<a name="top"></a>
<!-- Header -->
<div id="header">
<div class="wrap" id="header-wrap">
<div class="col-3 logo">
<a href="../../../index.html">
<img src="../../../assets/images/dac_logo.png" width="123" height="25" alt="Android Developers" />
</a>
<div class="btn-quicknav" id="btn-quicknav">
<a href="#" class="arrow-inactive">Quicknav</a>
<a href="#" class="arrow-active">Quicknav</a>
</div>
</div>
<ul class="nav-x col-9">
<li class="design">
<a href="../../../design/index.html"
zh-tw-lang="設計"
zh-cn-lang="设计"
ru-lang="Проектирование"
ko-lang="디자인"
ja-lang="設計"
es-lang="Diseñar"
>Design</a></li>
<li class="develop"><a href="../../../develop/index.html"
zh-tw-lang="開發"
zh-cn-lang="开发"
ru-lang="Разработка"
ko-lang="개발"
ja-lang="開発"
es-lang="Desarrollar"
>Develop</a></li>
<li class="distribute last"><a href="../../../distribute/index.html"
zh-tw-lang="發佈"
zh-cn-lang="分发"
ru-lang="Распространение"
ko-lang="배포"
ja-lang="配布"
es-lang="Distribuir"
>Distribute</a></li>
</ul>
<!-- New Search -->
<div class="menu-container">
<div class="moremenu">
<div id="more-btn"></div>
</div>
<div class="morehover" id="moremenu">
<div class="top"></div>
<div class="mid">
<div class="header">Links</div>
<ul>
<li><a href="https://play.google.com/apps/publish/">Google Play Developer Console</a></li>
<li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
<li><a href="../../../about/index.html">About Android</a></li>
</ul>
<div class="header">Android Sites</div>
<ul>
<li><a href="http://www.android.com">Android.com</a></li>
<li class="active"><a>Android Developers</a></li>
<li><a href="http://source.android.com">Android Open Source Project</a></li>
</ul>
<br class="clearfix" />
</div>
<div class="bottom"></div>
</div>
<div class="search" id="search-container">
<div class="search-inner">
<div id="search-btn"></div>
<div class="left"></div>
<form onsubmit="return submit_search()">
<input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../')"
onkeyup="return search_changed(event, false, '../../../')" />
</form>
<div class="right"></div>
<a class="close hide">close</a>
<div class="left"></div>
<div class="right"></div>
</div>
</div>
<div class="search_filtered_wrapper reference">
<div class="suggest-card reference no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
<div class="search_filtered_wrapper docs">
<div class="suggest-card dummy no-display"> </div>
<div class="suggest-card develop no-display">
<ul class="search_filtered">
</ul>
<div class="child-card guides no-display">
</div>
<div class="child-card training no-display">
</div>
</div>
<div class="suggest-card design no-display">
<ul class="search_filtered">
</ul>
</div>
<div class="suggest-card distribute no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
</div>
<!-- /New Search>
<!-- Expanded quicknav -->
<div id="quicknav" class="col-9">
<ul>
<li class="design">
<ul>
<li><a href="../../../design/index.html">Get Started</a></li>
<li><a href="../../../design/style/index.html">Style</a></li>
<li><a href="../../../design/patterns/index.html">Patterns</a></li>
<li><a href="../../../design/building-blocks/index.html">Building Blocks</a></li>
<li><a href="../../../design/downloads/index.html">Downloads</a></li>
<li><a href="../../../design/videos/index.html">Videos</a></li>
</ul>
</li>
<li class="develop">
<ul>
<li><a href="../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../guide/components/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../tools/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a>
<ul><li><a href="../../../sdk/index.html">Get the SDK</a></li></ul>
</li>
<li><a href="../../../google/index.html">Google Services</a>
</li>
</ul>
</li>
<li class="distribute last">
<ul>
<li><a href="../../../distribute/index.html">Google Play</a></li>
<li><a href="../../../distribute/googleplay/publish/index.html">Publishing</a></li>
<li><a href="../../../distribute/googleplay/promote/index.html">Promoting</a></li>
<li><a href="../../../distribute/googleplay/quality/index.html">App Quality</a></li>
<li><a href="../../../distribute/googleplay/spotlight/index.html">Spotlight</a></li>
<li><a href="../../../distribute/open.html">Open Distribution</a></li>
</ul>
</li>
</ul>
</div>
<!-- /Expanded quicknav -->
</div>
</div>
<!-- /Header -->
<div id="searchResults" class="wrap" style="display:none;">
<h2 id="searchTitle">Results</h2>
<div id="leftSearchControl" class="search-control">Loading...</div>
</div>
<!-- Secondary x-nav -->
<div id="nav-x">
<div class="wrap">
<ul class="nav-x col-9 develop" style="width:100%">
<li class="training"><a href="../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li class="guide"><a href="../../../guide/components/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li class="reference"><a href="../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li class="tools"><a href="../../../tools/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a></li>
<li class="google"><a href="../../../google/index.html"
>Google Services</a>
</li>
</ul>
</div>
</div>
<!-- /Sendondary x-nav -->
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<ul id="nav">
<!-- Walkthrough for Developers -- quick overview of what it's like to develop on Android -->
<!--<li style="color:red">Overview</li> -->
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/components/index.html">
<span class="en">App Components</span>
</a></div>
<ul>
<li><a href="../../../guide/components/fundamentals.html">
<span class="en">App Fundamentals</span></a>
</li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/components/activities.html">
<span class="en">Activities</span>
</a></div>
<ul>
<li><a href="../../../guide/components/fragments.html">
<span class="en">Fragments</span>
</a></li>
<li><a href="../../../guide/components/loaders.html">
<span class="en">Loaders</span>
</a></li>
<li><a href="../../../guide/components/tasks-and-back-stack.html">
<span class="en">Tasks and Back Stack</span>
</a></li>
</ul>
</li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/components/services.html">
<span class="en">Services</span>
</a></div>
<ul>
<li><a href="../../../guide/components/bound-services.html">
<span class="en">Bound Services</span>
</a></li>
<li><a href="../../../guide/components/aidl.html">
<span class="en">AIDL</span>
</a></li>
</ul>
</li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/providers/content-providers.html">
<span class="en">Content Providers</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/providers/content-provider-basics.html">
<span class="en">Content Provider Basics</span>
</a></li>
<li><a href="../../../guide/topics/providers/content-provider-creating.html">
<span class="en">Creating a Content Provider</span>
</a></li>
<li><a href="../../../guide/topics/providers/calendar-provider.html">
<span class="en">Calendar Provider</span>
</a></li>
<li><a href="../../../guide/topics/providers/contacts-provider.html">
<span class="en">Contacts Provider</span>
</a></li>
<li><a href="../../../guide/topics/providers/document-provider.html">
<span class="en">Storage Access Framework</span>
</a></li>
</ul>
</li>
<li><a href="../../../guide/components/intents-filters.html">
<span class="en">Intents and Intent Filters</span>
</a></li>
<li><a href="../../../guide/components/processes-and-threads.html">
<span class="en">Processes and Threads</span>
</a>
</li>
<li><a href="../../../guide/topics/security/permissions.html">
<span class="en">Permissions</span>
</a>
</li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/appwidgets/index.html">
<span class="en">App Widgets</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/appwidgets/host.html">
<span class="en">App Widget Host</span>
</a></li>
</ul>
</li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/manifest/manifest-intro.html">
<span class="en">Android Manifest</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/manifest/action-element.html"><action></a></li>
<li><a href="../../../guide/topics/manifest/activity-element.html"><activity></a></li>
<li><a href="../../../guide/topics/manifest/activity-alias-element.html"><activity-alias></a></li>
<li><a href="../../../guide/topics/manifest/application-element.html"><application></a></li>
<li><a href="../../../guide/topics/manifest/category-element.html"><category></a></li>
<li><a href="../../../guide/topics/manifest/compatible-screens-element.html"><compatible-screens></a></li>
<li><a href="../../../guide/topics/manifest/data-element.html"><data></a></li>
<li><a href="../../../guide/topics/manifest/grant-uri-permission-element.html"><grant-uri-permission></a></li>
<li><a href="../../../guide/topics/manifest/instrumentation-element.html"><instrumentation></a></li>
<li><a href="../../../guide/topics/manifest/intent-filter-element.html"><intent-filter></a></li>
<li><a href="../../../guide/topics/manifest/manifest-element.html"><manifest></a></li>
<li><a href="../../../guide/topics/manifest/meta-data-element.html"><meta-data></a></li>
<li><a href="../../../guide/topics/manifest/path-permission-element.html"><path-permission></a></li>
<li><a href="../../../guide/topics/manifest/permission-element.html"><permission></a></li>
<li><a href="../../../guide/topics/manifest/permission-group-element.html"><permission-group></a></li>
<li><a href="../../../guide/topics/manifest/permission-tree-element.html"><permission-tree></a></li>
<li><a href="../../../guide/topics/manifest/provider-element.html"><provider></a></li>
<li><a href="../../../guide/topics/manifest/receiver-element.html"><receiver></a></li>
<li><a href="../../../guide/topics/manifest/service-element.html"><service></a></li>
<li><a href="../../../guide/topics/manifest/supports-gl-texture-element.html"><supports-gl-texture></a></li>
<li><a href="../../../guide/topics/manifest/supports-screens-element.html"><supports-screens></a></li><!-- ##api level 4## -->
<li><a href="../../../guide/topics/manifest/uses-configuration-element.html"><uses-configuration></a></li>
<li><a href="../../../guide/topics/manifest/uses-feature-element.html"><uses-feature></a></li> <!-- ##api level 4## -->
<li><a href="../../../guide/topics/manifest/uses-library-element.html"><uses-library></a></li>
<li><a href="../../../guide/topics/manifest/uses-permission-element.html"><uses-permission></a></li>
<li><a href="../../../guide/topics/manifest/uses-sdk-element.html"><uses-sdk></a></li>
</ul>
</li><!-- end of the manifest file -->
</ul>
</li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/ui/index.html">
<span class="en">User Interface</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/ui/overview.html">
<span class="en">Overview</span>
</a></li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/ui/declaring-layout.html">
<span class="en">Layouts</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/ui/layout/linear.html">
<span class="en">Linear Layout</span>
</a></li>
<li><a href="../../../guide/topics/ui/layout/relative.html">
<span class="en">Relative Layout</span>
</a></li>
<!--
<li><a href="../../../guide/topics/ui/layout/grid.html">
<span class="en">Grid Layout</span>
</a></li>
-->
<li><a href="../../../guide/topics/ui/layout/listview.html">
<span class="en">List View</span>
</a></li>
<li><a href="../../../guide/topics/ui/layout/gridview.html">
<span class="en">Grid View</span>
</a></li>
</ul>
</li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/ui/controls.html">
<span class="en">Input Controls</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/ui/controls/button.html">
<span class="en">Buttons</span>
</a></li>
<li><a href="../../../guide/topics/ui/controls/text.html">
<span class="en">Text Fields</span>
</a></li>
<li><a href="../../../guide/topics/ui/controls/checkbox.html">
<span class="en">Checkboxes</span>
</a></li>
<li><a href="../../../guide/topics/ui/controls/radiobutton.html">
<span class="en">Radio Buttons</span>
</a></li>
<li><a href="../../../guide/topics/ui/controls/togglebutton.html">
<span class="en">Toggle Buttons</span>
</a></li>
<li><a href="../../../guide/topics/ui/controls/spinner.html">
<span class="en">Spinners</span>
</a></li>
<li><a href="../../../guide/topics/ui/controls/pickers.html">
<span class="en">Pickers</span>
</a></li>
<!--
<li><a href="../../../guide/topics/ui/controls/progress.html">
<span class="en">Seek and Progress Bars</span>
</a></li>
-->
</ul>
</li>
<li><a href="../../../guide/topics/ui/ui-events.html">
<span class="en">Input Events</span>
</a></li>
<li><a href="../../../guide/topics/ui/menus.html">
<span class="en">Menus</span></span>
</a></li>
<li><a href="../../../guide/topics/ui/actionbar.html">
<span class="en">Action Bar</span>
</a></li>
<li><a href="../../../guide/topics/ui/settings.html">
<span class="en">Settings</span>
</a></li>
<li><a href="../../../guide/topics/ui/dialogs.html">
<span class="en">Dialogs</span>
</a></li>
<li><a href="../../../guide/topics/ui/notifiers/notifications.html">
<span class="en">Notifications</span>
</a></li>
<li><a href="../../../guide/topics/ui/notifiers/toasts.html">
<span class="en">Toasts</span>
</a></li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/search/index.html">
<span class="en">Search</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/search/search-dialog.html">Creating a Search Interface</a></li>
<li><a href="../../../guide/topics/search/adding-recent-query-suggestions.html">Adding Recent Query Suggestions</a></li>
<li><a href="../../../guide/topics/search/adding-custom-suggestions.html">Adding Custom Suggestions</a></li>
<li><a href="../../../guide/topics/search/searchable-config.html">Searchable Configuration</a></li>
</ul>
</li>
<li><a href="../../../guide/topics/ui/drag-drop.html">
<span class="en">Drag and Drop</span>
</a></li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/ui/accessibility/index.html">
<span class="en">Accessibility</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/ui/accessibility/apps.html">
<span class="en">Making Applications Accessible</span>
</a></li>
<li><a href="../../../guide/topics/ui/accessibility/checklist.html">
<span class="en">Accessibility Developer Checklist</span>
</a></li>
<li><a href="../../../guide/topics/ui/accessibility/services.html">
<span class="en">Building Accessibility Services</span>
</a></li>
</ul>
</li>
<li><a href="../../../guide/topics/ui/themes.html">
<span class="en">Styles and Themes</span>
</a></li>
<li><a href="../../../guide/topics/ui/custom-components.html">
<span class="en">Custom Components</span>
</a></li>
</ul>
</li><!-- end of User Interface -->
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/resources/index.html">
<span class="en">App Resources</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/resources/overview.html">
<span class="en">Overview</span>
</a></li>
<li><a href="../../../guide/topics/resources/providing-resources.html">
<span class="en">Providing Resources</span>
</a></li>
<li><a href="../../../guide/topics/resources/accessing-resources.html">
<span class="en">Accessing Resources</span>
</a></li>
<li><a href="../../../guide/topics/resources/runtime-changes.html">
<span class="en">Handling Runtime Changes</span>
</a></li>
<li><a href="../../../guide/topics/resources/localization.html">
<span class="en">Localization</span>
</a></li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/resources/available-resources.html">
<span class="en">Resource Types</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/resources/animation-resource.html">Animation</a></li>
<li><a href="../../../guide/topics/resources/color-list-resource.html">Color State List</a></li>
<li><a href="../../../guide/topics/resources/drawable-resource.html">Drawable</a></li>
<li><a href="../../../guide/topics/resources/layout-resource.html">Layout</a></li>
<li><a href="../../../guide/topics/resources/menu-resource.html">Menu</a></li>
<li><a href="../../../guide/topics/resources/string-resource.html">String</a></li>
<li><a href="../../../guide/topics/resources/style-resource.html">Style</a></li>
<li><a href="../../../guide/topics/resources/more-resources.html">More Types</a></li>
</ul>
</li><!-- end of resource types -->
</ul>
</li><!-- end of app resources -->
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/graphics/index.html">
<span class="en">Animation and Graphics</span>
</a></div>
<ul>
<li class="nav-section">
<li><a href="../../../guide/topics/graphics/overview.html">
<span class="en">Overview</span>
</a></li>
<li><a href="../../../guide/topics/graphics/prop-animation.html">
<span class="en">Property Animation</span>
</a></li>
<li><a href="../../../guide/topics/graphics/view-animation.html">
<span class="en">View Animation</span>
</a></li>
<li><a href="../../../guide/topics/graphics/drawable-animation.html">
<span class="en">Drawable Animation</span>
</a></li>
<li><a href="../../../guide/topics/graphics/2d-graphics.html">
<span class="en">Canvas and Drawables</span>
</a></li>
<li><a href="../../../guide/topics/graphics/opengl.html">
<span class="en">OpenGL ES</span>
</a></li>
<li><a href="../../../guide/topics/graphics/hardware-accel.html">
<span class="en">Hardware Acceleration</span>
</a></li>
</ul>
</li><!-- end of graphics and animation-->
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/renderscript/index.html">
<span class="en">Computation</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/renderscript/compute.html">
<span class="en">RenderScript</span></a>
</li>
<li><a href="../../../guide/topics/renderscript/advanced.html">
<span class="en">Advanced RenderScript</span></a>
</li>
<li><a href="../../../guide/topics/renderscript/reference.html">
<span class="en">Runtime API Reference</span></a>
</li>
</ul>
</li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/media/index.html">
<span class="en">Media and Camera</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/media/mediaplayer.html">
<span class="en">Media Playback</span></a>
</li>
<li><a href="../../../guide/appendix/media-formats.html">
<span class="en">Supported Media Formats</span></a>
</li>
<li><a href="../../../guide/topics/media/audio-capture.html">
<span class="en">Audio Capture</span></a>
</li>
<li><a href="../../../guide/topics/media/jetplayer.html">
<span class="en">JetPlayer</span></a>
</li>
<li><a href="../../../guide/topics/media/camera.html">
<span class="en">Camera</span></a>
</li>
</ul>
</li><!-- end of media and camera -->
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/sensors/index.html">
<span class="en">Location and Sensors</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/location/index.html">
<span class="en">Location and Maps</span>
</a>
<li><a href="../../../guide/topics/location/strategies.html">
<span class="en">Location Strategies</span>
</a></li>
<li><a href="../../../guide/topics/sensors/sensors_overview.html">
<span class="en">Sensors Overview</span>
</a></li>
<li><a href="../../../guide/topics/sensors/sensors_motion.html">
<span class="en">Motion Sensors</span>
</a></li>
<li><a href="../../../guide/topics/sensors/sensors_position.html">
<span class="en">Position Sensors</span>
</a></li>
<li><a href="../../../guide/topics/sensors/sensors_environment.html">
<span class="en">Environment Sensors</span>
</a></li>
</ul>
</li><!-- end of location and sensors -->
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/connectivity/index.html">
<span class="en">Connectivity</span>
</a></div>
<ul>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/connectivity/bluetooth.html">
<span class="en">Bluetooth</span></a>
</div>
<ul>
<li><a href="../../../guide/topics/connectivity/bluetooth-le.html">Bluetooth Low Energy</a></li>
</ul>
</li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/connectivity/nfc/index.html">
<span class="en">NFC</span></a>
</div>
<ul>
<li><a href="../../../guide/topics/connectivity/nfc/nfc.html">NFC Basics</a></li>
<li><a href="../../../guide/topics/connectivity/nfc/advanced-nfc.html">Advanced NFC</a></li>
<li><a href="../../../guide/topics/connectivity/nfc/hce.html">Host-based Card Emulation</a></li>
</ul>
</li>
<li><a href="../../../guide/topics/connectivity/wifip2p.html">
<span class="en">Wi-Fi P2P</span></a>
</li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/connectivity/usb/index.html">
<span class="en">USB</span></a>
</div>
<ul>
<li><a href="../../../guide/topics/connectivity/usb/accessory.html">Accessory</a></li>
<li><a href="../../../guide/topics/connectivity/usb/host.html">Host</a></li>
</ul>
</li>
<li><a href="../../../guide/topics/connectivity/sip.html">
<span class="en">SIP</span>
</a>
</li>
</ul>
</li><!-- end of connectivity -->
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/text/index.html">
<span class="en">Text and Input</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/text/copy-paste.html">
<span class="en">Copy and Paste</span>
</a></li>
<li><a href="../../../guide/topics/text/creating-input-method.html">
<span class="en">Creating an IME</span>
</a></li>
<li><a href="../../../guide/topics/text/spell-checker-framework.html">
<span class="en">Spelling Checker</span>
</a></li>
</ul>
</li><!-- end of text and input -->
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/data/index.html">
<span class="en">Data Storage</span>
</a></div>
<ul>
<li><a href="../../../guide/topics/data/data-storage.html">
<span class="en">Storage Options</span>
</a></li>
<li><a href="../../../guide/topics/data/backup.html">
<span class="en">Data Backup</span>
</a></li>
<li><a href="../../../guide/topics/data/install-location.html">
<span class="en">App Install Location</span>
</a></li>
</ul>
</li><!-- end of data storage -->
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/topics/admin/index.html">
<span class="en">Administration</span>
</a></div>
<ul>
<li>
<a href="../../../guide/topics/admin/device-admin.html">
<span class="en">Device Policies</span></a>
</li>
<!--
<li>
<a href="../../../guide/topics/admin/keychain.html">
<span class="en">Certificate Store</span></a>
</li>
-->
</ul>
</li><!-- end of administration -->
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/webapps/index.html">
<span class="en">Web Apps</span>
</a></div>
<ul>
<li><a href="../../../guide/webapps/overview.html">
<span class="en">Overview</span>
</a></li>
<li><a href="../../../guide/webapps/targeting.html">
<span class="en">Targeting Screens from Web Apps</span>
</a></li>
<li><a href="../../../guide/webapps/webview.html">
<span class="en">Building Web Apps in WebView</span>
</a></li>
<li><a href="../../../guide/webapps/migrating.html">
<span class="en">Migrating to WebView in Android 4.4</span>
</a></li>
<li><a href="../../../guide/webapps/debugging.html">
<span class="en">Debugging Web Apps</span>
</a></li>
<li><a href="../../../guide/webapps/best-practices.html">
<span class="en">Best Practices for Web Apps</span>
</a></li>
</ul>
</li><!-- end of web apps -->
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/practices/index.html">
<span class="en">Best Practices</span>
<span class="de" style="display:none">Bewährte Verfahren</span>
<span class="es" style="display:none">Prácticas recomendadas</span>
<span class="fr" style="display:none">Meilleures pratiques</span>
<span class="it" style="display:none">Best practice</span>
<span class="ja" style="display:none">ベスト プラクティス</span>
<span class="zh-cn" style="display:none">最佳实践</span>
<span class="zh-tw" style="display:none">最佳實務</span>
</div></a>
<ul>
<li><a href="../../../guide/practices/compatibility.html">
<span class="en">Compatibility</span>
</a></li>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/practices/screens_support.html">
<span class="en">Supporting Multiple Screens</span>
</a></div>
<ul>
<li><a href="../../../guide/practices/screens-distribution.html">
<span class="en">Distributing to Specific Screens</span>
</a></li>
<li><a href="../../../guide/practices/screen-compat-mode.html">
<span class="en">Screen Compatibility Mode</span>
</a></li>
</ul>
</li>
<li><a href="../../../guide/practices/tablets-and-handsets.html">
<span class="en">Supporting Tablets and Handsets</span>
</a></li>
</ul>
</li>
<!-- this needs to move
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/practices/ui_guidelines/index.html">
<span class="en">UI Guidelines</span>
</a></div>
<ul>
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/practices/ui_guidelines/icon_design.html">
<span class="en">Icon Design</span>
</a></div>
<ul>
<li><a href="../../../guide/practices/ui_guidelines/icon_design_launcher.html">
<span class="en">Launcher Icons</span>
</a></li>
<li><a href="../../../guide/practices/ui_guidelines/icon_design_menu.html">
<span class="en">Menu Icons</span>
</a></li>
<li><a href="../../../guide/practices/ui_guidelines/icon_design_action_bar.html">
<span class="en">Action Bar Icons</span>
</a></li>
<li><a href="../../../guide/practices/ui_guidelines/icon_design_status_bar.html">
<span class="en">Status Bar Icons</span>
</a></li>
<li><a href="../../../guide/practices/ui_guidelines/icon_design_tab.html">
<span class="en">Tab Icons</span>
</a></li>
<li><a href="../../../guide/practices/ui_guidelines/icon_design_dialog.html">
<span class="en">Dialog Icons</span>
</a></li>
<li><a href="../../../guide/practices/ui_guidelines/icon_design_list.html">
<span class="en">List View Icons</span>
</a></li>
</ul>
</li>
<li><div><a href="../../../guide/practices/ui_guidelines/widget_design.html">
<span class="en">App Widget Design</span>
</a></div>
</li>
</ul>
</li>
</ul> -->
<!-- Remove
<li class="nav-section">
<div class="nav-section-header"><a href="../../../guide/appendix/index.html">
<span class="en">Appendix</span>
<span class="de" style="display:none">Anhang</span>
<span class="es" style="display:none">Apéndice</span>
<span class="fr" style="display:none">Annexes</span>
<span class="it" style="display:none">Appendice</span>
<span class="ja" style="display:none">付録</span>
<span class="zh-cn" style="display:none">附录</span>
<span class="zh-tw" style="display:none">附錄</span>
</a></div>
<ul>
<li><a href="../../../guide/appendix/g-app-intents.html">
<span class="en">Intents List: Google Apps</span>
</a></li>
<li><a href="../../../guide/appendix/glossary.html">
<span class="en">Glossary</span>
</a></li>
</ul>
</li>
</li>
-->
</ul>
<script type="text/javascript">
<!--
buildToggleLists();
changeNavLang(getLangPref());
//-->
</script>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<div class="col-12" id="doc-col" >
<h1 itemprop="name" >Menu Design Guidelines</h1>
<div id="jd-content">
<div class="jd-descr" itemprop="articleBody">
<div id="deprecatedSticker">
<a href="#"
onclick="$('#naMessage').show();$('#deprecatedSticker').hide();return false">
<strong>This doc is deprecated</strong></a>
</div>
<div id="naMessage" style="display:block">
<div><p><strong>This document has been deprecated.</strong></p>
<p>For design guidelines about adding user actions and other options, read the design guidelines
for <a href="../../../design/patterns/actionbar.html">Action Bar</a> or the developer guide about
<a href="../../../guide/topics/ui/menus.html">Menus</a>.</p>
<input style="margin-top:1em;padding:5px" type="button"
value="That's nice, but I still want to read this document"
onclick="$('#naMessage').hide();$('#deprecatedSticker').show()" />
</div>
</div>
<div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul>
<li>An Options menu is for any commands that are global to the current activity. </li>
<li>A Context menu is for any commands that apply to the current selection. </li>
<li>Place the most frequently used operations first. </li>
<li>Put only the most important commands fixed on the screen. </li>
<li>The commands on the Context menu that appears when you touch & hold on an item should be duplicated on the activity you get to by a normal press on that item.
</ul>
<h2>In this document</h2>
<ol>
<li><a href=#tour_of_the_menus>Tour of the Menus</a>
<ol>
<li style="padding-top: 4px;"><a href=#options_menu>Options Menu</a></li>
<li style="padding-top: 4px;"><a href=#context_menu>Context Menu</a></li>
<li style="padding-top: 4px;"><a href=#comparison_of_options_and_context_menus>Comparison of Options & Context Menus</a></li>
<li style="padding-top: 4px;"><a href=#commands_fixed>Commands Fixed in an Activity Screen</a></li>
</ol>
</li>
<li><a href=#guidelines>Guidelines</a>
<ol>
<li style="padding-top: 4px;"><a href=#separate_commands>Separate specific from global commands</a></li>
<li style="padding-top: 4px;"><a href=#most_frequently_used>Place most frequently used first</a></li>
<li style="padding-top: 4px;"><a href=#dont_put_commands>Don't put commands <em>only</em> in a Context menu</li>
<li style="padding-top: 4px;"><a href=#first_in_context_menu>First command in Context menu should be most intuitive</li>
<li style="padding-top: 4px;"><a href=#selecting_content_item>Selecting an item should perform most intuitive operation</a></li>
<li style="padding-top: 4px;"><a href=#context_menu_should_identify>A Context menu should identify the selected item</li>
<li style="padding-top: 4px;"><a href=#most_important_commands>Put only most important commands fixed on the screen</a></li>
<li style="padding-top: 4px;"><a href=#short_names>Use short names in Options icon menu</a></li>
<li style="padding-top: 4px;"><a href=#a_dialog_should_not_have_an_options_menu>A dialog should not have Options menu</a></li>
<li style="padding-top: 4px;"><a href=#do_not_substitute_message>If no Options menu, don't display message</a></li>
<li style="padding-top: 4px;"><a href=#dim_hide_menu_items>Dim or hide menu items not available</a></li>
</ol>
</li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="http://android-developers.blogspot.com/2008/12/touch-mode.html">Touch mode</a></li>
<li><a href="../../../guide/practices/ui_guidelines/activity_task_design.html">Activity and Task Design</a></li>
</ol>
</div>
</div>
<p>
A menu holds a set of commands (user actions) that are normally hidden, and
are accessible by a button, key, or gesture. Menu commands provide a means
for performing operations and for navigating to other parts of your
application or other applications. Menus are useful for freeing screen space,
as an alternative to placing functionality and navigation, in buttons or other
user controls in the content area of your application.
</p>
<p>
The Android system provides two types of menus you can use to provide
functionality or navigation. Between them, you should be able to organize
the functionality and navigation for your application. Briefly:
<ul>
<li>The <em>Options menu</em> contains primary functionality that applies
globally to the current activity or starts a related activity.
It is typically invoked by a user pressing a hard button, often labeled <em>Menu</em>.</li>
<li>The <em>Context menu</em> contains secondary functionality for the currently
selected item. It is typically invoked by a user's touch & hold
on an item. Like on the Options menu, the operation can run either
in the current or another activity.</li>
</ul>
</p>
<p>
All but the simplest applications have menus. The system automatically
lays the menus out and provides standard ways for users to access them.
In this sense, they are familiar and dependable ways for users to access
functionality across all applications. All menus are panels that "float"
on top of the activity screen and are smaller than full screen, so that the
application is still visible around its edges. This is a visual reminder
that a menu is an intermediary operation that disappears once it's used.
</p>
<p>
Let's start out with a quick tour of the menus.
</p>
<h2 id="tour_of_the_menus">Tour of the Menus</h2>
<p class="note"><strong>Note:</strong> Your menus and screens might not look
like those shown in this document; they may vary from one version of Android
or device to another.
</p>
<h3 id="options_menu">Options Menu</h3>
<p>
The Options menu contains commands that apply globally across the current
activity, or can start another activity. They do not apply to a selected
item in the content (a <a href="#context_menu">Context menu</a> does that).
</p>
<p>
On most devices, a user presses the <em>Menu</em> button to access the Options menu,
as shown in the screenshot below. To close the menu, the user presses
<em>Menu</em> again, or presses the <em>Back</em> button.
In fact, to cancel out of any menu, press the <em>Back</em> button. (Pressing the <em>Menu</em>
button or touching outside the menu also works.) Note that how to invoke this
menu may be different on different devices.
</p>
<p>
Each
<a href="../../../guide/practices/ui_guidelines/activity_task_design.html#activities">activity</a>
activity has its own set of operations and therefore its own Options menu.
An application with multiple activities would have a different Options menu
for each activity.
</p>
<p>
For example, in the message list view of an email program, the Options menu
might let you search the messages, compose a new message, refresh the list,
or change the email settings. The compose view of an email program would
have a different Options menu, such as adding a CC field, attaching a file,
or discarding the message.
</p>
<p id="options_icon_expanded_menus">
In order to handle a large number of menu items, the Options menu
progressively discloses them in two steps:
</p>
<ul>
<li>
<b>Options icon menu</b> - The first press of the <em>Menu</em> button displays a
non-scrollable grid of icons at the bottom of the screen. (On the G1
phone, up to 6 buttons typically appear.)
</li>
<li>
<b>Options expanded menu</b> - If the activity has more menu items than will
fit on the icon menu, then the last icon is labeled "More" — selecting it
displays a list that can contain any number of menu items and will scroll
as necessary.
</li>
</ul>
<img src=../../../images/menu_design/MenuDiagram.png>
<p>
On some versions of Android, the user can display keyboard shortcuts in the
icon menu by long pressing the <em>Menu</em> button — the text in the icon menu
alternates between the command names and their keyboard shortcuts (if any).
</p>
<h3 id="context_menu">Context Menu</h3>
<p>
A Context menu is similar to a right-click context menu in a desktop
operating system. It is normally a shortcut that duplicates commands
found elsewhere.
</p>
<p>
A user can touch & hold on content on the screen to
access a Context menu (if one exists), as shown in the screenshot below.
A Context menu is a list of menu items (commands) that can operate
on the selected content. The command can either be part of the current
activity, or the system can pass the selected content along to
an operation in another activity (by way of an
<a href="../../../guide/practices/ui_guidelines/activity_task_design.html#intents">intent</a>).
</p>
<p>
For example, in an email message list, a user can touch & hold on
an email message to open a Context menu containing commands to read,
archive, or delete the message.
</p>
<p id="location">
A user can also touch & hold a <em>location</em> on the screen to
access a Context menu. An example is when the user does touch & hold
on a blank spot on the Home screen, a Context menu appears; selecting
an item from that menu inserts an icon at that location.
</p>
<img src=../../../images/menu_design/ContextMenuDiagram.png>
<h4 id="context_menu_shortcut">Context Menu is a Shortcut</h4>
<p>
In the above example, if the user performs touch & hold on the contact
"Obi Wan Kenobi", a Context menu opens. The commands provided in
this Context menu are the complete set of actions that can be performed
on this contact.
</p>
<p>
A normal touch on an item in the content activates the most intuitive
command for that selection — in this case, "View contact".
We recommend that the most intuitive command also be listed as the
first item in the Context menu. In this example, selecting the contact
"Obi Wan Kenobi" runs the same command "View contact" that is listed
at the top of the Context menu.
</p>
<p>
Also note, as shown in the following screenshot, the Context menu and the
next screen both hold the same complete set of commands that can be performed
on this contact. The Context menu displays the commands in a list,
while the "View contact" activity splits them into various items in the
Options menu, icon buttons and list items.
</p>
<p>
Because of this duplication, using the Context menu is considered a <em>shortcut</em>
for going to the next screen and performing the operation there. Context menus
are less discoverable than either buttons fixed on-screen or the Options menu.
Many users never discover or use Context menus. It is for this reason that, for
the most part, any command on a Context menu should also appear on the most
intuitive operation's screen. As the next section explains, text operations,
such as "Select text" might appear only on a Context menu. Also, rich
applications, such as browsers, which themselves can contain web applications,
may have commands on Context menus that are not available elsewhere.
</p>
<img src=../../../images/menu_design/ContextMenuViewContactDiagram.png>
<h4>Text Commands in Context Menu</h4>
<p>
Text links and text fields in the content both have system-provided operations
that are common across all applications: operations such as "Select all", "Select text",
"Copy all", and "Add to dictionary". If the text field is editable, it also
has other operations, such as "Cut all" and "Input Method", and if text
is also on the clipboard, it has "Paste". The system automatically inserts
the appropriate menu items into the Context menu of text links and text
fields, as shown in the following screenshot.
</p>
<img src=../../../images/menu_design/TextFieldContextMenuDiagram.png>
<h3 id="comparison_of_options_and_context_menus">Comparison of Options and Context Menus</h3>
<p>
An Options menu holds commands that are global to the activity while a
Context menu holds commands that apply only to an item in the content.
As shown in these diagrams, the user navigates to the menu, then
touches a menu item to perform an action or open a dialog.
</p>
<img src=../../../images/menu_design/TaskFlowDiagram.png>
<p>
For more technical information on menus, see the
<a href="../../../guide/topics/ui/menus.html">Menus</a> developer guide.
</p>
<h3 id="commands_fixed">Commands Fixed in an Activity Screen</h4>
<p>
Commands can also be fixed directly on screen, typically in
text buttons, graphic buttons, or list items. This placement is by far the most
discoverable location for commands — a user can immediately see the command
without having to first press a button. This increased visibility needs to be
weighed against the space such user controls take up, or the sense that they
might clutter the visual design.
</p>
<h2 id="guidelines">Guidelines</h2>
<p>
Selecting the right kind of menu to present, and using menus
consistently, are critical factors in good application design. The following
guidelines should assist user experience designers and application developers
toward this end.
</p>
<h3 id="separate_commands">Separate selection-specific commands from global commands</h3>
<p>
Put any commands that are global to the current activity in the Options menu
or place them fixed in an activity screen; put commands that apply to the
current selection in the Context menu. (In any case, the command
could either run as part of this activity or start another activity.)
</p>
<p>
You can determine in which menu to place a command by what it operates on:
If the command acts on selected content (or a particular
<a href="#location">location</a>) on the screen, put the command in the
Context menu for that content. If the command acts on no specific content
or location, put it in the Options menu. This separation of commands
is enforced by the system in the following way. When you press the <em>Menu</em>
button to display the Options menu, the selected content becomes unselected,
and so cannot be operated on. For an explanation
of why the content becomes unselected, see the article on
<a href="http://android-developers.blogspot.com/2008/12/touch-mode.html">Touch mode</a>.
</p>
<p>
An example of a selection-specific Context menu is when a user performs a
touch & hold on a person's name in a list view of a contacts application.
The Context menu would typically contain commands "View contact", "Call contact",
and "Edit contact".
</p>
<h3 id="most_frequently_used">Place the most frequently used operations first</h3>
<p>
Because of limited screen height, some menus may be scrollable, so it's
important to place the most important commands so they can be viewed without
scrolling. In the case of the Options menu, place the most frequently used
operation on its <a href="#options_icon_expanded_menus">icon menu</a>;
the user will have to select "More" to see the rest.
It's also useful to place similar commands in the same location —
for example, the Search icon might always be the first icon in the Options
menu across several activities that offer search.
</p>
<p>
In a Context menu, the most intuitive command should be first, followed
by commands in order of decreasing use, with the least used command at the bottom.
</p>
<h3 id="dont_put_commands">Don't put commands <em>only</em> in a Context menu</h3>
<p>
If a user can fully access your application without using Context menus,
then it's designed properly! In general, if part of your application is inaccessible
without using Context menus, then you need to duplicate those commands elsewhere.
</p>
<p>
Before opening a Context menu, it has no visual representation that identifies
its presence (whereas the Options menu has the <em>Menu</em> button), and so is not
particularly discoverable.
Therefore, in general, a Context menu should <em>duplicate</em> commands
found in the corresponding activity screen. For example, while it's useful to
let the user call a phone number from a Context menu invoked by touch
& hold on a name in a list of contacts, that operation should <em>also</em>
be available by the user touching the phone number itself when viewing contact details.
See <a href="#context_menu_shortcut">shortcut</a> for an illustration of this example.
</p>
<h3 id="first_in_context_menu">The first command in a Context menu should be the selection's most intuitive command</h3>
<p>
As described under <a href="#context_menu_shortcut">shortcut</a>,
touching on an item in the content should activate the same command as touching
the first item in the Context menu. Both cases should be the most intuitive
operation for that item.
</p>
<h3 id="selecting_content_item">Selecting an item in the content should perform the most intuitive operation</h3>
<p>
In your application, when the user touches any actionable text (such as a link
or list item) or image (such as a photo icon), execute the operation most
likely to be desired by the user.
</p>
<p>
Some examples of primary operations:
</p>
<ul>
<li>Selecting an image executes "View image"</li>
<li>Selecting a media icon or filename executes "Play"</li>
<li>Selecting a URL link executes "Open link"</li>
<li>Selecting an address executes "Go to address" (in a maps application)</li>
</ul>
<p>
Note that selecting the same item in different contexts might invoke
different operations:
</p>
<ul>
<li>In a contact application, selecting a contact executes "View details"</li>
<li>In an IM application, selecting a contact executes "Start chat"</li>
<li>In an Email application, when adding a recipient to the "To" field
through the contact book, selecting a contact executes "Add to recipient
list"</li>
</ul>
<h3 id="context_menu_should_identify">A Context menu should identify the selected item</h3>
<p>
When a user does touch & hold on an item, the Context menu should
contain the name of the selected item. Therefore,
when creating a Context menu, be sure to include a title and the name of the
selected item so that it's clear to the user what the context is.
For example, if a user selects a contact "Joan of Arc", put that name in the
title of the Context menu (using
<code><a href="../../../reference/android/view/ContextMenu.html#setHeaderTitle(java.lang.CharSequence)">setHeaderTitle</a></code>).
Likewise, a command to edit the contact should be called "Edit contact",
not just "Edit".
</p>
<h3 id="most_important_commands">Put only the most important commands fixed on the screen</h3>
<p>
By putting commands in menus, you free up the screen to hold more content.
On the other hand, fixing commands in the content area of an activity
makes them more prominent and easy to use.
</p>
<p>
Here are a number of important reasons to place commands fixed on the activity screen:
</p>
<ul>
<li>
To give a command the highest prominence, ensuring the command is obvious and won't be overlooked.<br>
Example: A "Buy" button in a store application.
</li>
<li>
When quick access to the command is important and going to the menu would be
tedious or slow.<br>
Example: Next/Previous buttons or Zoom In/Out buttons in an image viewing application.
</li>
<li>
When in the middle of an operation that needs to be completed.<br>
Example: Save/Discard buttons in an image crop activity.
</li>
<li>
Dialogs and wizards.<br>
Example: OK/Cancel buttons
</li>
<li>
For direct manipulation.<br>
Example: Dragging an icon in the Home screen to the trash
</li>
</ul>
<h3 id="short_names">Use short names in the Options icon menu</h3>
<p>
If a text label in the <a href="#options_icon_expanded_menus">Options icon menu</a>
is too long, the system truncates it in the middle. Thus, "Create Notification"
is truncated to something like "Create…ication". You have no control over
this truncation, so the best bet is to keep the text short. In some versions of Android,
when the icon is highlighted by a navigation key (such as a trackball), the
entire descriptive text may be shown as a marquee, where the words are
readable as they scroll by. <!--For more information, see the Text Guidelines
[update link].-->
</p>
<h3 id="a_dialog_should_not_have_an_options_menu">A dialog should not have an Options menu</h3>
<p>
When a dialog is displayed, pressing the <em>Menu</em> button should do nothing. This also holds
true
for activities that look like dialogs. A dialog box is recognizable by being
smaller than full-screen, having zero to three buttons, is non-scrollable, and
possibly a list of selectable items that can include checkboxes or radio buttons.
<!--For examples of dialogs, see Text Guidelines.-->
</p>
<p>
The rationale behind not having a menu is that when a dialog is displayed, the user is in
the middle of a procedure and should not be allowed to start a new global task
(which is what the Option menu provides).
</p>
<h3 id="do_not_substitute_message">If an activity has no Options menu, do not display a message</h3>
<p>
When the user presses the <em>Menu</em> button, if there is no Options menu, the system
currently does nothing. We recommend you do not perform any action (such as
displaying a message). It's a better user experience for this behavior to be
consistent across applications.
</p>
<h3 id="dim_hide_menu_items">Dim or hide menu items that are not available in the current context</h3>
<p>
Sometimes a menu item's action cannot be performed — for example,
the "Forward" button in a browser cannot work until after the "Back"
button has been pressed. We recommend:
</p>
<ul>
<li>
<b>In Options menu</b> - disable the menu item, which dims the text and icon,
turning it gray. This applies to menu items in both the icon menu and the
"More" menu. It would be disorienting for the icon menu to change from 6
items to 5 items, and we treat the "More" menu the same way.
</li>
<li>
<b>In Context menu</b> - hide the menu item. This makes the menu shorter so the
user sees only available choices (which also reduces any scrolling).
</li>
</ul>
</body>
</html>
</div>
<div class="content-footer layout-content-row"
itemscope itemtype="http://schema.org/SiteNavigationElement">
<div class="layout-content-col col-8" style="padding-top:4px">
<div class="g-plusone" data-size="medium"></div>
</div>
<div class="paging-links layout-content-col col-4">
</div>
</div>
</div> <!-- end jd-content -->
<div id="footer" class="wrap" >
<div id="copyright">
Except as noted, this content is
licensed under <a href="http://creativecommons.org/licenses/by/2.5/">
Creative Commons Attribution 2.5</a>. For details and
restrictions, see the <a href="../../../license.html">Content
License</a>.
</div>
<div id="footerlinks">
<p>
<a href="../../../about/index.html">About Android</a> |
<a href="../../../legal.html">Legal</a> |
<a href="../../../support.html">Support</a>
</p>
</div>
</div> <!-- end footer -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
</body>
</html>
| {
"content_hash": "a4c82b6f19981deea574f94b7e51772d",
"timestamp": "",
"source": "github",
"line_count": 1618,
"max_line_length": 168,
"avg_line_length": 39.20271940667491,
"alnum_prop": 0.5742393189342583,
"repo_name": "terrytowne/android-developer-cn",
"id": "86b644dcda87eb41fc1d34f44cbe823cfaff126d",
"size": "63857",
"binary": false,
"copies": "2",
"ref": "refs/heads/4.4.zh_cn",
"path": "guide/practices/ui_guidelines/menu_design.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "225261"
},
{
"name": "JavaScript",
"bytes": "218708"
}
],
"symlink_target": ""
} |
package com.github.dozermapper.core.vo;
import java.util.Date;
import java.util.Map;
import java.util.Set;
public class NoCustomMappingsObjectPrime extends BaseTestObject {
private String stringDataType;
private Map mapDataType;
private double three;
private Integer four;
private Long five;
private String six;
private String seven;
private Set setDataType;
private Date date;
public void setStringDataType(String one) {
this.stringDataType = one;
}
public String getStringDataType() {
return stringDataType;
}
public Map getMapDataType() {
return mapDataType;
}
public void setMapDataType(Map two) {
this.mapDataType = two;
}
public Long getFive() {
return five;
}
public Integer getFour() {
return four;
}
public String getSeven() {
return seven;
}
public String getSix() {
return six;
}
public double getThree() {
return three;
}
public void setThree(double three) {
this.three = three;
}
public void setSix(String six) {
this.six = six;
}
public void setSeven(String seven) {
this.seven = seven;
}
public void setFour(Integer four) {
this.four = four;
}
public void setFive(Long five) {
this.five = five;
}
public Set getSetDataType() {
return setDataType;
}
public void setSetDataType(Set setDataType) {
this.setDataType = setDataType;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
| {
"content_hash": "48042d9804f71d61b087e2a29c146859",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 65,
"avg_line_length": 18.505494505494507,
"alnum_prop": 0.6051068883610451,
"repo_name": "orange-buffalo/dozer",
"id": "eddc92830cac0fd246f8182a7fc7c9b96e39300e",
"size": "2286",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/test/java/com/github/dozermapper/core/vo/NoCustomMappingsObjectPrime.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2283605"
},
{
"name": "Shell",
"bytes": "1705"
}
],
"symlink_target": ""
} |
/*
* Table styles
*/
table.dataTable {
width: 100%;
margin: 0 auto;
clear: both;
border-collapse: separate;
border-spacing: 0;
/*
* Header and footer styles
*/
/*
* Body styles
*/
}
table.dataTable thead th,
table.dataTable tfoot th {
font-weight: bold;
}
table.dataTable thead th,
table.dataTable thead td {
padding: 10px 18px;
border-bottom: 1px solid #111111;
}
table.dataTable thead th:active,
table.dataTable thead td:active {
outline: none;
}
table.dataTable tfoot th,
table.dataTable tfoot td {
padding: 10px 18px 6px 18px;
border-top: 1px solid #111111;
}
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting {
cursor: pointer;
*cursor: hand;
}
table.dataTable thead .sorting {
background: url("../images/sort_both.png") #016cc2 no-repeat center right;
}
table.dataTable thead .sorting_asc {
background: url("../images/sort_asc.png") #016cc2 no-repeat center right;
}
table.dataTable thead .sorting_desc {
background: url("../images/sort_desc.png") #016cc2 no-repeat center right;
}
table.dataTable thead .sorting_asc_disabled {
background: url("../images/sort_asc_disabled.png") #016cc2 no-repeat center right;
}
table.dataTable thead .sorting_desc_disabled {
background: url("../images/sort_desc_disabled.png") #016cc2 no-repeat center right;
}
table.dataTable tbody tr {
background-color: white;
}
table.dataTable tbody tr.selected {
background-color: #b0bed9;
}
table.dataTable tbody th,
table.dataTable tbody td {
padding: 8px 10px;
}
table.dataTable.row-border tbody th, table.dataTable.row-border tbody td, table.dataTable.display tbody th, table.dataTable.display tbody td {
border-top: 1px solid #dddddd;
}
table.dataTable.row-border tbody tr:first-child th,
table.dataTable.row-border tbody tr:first-child td, table.dataTable.display tbody tr:first-child th,
table.dataTable.display tbody tr:first-child td {
border-top: none;
}
table.dataTable.cell-border tbody th, table.dataTable.cell-border tbody td {
border-top: 1px solid #dddddd;
border-right: 1px solid #dddddd;
}
table.dataTable.cell-border tbody tr th:first-child,
table.dataTable.cell-border tbody tr td:first-child {
border-left: 1px solid #dddddd;
}
table.dataTable.cell-border tbody tr:first-child th,
table.dataTable.cell-border tbody tr:first-child td {
border-top: none;
}
table.dataTable.stripe tbody tr.odd, table.dataTable.display tbody tr.odd {
background-color: #f9f9f9;
}
table.dataTable.stripe tbody tr.odd.selected, table.dataTable.display tbody tr.odd.selected {
background-color: #abb9d3;
}
table.dataTable.hover tbody tr:hover,
table.dataTable.hover tbody tr.odd:hover,
table.dataTable.hover tbody tr.even:hover, table.dataTable.display tbody tr:hover,
table.dataTable.display tbody tr.odd:hover,
table.dataTable.display tbody tr.even:hover {
background-color: whitesmoke;
}
table.dataTable.hover tbody tr:hover.selected,
table.dataTable.hover tbody tr.odd:hover.selected,
table.dataTable.hover tbody tr.even:hover.selected, table.dataTable.display tbody tr:hover.selected,
table.dataTable.display tbody tr.odd:hover.selected,
table.dataTable.display tbody tr.even:hover.selected {
background-color: #a9b7d1;
}
table.dataTable.order-column tbody tr > .sorting_1,
table.dataTable.order-column tbody tr > .sorting_2,
table.dataTable.order-column tbody tr > .sorting_3, table.dataTable.display tbody tr > .sorting_1,
table.dataTable.display tbody tr > .sorting_2,
table.dataTable.display tbody tr > .sorting_3 {
background-color: #f9f9f9;
}
table.dataTable.order-column tbody tr.selected > .sorting_1,
table.dataTable.order-column tbody tr.selected > .sorting_2,
table.dataTable.order-column tbody tr.selected > .sorting_3, table.dataTable.display tbody tr.selected > .sorting_1,
table.dataTable.display tbody tr.selected > .sorting_2,
table.dataTable.display tbody tr.selected > .sorting_3 {
background-color: #acbad4;
}
table.dataTable.display tbody tr.odd > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd > .sorting_1 {
background-color: #f1f1f1;
}
table.dataTable.display tbody tr.odd > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd > .sorting_2 {
background-color: #f3f3f3;
}
table.dataTable.display tbody tr.odd > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd > .sorting_3 {
background-color: whitesmoke;
}
table.dataTable.display tbody tr.odd.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_1 {
background-color: #a6b3cd;
}
table.dataTable.display tbody tr.odd.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_2 {
background-color: #a7b5ce;
}
table.dataTable.display tbody tr.odd.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_3 {
background-color: #a9b6d0;
}
table.dataTable.display tbody tr.even > .sorting_1, table.dataTable.order-column.stripe tbody tr.even > .sorting_1 {
background-color: #f9f9f9;
}
table.dataTable.display tbody tr.even > .sorting_2, table.dataTable.order-column.stripe tbody tr.even > .sorting_2 {
background-color: #fbfbfb;
}
table.dataTable.display tbody tr.even > .sorting_3, table.dataTable.order-column.stripe tbody tr.even > .sorting_3 {
background-color: #fdfdfd;
}
table.dataTable.display tbody tr.even.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_1 {
background-color: #acbad4;
}
table.dataTable.display tbody tr.even.selected > .sorting_2, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_2 {
background-color: #adbbd6;
}
table.dataTable.display tbody tr.even.selected > .sorting_3, table.dataTable.order-column.stripe tbody tr.even.selected > .sorting_3 {
background-color: #afbdd8;
}
table.dataTable.display tbody tr:hover > .sorting_1,
table.dataTable.display tbody tr.odd:hover > .sorting_1,
table.dataTable.display tbody tr.even:hover > .sorting_1, table.dataTable.order-column.hover tbody tr:hover > .sorting_1,
table.dataTable.order-column.hover tbody tr.odd:hover > .sorting_1,
table.dataTable.order-column.hover tbody tr.even:hover > .sorting_1 {
background-color: #eaeaea;
}
table.dataTable.display tbody tr:hover > .sorting_2,
table.dataTable.display tbody tr.odd:hover > .sorting_2,
table.dataTable.display tbody tr.even:hover > .sorting_2, table.dataTable.order-column.hover tbody tr:hover > .sorting_2,
table.dataTable.order-column.hover tbody tr.odd:hover > .sorting_2,
table.dataTable.order-column.hover tbody tr.even:hover > .sorting_2 {
background-color: #ebebeb;
}
table.dataTable.display tbody tr:hover > .sorting_3,
table.dataTable.display tbody tr.odd:hover > .sorting_3,
table.dataTable.display tbody tr.even:hover > .sorting_3, table.dataTable.order-column.hover tbody tr:hover > .sorting_3,
table.dataTable.order-column.hover tbody tr.odd:hover > .sorting_3,
table.dataTable.order-column.hover tbody tr.even:hover > .sorting_3 {
background-color: #eeeeee;
}
table.dataTable.display tbody tr:hover.selected > .sorting_1,
table.dataTable.display tbody tr.odd:hover.selected > .sorting_1,
table.dataTable.display tbody tr.even:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_1,
table.dataTable.order-column.hover tbody tr.odd:hover.selected > .sorting_1,
table.dataTable.order-column.hover tbody tr.even:hover.selected > .sorting_1 {
background-color: #a1aec7;
}
table.dataTable.display tbody tr:hover.selected > .sorting_2,
table.dataTable.display tbody tr.odd:hover.selected > .sorting_2,
table.dataTable.display tbody tr.even:hover.selected > .sorting_2, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_2,
table.dataTable.order-column.hover tbody tr.odd:hover.selected > .sorting_2,
table.dataTable.order-column.hover tbody tr.even:hover.selected > .sorting_2 {
background-color: #a2afc8;
}
table.dataTable.display tbody tr:hover.selected > .sorting_3,
table.dataTable.display tbody tr.odd:hover.selected > .sorting_3,
table.dataTable.display tbody tr.even:hover.selected > .sorting_3, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_3,
table.dataTable.order-column.hover tbody tr.odd:hover.selected > .sorting_3,
table.dataTable.order-column.hover tbody tr.even:hover.selected > .sorting_3 {
background-color: #a4b2cb;
}
table.dataTable.no-footer {
border-bottom: 1px solid #111111;
}
table.dataTable.nowrap th, table.dataTable.nowrap td {
white-space: nowrap;
}
table.dataTable.compact thead th,
table.dataTable.compact thead td {
padding: 5px 9px;
}
table.dataTable.compact tfoot th,
table.dataTable.compact tfoot td {
padding: 5px 9px 3px 9px;
}
table.dataTable.compact tbody th,
table.dataTable.compact tbody td {
padding: 4px 5px;
}
table.dataTable th.dt-left,
table.dataTable td.dt-left {
text-align: left;
}
table.dataTable th.dt-center,
table.dataTable td.dt-center,
table.dataTable td.dataTables_empty {
text-align: center;
padding:25px 0px;
}
table.dataTable th.dt-right,
table.dataTable td.dt-right {
text-align: right;
}
table.dataTable th.dt-justify,
table.dataTable td.dt-justify {
text-align: justify;
}
table.dataTable th.dt-nowrap,
table.dataTable td.dt-nowrap {
white-space: nowrap;
}
table.dataTable thead th.dt-head-left,
table.dataTable thead td.dt-head-left,
table.dataTable tfoot th.dt-head-left,
table.dataTable tfoot td.dt-head-left {
text-align: left;
}
table.dataTable thead th.dt-head-center,
table.dataTable thead td.dt-head-center,
table.dataTable tfoot th.dt-head-center,
table.dataTable tfoot td.dt-head-center {
text-align: center;
}
table.dataTable thead th.dt-head-right,
table.dataTable thead td.dt-head-right,
table.dataTable tfoot th.dt-head-right,
table.dataTable tfoot td.dt-head-right {
text-align: right;
}
table.dataTable thead th.dt-head-justify,
table.dataTable thead td.dt-head-justify,
table.dataTable tfoot th.dt-head-justify,
table.dataTable tfoot td.dt-head-justify {
text-align: justify;
}
table.dataTable thead th.dt-head-nowrap,
table.dataTable thead td.dt-head-nowrap,
table.dataTable tfoot th.dt-head-nowrap,
table.dataTable tfoot td.dt-head-nowrap {
white-space: nowrap;
}
table.dataTable tbody th.dt-body-left,
table.dataTable tbody td.dt-body-left {
text-align: left;
}
table.dataTable tbody th.dt-body-center,
table.dataTable tbody td.dt-body-center {
text-align: center;
}
table.dataTable tbody th.dt-body-right,
table.dataTable tbody td.dt-body-right {
text-align: right;
}
table.dataTable tbody th.dt-body-justify,
table.dataTable tbody td.dt-body-justify {
text-align: justify;
}
table.dataTable tbody th.dt-body-nowrap,
table.dataTable tbody td.dt-body-nowrap {
white-space: nowrap;
}
table.dataTable,
table.dataTable th,
table.dataTable td {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
/*
* Control feature layout
*/
.dataTables_wrapper {
position: relative;
clear: both;
*zoom: 1;
zoom: 1;
}
.dataTables_wrapper .dataTables_length {
float: left;
}
.dataTables_wrapper .dataTables_filter {
float: right;
text-align: right;
}
.dataTables_wrapper .dataTables_filter input {
margin-left: 0.5em;
font-size:11px;
width:170px;
}
.dataTables_wrapper .dataTables_info {
clear: both;
float: left;
padding-top: 0.755em;
}
.dataTables_wrapper .dataTables_paginate {
float: right;
text-align: right;
padding-top: 0.25em;
}
.dataTables_wrapper .dataTables_paginate .paginate_button {
box-sizing: border-box;
display: inline-block;
min-width: 1.5em;
padding: 0.5em 1em;
margin-left: 2px;
text-align: center;
text-decoration: none !important;
cursor: pointer;
*cursor: hand;
color: #333333 !important;
border: 1px solid transparent;
}
.dataTables_wrapper .dataTables_paginate .paginate_button.current, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover {
color: #333333 !important;
border: 1px solid #cacaca;
background-color: white;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, white), color-stop(100%, gainsboro));
/* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, white 0%, gainsboro 100%);
/* Chrome10+,Safari5.1+ */
background: -moz-linear-gradient(top, white 0%, gainsboro 100%);
/* FF3.6+ */
background: -ms-linear-gradient(top, white 0%, gainsboro 100%);
/* IE10+ */
background: -o-linear-gradient(top, white 0%, gainsboro 100%);
/* Opera 11.10+ */
background: linear-gradient(to bottom, white 0%, gainsboro 100%);
/* W3C */
}
.dataTables_wrapper .dataTables_paginate .paginate_button.disabled, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover, .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active {
cursor: default;
color: #666 !important;
border: 1px solid transparent;
background: transparent;
box-shadow: none;
}
.dataTables_wrapper .dataTables_paginate .paginate_button:hover {
color: white !important;
border: 1px solid #111111;
background-color: #585858;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #585858), color-stop(100%, #111111));
/* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #585858 0%, #111111 100%);
/* Chrome10+,Safari5.1+ */
background: -moz-linear-gradient(top, #585858 0%, #111111 100%);
/* FF3.6+ */
background: -ms-linear-gradient(top, #585858 0%, #111111 100%);
/* IE10+ */
background: -o-linear-gradient(top, #585858 0%, #111111 100%);
/* Opera 11.10+ */
background: linear-gradient(to bottom, #585858 0%, #111111 100%);
/* W3C */
}
.dataTables_wrapper .dataTables_paginate .paginate_button:active {
outline: none;
background-color: #2b2b2b;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #2b2b2b), color-stop(100%, #0c0c0c));
/* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
/* Chrome10+,Safari5.1+ */
background: -moz-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
/* FF3.6+ */
background: -ms-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
/* IE10+ */
background: -o-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);
/* Opera 11.10+ */
background: linear-gradient(to bottom, #2b2b2b 0%, #0c0c0c 100%);
/* W3C */
box-shadow: inset 0 0 3px #111;
}
.dataTables_wrapper .dataTables_processing {
position: absolute;
top: 50%;
left: 50%;
width: 100%;
height: 40px;
margin-left: -50%;
margin-top: -25px;
padding-top: 20px;
text-align: center;
font-size: 1.2em;
background-color: white;
background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255, 255, 255, 0)), color-stop(25%, rgba(255, 255, 255, 0.9)), color-stop(75%, rgba(255, 255, 255, 0.9)), color-stop(100%, rgba(255, 255, 255, 0)));
/* Chrome,Safari4+ */
background: -webkit-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
/* Chrome10+,Safari5.1+ */
background: -moz-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
/* FF3.6+ */
background: -ms-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
/* IE10+ */
background: -o-linear-gradient(left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
/* Opera 11.10+ */
background: linear-gradient(to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 25%, rgba(255, 255, 255, 0.9) 75%, rgba(255, 255, 255, 0) 100%);
/* W3C */
}
.dataTables_wrapper .dataTables_length,
.dataTables_wrapper .dataTables_filter,
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_processing,
.dataTables_wrapper .dataTables_paginate {
color: #333333;
font-size:13px;
}
.dataTables_wrapper .dataTables_scroll {
clear: both;
}
.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody {
*margin-top: -1px;
-webkit-overflow-scrolling: touch;
}
.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th > div.dataTables_sizing,
.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td > div.dataTables_sizing {
height: 0;
overflow: hidden;
margin: 0 !important;
padding: 0 !important;
}
.dataTables_wrapper.no-footer .dataTables_scrollBody {
border-bottom: 1px solid #111111;
}
.dataTables_wrapper.no-footer div.dataTables_scrollHead table,
.dataTables_wrapper.no-footer div.dataTables_scrollBody table {
border-bottom: none;
}
.dataTables_wrapper:after {
visibility: hidden;
display: block;
content: "";
clear: both;
height: 0;
}
@media screen and (max-width: 767px) {
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_paginate {
float: none;
text-align: center;
}
.dataTables_wrapper .dataTables_paginate {
margin-top: 0.5em;
}
}
@media screen and (max-width: 640px) {
.dataTables_wrapper .dataTables_length,
.dataTables_wrapper .dataTables_filter {
float: none;
text-align: center;
}
.dataTables_wrapper .dataTables_filter {
margin-top: 0.5em;
}
}
| {
"content_hash": "958d2361987d5553dfe96f9ea49b9c29",
"timestamp": "",
"source": "github",
"line_count": 480,
"max_line_length": 228,
"avg_line_length": 36.07083333333333,
"alnum_prop": 0.7321242924800739,
"repo_name": "assettcu/places",
"id": "6013b3480e473421ad766952a4f6d2903a8cbfcf",
"size": "17314",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "library/jquery/modules/datatables/media/css/jquery.dataTables.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "348"
},
{
"name": "Batchfile",
"bytes": "380"
},
{
"name": "CSS",
"bytes": "311356"
},
{
"name": "HTML",
"bytes": "3767044"
},
{
"name": "JavaScript",
"bytes": "1977513"
},
{
"name": "PHP",
"bytes": "312073"
}
],
"symlink_target": ""
} |
namespace blink {
namespace {
DOMException* ToException(WebSetSinkIdError error) {
switch (error) {
case WebSetSinkIdError::kNotFound:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotFoundError, "Requested device not found");
case WebSetSinkIdError::kNotAuthorized:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"No permission to use requested device");
case WebSetSinkIdError::kAborted:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kAbortError,
"The operation could not be performed and was aborted");
case WebSetSinkIdError::kNotSupported:
return MakeGarbageCollected<DOMException>(
DOMExceptionCode::kNotSupportedError, "Operation not supported");
default:
NOTREACHED();
return MakeGarbageCollected<DOMException>(DOMExceptionCode::kAbortError,
"Invalid error code");
}
}
class SetSinkIdResolver : public ScriptPromiseResolver {
public:
static SetSinkIdResolver* Create(ScriptState*,
HTMLMediaElement&,
const String& sink_id);
SetSinkIdResolver(ScriptState*, HTMLMediaElement&, const String& sink_id);
SetSinkIdResolver(const SetSinkIdResolver&) = delete;
SetSinkIdResolver& operator=(const SetSinkIdResolver&) = delete;
~SetSinkIdResolver() override = default;
void StartAsync();
void Start();
void Trace(Visitor*) const override;
private:
void DoSetSinkId();
void OnSetSinkIdComplete(absl::optional<WebSetSinkIdError> error);
Member<HTMLMediaElement> element_;
String sink_id_;
};
SetSinkIdResolver* SetSinkIdResolver::Create(ScriptState* script_state,
HTMLMediaElement& element,
const String& sink_id) {
SetSinkIdResolver* resolver =
MakeGarbageCollected<SetSinkIdResolver>(script_state, element, sink_id);
resolver->KeepAliveWhilePending();
return resolver;
}
SetSinkIdResolver::SetSinkIdResolver(ScriptState* script_state,
HTMLMediaElement& element,
const String& sink_id)
: ScriptPromiseResolver(script_state),
element_(element),
sink_id_(sink_id) {}
void SetSinkIdResolver::StartAsync() {
ExecutionContext* context = GetExecutionContext();
if (!context)
return;
context->GetTaskRunner(TaskType::kInternalMedia)
->PostTask(FROM_HERE, WTF::Bind(&SetSinkIdResolver::DoSetSinkId,
WrapWeakPersistent(this)));
}
void SetSinkIdResolver::Start() {
auto* context = GetExecutionContext();
if (!context || context->IsContextDestroyed())
return;
if (LocalDOMWindow* window = DynamicTo<LocalDOMWindow>(context)) {
if (window->document()->IsPrerendering()) {
window->document()->AddPostPrerenderingActivationStep(
WTF::Bind(&SetSinkIdResolver::Start, WrapWeakPersistent(this)));
return;
}
}
if (sink_id_ == HTMLMediaElementAudioOutputDevice::sinkId(*element_))
Resolve();
else
StartAsync();
}
void SetSinkIdResolver::DoSetSinkId() {
auto set_sink_id_completion_callback =
WTF::Bind(&SetSinkIdResolver::OnSetSinkIdComplete, WrapPersistent(this));
WebMediaPlayer* web_media_player = element_->GetWebMediaPlayer();
if (web_media_player) {
if (web_media_player->SetSinkId(
sink_id_, std::move(set_sink_id_completion_callback))) {
element_->DidAudioOutputSinkChanged(sink_id_);
}
return;
}
ExecutionContext* context = GetExecutionContext();
if (!context) {
// Detached contexts shouldn't be playing audio. Note that despite this
// explicit Reject(), any associated JS callbacks will never be called
// because the context is already detached...
Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"Impossible to authorize device for detached context"));
return;
}
// This is associated with an HTML element, so the context must be a window.
if (WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(
To<LocalDOMWindow>(context)->GetFrame())) {
web_frame->Client()->CheckIfAudioSinkExistsAndIsAuthorized(
sink_id_, std::move(set_sink_id_completion_callback));
} else {
Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"Impossible to authorize device if there is no frame"));
return;
}
}
void SetSinkIdResolver::OnSetSinkIdComplete(
absl::optional<WebSetSinkIdError> error) {
if (!GetExecutionContext() || GetExecutionContext()->IsContextDestroyed())
return;
if (error) {
Reject(ToException(*error));
return;
}
HTMLMediaElementAudioOutputDevice& aod_element =
HTMLMediaElementAudioOutputDevice::From(*element_);
aod_element.setSinkId(sink_id_);
Resolve();
}
void SetSinkIdResolver::Trace(Visitor* visitor) const {
visitor->Trace(element_);
ScriptPromiseResolver::Trace(visitor);
}
} // namespace
HTMLMediaElementAudioOutputDevice::HTMLMediaElementAudioOutputDevice(
HTMLMediaElement& element)
: AudioOutputDeviceController(element) {}
// static
HTMLMediaElementAudioOutputDevice& HTMLMediaElementAudioOutputDevice::From(
HTMLMediaElement& element) {
HTMLMediaElementAudioOutputDevice* self =
static_cast<HTMLMediaElementAudioOutputDevice*>(
AudioOutputDeviceController::From(element));
if (!self) {
self = MakeGarbageCollected<HTMLMediaElementAudioOutputDevice>(element);
AudioOutputDeviceController::ProvideTo(element, self);
}
return *self;
}
String HTMLMediaElementAudioOutputDevice::sinkId(HTMLMediaElement& element) {
HTMLMediaElementAudioOutputDevice& aod_element =
HTMLMediaElementAudioOutputDevice::From(element);
return aod_element.sink_id_;
}
void HTMLMediaElementAudioOutputDevice::setSinkId(const String& sink_id) {
sink_id_ = sink_id;
}
ScriptPromise HTMLMediaElementAudioOutputDevice::setSinkId(
ScriptState* script_state,
HTMLMediaElement& element,
const String& sink_id) {
SetSinkIdResolver* resolver =
SetSinkIdResolver::Create(script_state, element, sink_id);
ScriptPromise promise = resolver->Promise();
resolver->Start();
return promise;
}
void HTMLMediaElementAudioOutputDevice::SetSinkId(const String& sink_id) {
// No need to call WebFrameClient::CheckIfAudioSinkExistsAndIsAuthorized as
// this call is not coming from content and should already be allowed.
HTMLMediaElement* html_media_element = GetSupplementable();
WebMediaPlayer* web_media_player = html_media_element->GetWebMediaPlayer();
if (!web_media_player)
return;
sink_id_ = sink_id;
if (web_media_player->SetSinkId(sink_id_, base::DoNothing()))
html_media_element->DidAudioOutputSinkChanged(sink_id_);
}
void HTMLMediaElementAudioOutputDevice::Trace(Visitor* visitor) const {
AudioOutputDeviceController::Trace(visitor);
}
} // namespace blink
| {
"content_hash": "fa6b604a6be0a2001359e3394b9e53f4",
"timestamp": "",
"source": "github",
"line_count": 213,
"max_line_length": 79,
"avg_line_length": 33.455399061032864,
"alnum_prop": 0.7022172326690991,
"repo_name": "scheib/chromium",
"id": "c4f8915992f896e3030ef1e650528c53dfc5b6c4",
"size": "8307",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "third_party/blink/renderer/modules/audio_output_devices/html_media_element_audio_output_device.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package eu.agilejava.snoopee.ui;
import eu.agilejava.snoopee.SnoopEEClientRegistry;
import eu.agilejava.snoopee.SnoopEEConfig;
import java.util.Collection;
import java.util.Set;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
/**
* Controller for the SnoopEE service UI.
*
* @author Ivar Grimstad (ivar.grimstad@gmail.com)
*/
@Named
@RequestScoped
public class SnoopController {
private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee");
@EJB
private SnoopEEClientRegistry clients;
public Set<String> getClients() {
return clients.getClients();
}
public Collection<SnoopEEConfig> getClientConfigurations() {
return clients.getServiceConfigs();
}
}
| {
"content_hash": "d1cb9c7f3e60922c9778b0cd6c61e565",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 81,
"avg_line_length": 23.441176470588236,
"alnum_prop": 0.7553324968632371,
"repo_name": "ivargrimstad/snoopee",
"id": "ff8daea4f80895c1054f5e42a827ba2309869629",
"size": "1959",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/ui/SnoopController.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1552"
},
{
"name": "HTML",
"bytes": "4364"
},
{
"name": "Java",
"bytes": "107758"
},
{
"name": "Shell",
"bytes": "280"
}
],
"symlink_target": ""
} |
// MESSAGE VISION_SPEED_ESTIMATE PACKING
#define MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE 103
MAVPACKED(
typedef struct __mavlink_vision_speed_estimate_t {
uint64_t usec; /*< Timestamp (microseconds, synced to UNIX time or since system boot)*/
float x; /*< Global X speed*/
float y; /*< Global Y speed*/
float z; /*< Global Z speed*/
}) mavlink_vision_speed_estimate_t;
#define MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN 20
#define MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_MIN_LEN 20
#define MAVLINK_MSG_ID_103_LEN 20
#define MAVLINK_MSG_ID_103_MIN_LEN 20
#define MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_CRC 208
#define MAVLINK_MSG_ID_103_CRC 208
#if MAVLINK_COMMAND_24BIT
#define MAVLINK_MESSAGE_INFO_VISION_SPEED_ESTIMATE { \
103, \
"VISION_SPEED_ESTIMATE", \
4, \
{ { "usec", NULL, MAVLINK_TYPE_UINT64_T, 0, 0, offsetof(mavlink_vision_speed_estimate_t, usec) }, \
{ "x", NULL, MAVLINK_TYPE_FLOAT, 0, 8, offsetof(mavlink_vision_speed_estimate_t, x) }, \
{ "y", NULL, MAVLINK_TYPE_FLOAT, 0, 12, offsetof(mavlink_vision_speed_estimate_t, y) }, \
{ "z", NULL, MAVLINK_TYPE_FLOAT, 0, 16, offsetof(mavlink_vision_speed_estimate_t, z) }, \
} \
}
#else
#define MAVLINK_MESSAGE_INFO_VISION_SPEED_ESTIMATE { \
"VISION_SPEED_ESTIMATE", \
4, \
{ { "usec", NULL, MAVLINK_TYPE_UINT64_T, 0, 0, offsetof(mavlink_vision_speed_estimate_t, usec) }, \
{ "x", NULL, MAVLINK_TYPE_FLOAT, 0, 8, offsetof(mavlink_vision_speed_estimate_t, x) }, \
{ "y", NULL, MAVLINK_TYPE_FLOAT, 0, 12, offsetof(mavlink_vision_speed_estimate_t, y) }, \
{ "z", NULL, MAVLINK_TYPE_FLOAT, 0, 16, offsetof(mavlink_vision_speed_estimate_t, z) }, \
} \
}
#endif
/**
* @brief Pack a vision_speed_estimate message
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
*
* @param usec Timestamp (microseconds, synced to UNIX time or since system boot)
* @param x Global X speed
* @param y Global Y speed
* @param z Global Z speed
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_vision_speed_estimate_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
uint64_t usec, float x, float y, float z)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN];
_mav_put_uint64_t(buf, 0, usec);
_mav_put_float(buf, 8, x);
_mav_put_float(buf, 12, y);
_mav_put_float(buf, 16, z);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN);
#else
mavlink_vision_speed_estimate_t packet;
packet.usec = usec;
packet.x = x;
packet.y = y;
packet.z = z;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE;
return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_MIN_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_CRC);
}
/**
* @brief Pack a vision_speed_estimate message on a channel
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param usec Timestamp (microseconds, synced to UNIX time or since system boot)
* @param x Global X speed
* @param y Global Y speed
* @param z Global Z speed
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_vision_speed_estimate_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t* msg,
uint64_t usec,float x,float y,float z)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN];
_mav_put_uint64_t(buf, 0, usec);
_mav_put_float(buf, 8, x);
_mav_put_float(buf, 12, y);
_mav_put_float(buf, 16, z);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN);
#else
mavlink_vision_speed_estimate_t packet;
packet.usec = usec;
packet.x = x;
packet.y = y;
packet.z = z;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE;
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_MIN_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_CRC);
}
/**
* @brief Encode a vision_speed_estimate struct
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
* @param vision_speed_estimate C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_vision_speed_estimate_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_vision_speed_estimate_t* vision_speed_estimate)
{
return mavlink_msg_vision_speed_estimate_pack(system_id, component_id, msg, vision_speed_estimate->usec, vision_speed_estimate->x, vision_speed_estimate->y, vision_speed_estimate->z);
}
/**
* @brief Encode a vision_speed_estimate struct on a channel
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param vision_speed_estimate C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_vision_speed_estimate_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_vision_speed_estimate_t* vision_speed_estimate)
{
return mavlink_msg_vision_speed_estimate_pack_chan(system_id, component_id, chan, msg, vision_speed_estimate->usec, vision_speed_estimate->x, vision_speed_estimate->y, vision_speed_estimate->z);
}
/**
* @brief Send a vision_speed_estimate message
* @param chan MAVLink channel to send the message
*
* @param usec Timestamp (microseconds, synced to UNIX time or since system boot)
* @param x Global X speed
* @param y Global Y speed
* @param z Global Z speed
*/
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
static inline void mavlink_msg_vision_speed_estimate_send(mavlink_channel_t chan, uint64_t usec, float x, float y, float z)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN];
_mav_put_uint64_t(buf, 0, usec);
_mav_put_float(buf, 8, x);
_mav_put_float(buf, 12, y);
_mav_put_float(buf, 16, z);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE, buf, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_MIN_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_CRC);
#else
mavlink_vision_speed_estimate_t packet;
packet.usec = usec;
packet.x = x;
packet.y = y;
packet.z = z;
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE, (const char *)&packet, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_MIN_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_CRC);
#endif
}
/**
* @brief Send a vision_speed_estimate message
* @param chan MAVLink channel to send the message
* @param struct The MAVLink struct to serialize
*/
static inline void mavlink_msg_vision_speed_estimate_send_struct(mavlink_channel_t chan, const mavlink_vision_speed_estimate_t* vision_speed_estimate)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
mavlink_msg_vision_speed_estimate_send(chan, vision_speed_estimate->usec, vision_speed_estimate->x, vision_speed_estimate->y, vision_speed_estimate->z);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE, (const char *)vision_speed_estimate, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_MIN_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_CRC);
#endif
}
#if MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
This varient of _send() can be used to save stack space by re-using
memory from the receive buffer. The caller provides a
mavlink_message_t which is the size of a full mavlink message. This
is usually the receive buffer for the channel, and allows a reply to an
incoming message with minimum stack space usage.
*/
static inline void mavlink_msg_vision_speed_estimate_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan, uint64_t usec, float x, float y, float z)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char *buf = (char *)msgbuf;
_mav_put_uint64_t(buf, 0, usec);
_mav_put_float(buf, 8, x);
_mav_put_float(buf, 12, y);
_mav_put_float(buf, 16, z);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE, buf, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_MIN_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_CRC);
#else
mavlink_vision_speed_estimate_t *packet = (mavlink_vision_speed_estimate_t *)msgbuf;
packet->usec = usec;
packet->x = x;
packet->y = y;
packet->z = z;
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE, (const char *)packet, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_MIN_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_CRC);
#endif
}
#endif
#endif
// MESSAGE VISION_SPEED_ESTIMATE UNPACKING
/**
* @brief Get field usec from vision_speed_estimate message
*
* @return Timestamp (microseconds, synced to UNIX time or since system boot)
*/
static inline uint64_t mavlink_msg_vision_speed_estimate_get_usec(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint64_t(msg, 0);
}
/**
* @brief Get field x from vision_speed_estimate message
*
* @return Global X speed
*/
static inline float mavlink_msg_vision_speed_estimate_get_x(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 8);
}
/**
* @brief Get field y from vision_speed_estimate message
*
* @return Global Y speed
*/
static inline float mavlink_msg_vision_speed_estimate_get_y(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 12);
}
/**
* @brief Get field z from vision_speed_estimate message
*
* @return Global Z speed
*/
static inline float mavlink_msg_vision_speed_estimate_get_z(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 16);
}
/**
* @brief Decode a vision_speed_estimate message into a struct
*
* @param msg The message to decode
* @param vision_speed_estimate C-struct to decode the message contents into
*/
static inline void mavlink_msg_vision_speed_estimate_decode(const mavlink_message_t* msg, mavlink_vision_speed_estimate_t* vision_speed_estimate)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
vision_speed_estimate->usec = mavlink_msg_vision_speed_estimate_get_usec(msg);
vision_speed_estimate->x = mavlink_msg_vision_speed_estimate_get_x(msg);
vision_speed_estimate->y = mavlink_msg_vision_speed_estimate_get_y(msg);
vision_speed_estimate->z = mavlink_msg_vision_speed_estimate_get_z(msg);
#else
uint8_t len = msg->len < MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN? msg->len : MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN;
memset(vision_speed_estimate, 0, MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE_LEN);
memcpy(vision_speed_estimate, _MAV_PAYLOAD(msg), len);
#endif
}
| {
"content_hash": "5ca7c6e5b0b915e60f7e6e5e5a811dde",
"timestamp": "",
"source": "github",
"line_count": 287,
"max_line_length": 247,
"avg_line_length": 40.26132404181185,
"alnum_prop": 0.7220250973604501,
"repo_name": "darknight-007/sitl_gazebo",
"id": "9f828753bddbefc137320868780892f348d900a1",
"size": "11555",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "include/mavlink/v1.0/common/mavlink_msg_vision_speed_estimate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4965296"
},
{
"name": "C++",
"bytes": "352958"
},
{
"name": "CMake",
"bytes": "8485"
},
{
"name": "Protocol Buffer",
"bytes": "2131"
},
{
"name": "Python",
"bytes": "33954"
},
{
"name": "Shell",
"bytes": "337"
}
],
"symlink_target": ""
} |
#ifndef WebDatabaseObserver_h
#define WebDatabaseObserver_h
namespace blink {
class WebString;
class WebDatabaseObserver {
public:
// FIXME: |isSyncDatabse| arguments are alwyas |false|. We should remove them.
virtual void databaseOpened(
const WebString& databaseIdentifier,
const WebString& databaseName,
const WebString& databaseDisplayName,
unsigned long estimatedSize) = 0;
virtual void databaseModified(
const WebString& databaseIdentifier,
const WebString& databaseName) = 0;
virtual void databaseClosed(
const WebString& databaseIdentifier,
const WebString& databaseName) = 0;
virtual void reportOpenDatabaseResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
int errorSite, int webSqlErrorCode, int sqliteErrorCode)
{
reportOpenDatabaseResult(databaseIdentifier, databaseName, false, errorSite, webSqlErrorCode, sqliteErrorCode);
}
virtual void reportChangeVersionResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
int errorSite, int webSqlErrorCode, int sqliteErrorCode)
{
reportChangeVersionResult(databaseIdentifier, databaseName, false, errorSite, webSqlErrorCode, sqliteErrorCode);
}
virtual void reportStartTransactionResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
int errorSite, int webSqlErrorCode, int sqliteErrorCode)
{
reportStartTransactionResult(databaseIdentifier, databaseName, false, errorSite, webSqlErrorCode, sqliteErrorCode);
}
virtual void reportCommitTransactionResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
int errorSite, int webSqlErrorCode, int sqliteErrorCode)
{
reportCommitTransactionResult(databaseIdentifier, databaseName, false, errorSite, webSqlErrorCode, sqliteErrorCode);
}
virtual void reportExecuteStatementResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
int errorSite, int webSqlErrorCode, int sqliteErrorCode)
{
reportExecuteStatementResult(databaseIdentifier, databaseName, false, errorSite, webSqlErrorCode, sqliteErrorCode);
}
virtual void reportVacuumDatabaseResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
int sqliteErrorCode)
{
reportVacuumDatabaseResult(databaseIdentifier, databaseName, false, sqliteErrorCode);
}
// FIXME: Remove these functions once we no longer use isSyncDatabase in Chromium.
virtual void reportOpenDatabaseResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
bool isSyncDatabase,
int errorSite, int webSqlErrorCode, int sqliteErrorCode) { }
virtual void reportChangeVersionResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
bool isSyncDatabase,
int errorSite, int webSqlErrorCode, int sqliteErrorCode) { }
virtual void reportStartTransactionResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
bool isSyncDatabase,
int errorSite, int webSqlErrorCode, int sqliteErrorCode) { }
virtual void reportCommitTransactionResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
bool isSyncDatabase,
int errorSite, int webSqlErrorCode, int sqliteErrorCode) { }
virtual void reportExecuteStatementResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
bool isSyncDatabase,
int errorSite, int webSqlErrorCode, int sqliteErrorCode) { }
virtual void reportVacuumDatabaseResult(
const WebString& databaseIdentifier,
const WebString& databaseName,
bool isSyncDatabase, int sqliteErrorCode) { }
protected:
~WebDatabaseObserver() { }
};
} // namespace blink
#endif // WebDatabaseObserver_h
| {
"content_hash": "27693f0f69be9ab64cec65625f53c02f",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 124,
"avg_line_length": 38.99047619047619,
"alnum_prop": 0.7244748412310699,
"repo_name": "smilusingjavascript/blink",
"id": "9c02f6b26e270e8ba4bdbef155160a8d92adbc93",
"size": "5656",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/platform/WebDatabaseObserver.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "14584"
},
{
"name": "C",
"bytes": "1445607"
},
{
"name": "C++",
"bytes": "40292420"
},
{
"name": "CSS",
"bytes": "536635"
},
{
"name": "Java",
"bytes": "74957"
},
{
"name": "JavaScript",
"bytes": "26642040"
},
{
"name": "Objective-C",
"bytes": "35696"
},
{
"name": "Objective-C++",
"bytes": "341384"
},
{
"name": "PHP",
"bytes": "168951"
},
{
"name": "Perl",
"bytes": "583826"
},
{
"name": "Python",
"bytes": "3802000"
},
{
"name": "Ruby",
"bytes": "141818"
},
{
"name": "Shell",
"bytes": "8923"
},
{
"name": "XSLT",
"bytes": "49099"
}
],
"symlink_target": ""
} |
package podtask
// Concepts that have leaked to where they should not have.
import (
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/registry/etcd"
)
// makePodKey constructs etcd paths to pod items enforcing namespace rules.
func MakePodKey(ctx api.Context, id string) (string, error) {
return etcd.MakeEtcdItemKey(ctx, PodPath, id)
}
| {
"content_hash": "388cd1447b8623f75c65813828a31f30",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 75,
"avg_line_length": 30.23076923076923,
"alnum_prop": 0.7837150127226463,
"repo_name": "ruo91/kubernetes-mesos",
"id": "8afed31e2b6bcd1b76707cb1a0d3bea2ecb5caa4",
"size": "393",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "pkg/scheduler/podtask/leaky.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "437171"
},
{
"name": "HTML",
"bytes": "850"
},
{
"name": "JavaScript",
"bytes": "961"
},
{
"name": "Makefile",
"bytes": "9231"
},
{
"name": "PHP",
"bytes": "1974"
},
{
"name": "Shell",
"bytes": "38344"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_03) on Tue May 08 19:13:23 PDT 2012 -->
<title>All Classes</title>
<meta name="date" content="2012-05-08">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar">All Classes</h1>
<div class="indexContainer">
<ul>
<li><a href="BrowsePath.html" title="class in <Unnamed>">BrowsePath</a></li>
<li><a href="Hooks.html" title="class in <Unnamed>">Hooks</a></li>
<li><a href="LoadFile.html" title="class in <Unnamed>">LoadFile</a></li>
<li><a href="Main.html" title="class in <Unnamed>">Main</a></li>
<li><a href="ReportObject.html" title="class in <Unnamed>">ReportObject</a></li>
<li><a href="SaveObject.html" title="class in <Unnamed>">SaveObject</a></li>
<li><a href="StopWatch.html" title="class in <Unnamed>">StopWatch</a></li>
<li><a href="org/eclipse/wb/swt/SWTResourceManager.html" title="class in org.eclipse.wb.swt">SWTResourceManager</a></li>
<li><a href="TableListener.html" title="class in <Unnamed>">TableListener</a></li>
<li><a href="TaskObject.html" title="class in <Unnamed>">TaskObject</a></li>
<li><a href="TextListener.html" title="class in <Unnamed>">TextListener</a></li>
<li><a href="Tools.html" title="class in <Unnamed>">Tools</a></li>
<li><a href="WriteFile.html" title="class in <Unnamed>">WriteFile</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "9edc66c132c8c3cbd987dd38880f547b",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 120,
"avg_line_length": 52.333333333333336,
"alnum_prop": 0.6777070063694267,
"repo_name": "mittman/timeme",
"id": "ec39ff9fc2f343111b1826a3cddf5aadde432e99",
"size": "1570",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javadoc/allclasses-noframe.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "190023"
},
{
"name": "Shell",
"bytes": "5022"
}
],
"symlink_target": ""
} |
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= _.slugify(appname) %></title>
<link rel="stylesheet" href="styles/style.css">
<script src="src/vendor/require.js" type="text/javascript" charset="utf-8"></script><% if (includeModernizr) { %>
<script src="src/vendor/modernizr.js" type="text/javascript" charset="utf-8"></script><% } %>
<!--build tag-->
<!--do not remove the build script tag. This is automatically replace when the script is built-->
<script src="src/config.js" type="text/javascript" charset="utf-8"></script>
<!--end build tag-->
<script src="src/main.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<!--[if lt IE 10]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<div ui-view></div>
<script>
(function(b, o, i, l, e, r)
{
b.GoogleAnalyticsObject = l;
b[l] || (b[l] =
function()
{
(b[l].q = b[l].q || []).push(arguments)
});
b[l].l = +new Date;
e = o.createElement(i);
r = o.getElementsByTagName(i)[0];
e.src = '//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e, r)
}(window, document, 'script', 'ga'));
ga('create', 'UA-XXXXX-X'); // replace UA-XXXXX-X with your register ID
ga('send', 'pageview');
</script>
</body>
</html>
| {
"content_hash": "6156047c537b544c7b016d16d4ea29ea",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 180,
"avg_line_length": 42.638297872340424,
"alnum_prop": 0.5479041916167665,
"repo_name": "hung-phan/generator-angular-with-require",
"id": "8d5faf9d60f0b87ce7c49d842e149f379457a49a",
"size": "2004",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/templates/index.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3910"
},
{
"name": "JavaScript",
"bytes": "43858"
},
{
"name": "PHP",
"bytes": "806"
},
{
"name": "Perl",
"bytes": "29305"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.